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 Contoso.Core.CloudServices.Web { 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 } }
using OmniBeanEB.Library.Internal; using System; using System.Text; namespace OmniBeanEB.Library { [SmallBasicType] public class TextWindow { private static bool _windowVisible; public static EBPrimitive ForegroundColor { get { TextWindow.VerifyAccess(); return Console.ForegroundColor.ToString(); } set { TextWindow.VerifyAccess(); try { Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), value, true); } catch { } } } public static EBPrimitive BackgroundColor { get { TextWindow.VerifyAccess(); return Console.BackgroundColor.ToString(); } set { TextWindow.VerifyAccess(); try { Console.BackgroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), value, true); } catch { } } } public static EBPrimitive CursorLeft { get { TextWindow.VerifyAccess(); return new EBPrimitive(Console.CursorLeft); } set { TextWindow.VerifyAccess(); Console.CursorLeft = value; } } public static EBPrimitive CursorTop { get { TextWindow.VerifyAccess(); return new EBPrimitive(Console.CursorTop); } set { TextWindow.VerifyAccess(); Console.CursorTop = value; } } public static EBPrimitive Left { get { TextWindow.VerifyAccess(); IntPtr consoleWindow = NativeHelper.GetConsoleWindow(); RECT rECT; NativeHelper.GetWindowRect(consoleWindow, out rECT); return rECT.Left; } set { TextWindow.VerifyAccess(); IntPtr consoleWindow = NativeHelper.GetConsoleWindow(); RECT rECT; NativeHelper.GetWindowRect(consoleWindow, out rECT); NativeHelper.SetWindowPos(consoleWindow, IntPtr.Zero, value, rECT.Top, 0, 0, 1u); } } public static EBPrimitive Title { get { TextWindow.VerifyAccess(); return new EBPrimitive(Console.Title); } set { TextWindow.VerifyAccess(); Console.Title = value; } } public static EBPrimitive Top { get { TextWindow.VerifyAccess(); IntPtr consoleWindow = NativeHelper.GetConsoleWindow(); RECT rECT; NativeHelper.GetWindowRect(consoleWindow, out rECT); return rECT.Top; } set { TextWindow.VerifyAccess(); IntPtr consoleWindow = NativeHelper.GetConsoleWindow(); RECT rECT; NativeHelper.GetWindowRect(consoleWindow, out rECT); NativeHelper.SetWindowPos(consoleWindow, IntPtr.Zero, rECT.Left, value, 0, 0, 1u); } } public static void Show() { if (!TextWindow._windowVisible) { IntPtr consoleWindow = NativeHelper.GetConsoleWindow(); if (consoleWindow == IntPtr.Zero) { NativeHelper.AllocConsole(); } NativeHelper.ShowWindow(consoleWindow, 8); TextWindow._windowVisible = true; } } public static void Hide() { if (TextWindow._windowVisible) { IntPtr consoleWindow = NativeHelper.GetConsoleWindow(); if (consoleWindow != IntPtr.Zero) { NativeHelper.ShowWindow(consoleWindow, 0); } TextWindow._windowVisible = false; } } public static void Clear() { TextWindow.VerifyAccess(); Console.Clear(); } public static void Pause() { TextWindow.VerifyAccess(); Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); } public static void PauseIfVisible() { if (TextWindow._windowVisible) { TextWindow.Pause(); } } public static void PauseWithoutMessage() { TextWindow.VerifyAccess(); Console.ReadKey(true); } public static EBPrimitive Read() { TextWindow.VerifyAccess(); return new EBPrimitive(Console.ReadLine()); } [HideFromIntellisense] public static EBPrimitive ReadKey() { TextWindow.VerifyAccess(); return new string(Console.ReadKey(true).KeyChar, 1); } public static EBPrimitive ReadNumber() { TextWindow.VerifyAccess(); StringBuilder stringBuilder = new StringBuilder(); bool flag = false; int num = 0; while (true) { ConsoleKeyInfo consoleKeyInfo = Console.ReadKey(true); char c = consoleKeyInfo.KeyChar; bool flag2 = false; if (c == '-' && num == 0) { flag2 = true; } else if (c == '.' && !flag) { flag = true; flag2 = true; } else if (c >= '0' && c <= '9') { flag2 = true; } if (flag2) { Console.Write(c); stringBuilder.Append(c); num++; } else if (num > 0 && consoleKeyInfo.Key == ConsoleKey.Backspace) { Console.CursorLeft--; Console.Write(" "); Console.CursorLeft--; num--; c = stringBuilder[num]; if (c == '.') { flag = false; } stringBuilder.Remove(num, 1); } else if (consoleKeyInfo.Key == ConsoleKey.Enter) { break; } } Console.WriteLine(); if (stringBuilder.Length == 0) { return new EBPrimitive(0); } return new EBPrimitive(stringBuilder.ToString()); } public static void WriteLine(EBPrimitive data) { TextWindow.VerifyAccess(); Console.WriteLine((string)data); } public static void Write(EBPrimitive data) { TextWindow.VerifyAccess(); Console.Write((string)data); } private static void VerifyAccess() { if (!TextWindow._windowVisible) { TextWindow.Show(); } } } }
using System.Collections.Generic; using System.Xml.Linq; using Orchard.ContentManagement.Handlers; using Orchard.ContentManagement.MetaData.Models; using Orchard.Indexing; namespace Orchard.ContentManagement { /// <summary> /// Content management functionality to deal with Orchard content items and their parts /// </summary> public interface IContentManager : IDependency { IEnumerable<ContentTypeDefinition> GetContentTypeDefinitions(); /// <summary> /// Instantiates a new content item with the specified type /// </summary> /// <remarks> /// The content item is not yet persisted! /// </remarks> /// <param name="contentType">The name of the content type</param> ContentItem New(string contentType); /// <summary> /// Creates (persists) a new content item /// </summary> /// <param name="contentItem">The content instance filled with all necessary data</param> void Create(ContentItem contentItem); /// <summary> /// Creates (persists) a new content item with the specified version /// </summary> /// <param name="contentItem">The content instance filled with all necessary data</param> /// <param name="options">The version to create the item with</param> void Create(ContentItem contentItem, VersionOptions options); /// <summary> /// Makes a clone of the content item /// </summary> /// <param name="contentItem">The content item to clone</param> /// <returns>Clone of the item</returns> ContentItem Clone(ContentItem contentItem); /// <summary> /// Rolls back the specified content item by creating a new version based on the specified version. /// </summary> /// <param name="contentItem">The content item to roll back.</param> /// <param name="options">The version to roll back to. Either specify the version record id, version number, and IsPublished to publish the new version.</param> /// <returns>Returns the latest version of the content item, which is based on the specified version.</returns> ContentItem Restore(ContentItem contentItem, VersionOptions options); /// <summary> /// Gets the content item with the specified id /// </summary> /// <param name="id">Numeric id of the content item</param> ContentItem Get(int id); /// <summary> /// Gets the content item with the specified id and version /// </summary> /// <param name="id">Numeric id of the content item</param> /// <param name="options">The version option</param> ContentItem Get(int id, VersionOptions options); /// <summary> /// Gets the content item with the specified id, version and query hints /// </summary> /// <param name="id">Numeric id of the content item</param> /// <param name="options">The version option</param> /// <param name="hints">The query hints</param> ContentItem Get(int id, VersionOptions options, QueryHints hints); /// <summary> /// Gets all versions of the content item specified with its id /// </summary> /// <param name="id">Numeric id of the content item</param> IEnumerable<ContentItem> GetAllVersions(int id); IEnumerable<T> GetMany<T>(IEnumerable<int> ids, VersionOptions options, QueryHints hints) where T : class, IContent; IEnumerable<T> GetManyByVersionId<T>(IEnumerable<int> versionRecordIds, QueryHints hints) where T : class, IContent; IEnumerable<ContentItem> GetManyByVersionId(IEnumerable<int> versionRecordIds, QueryHints hints); void Publish(ContentItem contentItem); void Unpublish(ContentItem contentItem); void Remove(ContentItem contentItem); /// <summary> /// Deletes the draft version of the content item permanently. /// </summary> /// <param name="contentItem">The content item of which the draft version will be deleted.</param> void DiscardDraft(ContentItem contentItem); /// <summary> /// Permanently deletes the specified content item, including all of its content part records. /// </summary> void Destroy(ContentItem contentItem); void Index(ContentItem contentItem, IDocumentIndex documentIndex); XElement Export(ContentItem contentItem); void Import(XElement element, ImportContentSession importContentSession); void CompleteImport(XElement element, ImportContentSession importContentSession); /// <summary> /// Clears the current referenced content items /// </summary> void Clear(); /// <summary> /// Query for arbitrary content items /// </summary> IContentQuery<ContentItem> Query(); IHqlQuery HqlQuery(); ContentItemMetadata GetItemMetadata(IContent contentItem); IEnumerable<GroupInfo> GetEditorGroupInfos(IContent contentItem); IEnumerable<GroupInfo> GetDisplayGroupInfos(IContent contentItem); GroupInfo GetEditorGroupInfo(IContent contentItem, string groupInfoId); GroupInfo GetDisplayGroupInfo(IContent contentItem, string groupInfoId); ContentItem ResolveIdentity(ContentIdentity contentIdentity); /// <summary> /// Builds the display shape of the specified content item /// </summary> /// <param name="content">The content item to use</param> /// <param name="displayType">The display type (e.g. Summary, Detail) to use</param> /// <param name="groupId">Id of the display group (stored in the content item's metadata)</param> /// <returns>The display shape</returns> dynamic BuildDisplay(IContent content, string displayType = "", string groupId = ""); /// <summary> /// Builds the editor shape of the specified content item /// </summary> /// <param name="content">The content item to use</param> /// <param name="groupId">Id of the editor group (stored in the content item's metadata)</param> /// <returns>The editor shape</returns> dynamic BuildEditor(IContent content, string groupId = ""); /// <summary> /// Updates the content item and its editor shape with new data through an IUpdateModel /// </summary> /// <param name="content">The content item to update</param> /// <param name="updater">The updater to use for updating</param> /// <param name="groupId">Id of the editor group (stored in the content item's metadata)</param> /// <returns>The updated editor shape</returns> dynamic UpdateEditor(IContent content, IUpdateModel updater, string groupId = ""); } public interface IContentDisplay : IDependency { dynamic BuildDisplay(IContent content, string displayType = "", string groupId = ""); dynamic BuildEditor(IContent content, string groupId = ""); dynamic UpdateEditor(IContent content, IUpdateModel updater, string groupId = ""); } public class VersionOptions { /// <summary> /// Gets the latest version. /// </summary> public static VersionOptions Latest { get { return new VersionOptions { IsLatest = true }; } } /// <summary> /// Gets the latest published version. /// </summary> public static VersionOptions Published { get { return new VersionOptions { IsPublished = true }; } } /// <summary> /// Gets the latest draft version. /// </summary> public static VersionOptions Draft { get { return new VersionOptions { IsDraft = true }; } } /// <summary> /// Gets the latest version and creates a new version draft based on it. /// </summary> public static VersionOptions DraftRequired { get { return new VersionOptions { IsDraft = true, IsDraftRequired = true }; } } /// <summary> /// Gets all versions. /// </summary> public static VersionOptions AllVersions { get { return new VersionOptions { IsAllVersions = true }; } } /// <summary> /// Gets a specific version based on its number. /// </summary> public static VersionOptions Number(int version) { return new VersionOptions { VersionNumber = version }; } /// <summary> /// Gets a specific version based on the version record identifier. /// </summary> public static VersionOptions VersionRecord(int id) { return new VersionOptions { VersionRecordId = id }; } /// <summary> /// Creates a new version based on the specified version number. /// </summary> public static VersionOptions Restore(int version, bool publish = false) { return new VersionOptions { VersionNumber = version, IsPublished = publish}; } public bool IsLatest { get; private set; } public bool IsPublished { get; private set; } public bool IsDraft { get; private set; } public bool IsDraftRequired { get; private set; } public bool IsAllVersions { get; private set; } public int VersionNumber { get; private set; } public int VersionRecordId { get; private set; } } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System.Globalization { public static class __HebrewCalendar { public static IObservable<System.DateTime> AddMonths( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue, IObservable<System.DateTime> time, IObservable<System.Int32> months) { return Observable.Zip(HebrewCalendarValue, time, months, (HebrewCalendarValueLambda, timeLambda, monthsLambda) => HebrewCalendarValueLambda.AddMonths(timeLambda, monthsLambda)); } public static IObservable<System.DateTime> AddYears( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue, IObservable<System.DateTime> time, IObservable<System.Int32> years) { return Observable.Zip(HebrewCalendarValue, time, years, (HebrewCalendarValueLambda, timeLambda, yearsLambda) => HebrewCalendarValueLambda.AddYears(timeLambda, yearsLambda)); } public static IObservable<System.Int32> GetDayOfMonth( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue, IObservable<System.DateTime> time) { return Observable.Zip(HebrewCalendarValue, time, (HebrewCalendarValueLambda, timeLambda) => HebrewCalendarValueLambda.GetDayOfMonth(timeLambda)); } public static IObservable<System.DayOfWeek> GetDayOfWeek( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue, IObservable<System.DateTime> time) { return Observable.Zip(HebrewCalendarValue, time, (HebrewCalendarValueLambda, timeLambda) => HebrewCalendarValueLambda.GetDayOfWeek(timeLambda)); } public static IObservable<System.Int32> GetDayOfYear( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue, IObservable<System.DateTime> time) { return Observable.Zip(HebrewCalendarValue, time, (HebrewCalendarValueLambda, timeLambda) => HebrewCalendarValueLambda.GetDayOfYear(timeLambda)); } public static IObservable<System.Int32> GetDaysInMonth( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue, IObservable<System.Int32> year, IObservable<System.Int32> month, IObservable<System.Int32> era) { return Observable.Zip(HebrewCalendarValue, year, month, era, (HebrewCalendarValueLambda, yearLambda, monthLambda, eraLambda) => HebrewCalendarValueLambda.GetDaysInMonth(yearLambda, monthLambda, eraLambda)); } public static IObservable<System.Int32> GetDaysInYear( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue, IObservable<System.Int32> year, IObservable<System.Int32> era) { return Observable.Zip(HebrewCalendarValue, year, era, (HebrewCalendarValueLambda, yearLambda, eraLambda) => HebrewCalendarValueLambda.GetDaysInYear(yearLambda, eraLambda)); } public static IObservable<System.Int32> GetEra( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue, IObservable<System.DateTime> time) { return Observable.Zip(HebrewCalendarValue, time, (HebrewCalendarValueLambda, timeLambda) => HebrewCalendarValueLambda.GetEra(timeLambda)); } public static IObservable<System.Int32> GetMonth( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue, IObservable<System.DateTime> time) { return Observable.Zip(HebrewCalendarValue, time, (HebrewCalendarValueLambda, timeLambda) => HebrewCalendarValueLambda.GetMonth(timeLambda)); } public static IObservable<System.Int32> GetMonthsInYear( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue, IObservable<System.Int32> year, IObservable<System.Int32> era) { return Observable.Zip(HebrewCalendarValue, year, era, (HebrewCalendarValueLambda, yearLambda, eraLambda) => HebrewCalendarValueLambda.GetMonthsInYear(yearLambda, eraLambda)); } public static IObservable<System.Int32> GetYear( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue, IObservable<System.DateTime> time) { return Observable.Zip(HebrewCalendarValue, time, (HebrewCalendarValueLambda, timeLambda) => HebrewCalendarValueLambda.GetYear(timeLambda)); } public static IObservable<System.Boolean> IsLeapDay( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue, IObservable<System.Int32> year, IObservable<System.Int32> month, IObservable<System.Int32> day, IObservable<System.Int32> era) { return Observable.Zip(HebrewCalendarValue, year, month, day, era, (HebrewCalendarValueLambda, yearLambda, monthLambda, dayLambda, eraLambda) => HebrewCalendarValueLambda.IsLeapDay(yearLambda, monthLambda, dayLambda, eraLambda)); } public static IObservable<System.Int32> GetLeapMonth( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue, IObservable<System.Int32> year, IObservable<System.Int32> era) { return Observable.Zip(HebrewCalendarValue, year, era, (HebrewCalendarValueLambda, yearLambda, eraLambda) => HebrewCalendarValueLambda.GetLeapMonth(yearLambda, eraLambda)); } public static IObservable<System.Boolean> IsLeapMonth( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue, IObservable<System.Int32> year, IObservable<System.Int32> month, IObservable<System.Int32> era) { return Observable.Zip(HebrewCalendarValue, year, month, era, (HebrewCalendarValueLambda, yearLambda, monthLambda, eraLambda) => HebrewCalendarValueLambda.IsLeapMonth(yearLambda, monthLambda, eraLambda)); } public static IObservable<System.Boolean> IsLeapYear( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue, IObservable<System.Int32> year, IObservable<System.Int32> era) { return Observable.Zip(HebrewCalendarValue, year, era, (HebrewCalendarValueLambda, yearLambda, eraLambda) => HebrewCalendarValueLambda.IsLeapYear(yearLambda, eraLambda)); } public static IObservable<System.DateTime> ToDateTime( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue, IObservable<System.Int32> year, IObservable<System.Int32> month, IObservable<System.Int32> day, IObservable<System.Int32> hour, IObservable<System.Int32> minute, IObservable<System.Int32> second, IObservable<System.Int32> millisecond, IObservable<System.Int32> era) { return Observable.Zip(HebrewCalendarValue, year, month, day, hour, minute, second, millisecond, era, (HebrewCalendarValueLambda, yearLambda, monthLambda, dayLambda, hourLambda, minuteLambda, secondLambda, millisecondLambda, eraLambda) => HebrewCalendarValueLambda.ToDateTime(yearLambda, monthLambda, dayLambda, hourLambda, minuteLambda, secondLambda, millisecondLambda, eraLambda)); } public static IObservable<System.Int32> ToFourDigitYear( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue, IObservable<System.Int32> year) { return Observable.Zip(HebrewCalendarValue, year, (HebrewCalendarValueLambda, yearLambda) => HebrewCalendarValueLambda.ToFourDigitYear(yearLambda)); } public static IObservable<System.DateTime> get_MinSupportedDateTime( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue) { return Observable.Select(HebrewCalendarValue, (HebrewCalendarValueLambda) => HebrewCalendarValueLambda.MinSupportedDateTime); } public static IObservable<System.DateTime> get_MaxSupportedDateTime( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue) { return Observable.Select(HebrewCalendarValue, (HebrewCalendarValueLambda) => HebrewCalendarValueLambda.MaxSupportedDateTime); } public static IObservable<System.Globalization.CalendarAlgorithmType> get_AlgorithmType( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue) { return Observable.Select(HebrewCalendarValue, (HebrewCalendarValueLambda) => HebrewCalendarValueLambda.AlgorithmType); } public static IObservable<System.Int32[]> get_Eras( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue) { return Observable.Select(HebrewCalendarValue, (HebrewCalendarValueLambda) => HebrewCalendarValueLambda.Eras); } public static IObservable<System.Int32> get_TwoDigitYearMax( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue) { return Observable.Select(HebrewCalendarValue, (HebrewCalendarValueLambda) => HebrewCalendarValueLambda.TwoDigitYearMax); } public static IObservable<System.Reactive.Unit> set_TwoDigitYearMax( this IObservable<System.Globalization.HebrewCalendar> HebrewCalendarValue, IObservable<System.Int32> value) { return ObservableExt.ZipExecute(HebrewCalendarValue, value, (HebrewCalendarValueLambda, valueLambda) => HebrewCalendarValueLambda.TwoDigitYearMax = valueLambda); } } }
using UnityEngine; using System.Collections; namespace RootMotion.FinalIK { /// <summary> /// The base abstract class for all %IK solvers /// </summary> [System.Serializable] public abstract class IKSolver { #region Main Interface /// <summary> /// Determines whether this instance is valid or not. If log == true, will log a warning message in case of an invalid solver. /// </summary> public abstract bool IsValid(bool log); /// <summary> /// Initiate the solver with specified root Transform. Use only if this %IKSolver is not a member of an %IK component. /// </summary> public void Initiate(Transform root) { if (OnPreInitiate != null) OnPreInitiate(); if (root == null) Debug.LogError("Initiating IKSolver with null root Transform."); this.root = root; initiated = false; if (!IsValid(Application.isPlaying)) return; OnInitiate(); StoreDefaultLocalState(); initiated = true; firstInitiation = false; if (OnPostInitiate != null) OnPostInitiate(); } /// <summary> /// Updates the %IK solver. Use only if this %IKSolver is not a member of an %IK component or the %IK component has been disabled and you intend to manually control the updating. /// </summary> public void Update() { if (OnPreUpdate != null) OnPreUpdate(); if (firstInitiation) LogWarning("Trying to update IK solver before initiating it. If you intended to disable the IK component to manage it's updating, use ik.Disable() instead of ik.enabled = false, the latter does not guarantee solver initiation."); if (!initiated) return; OnUpdate(); if (OnPostUpdate != null) OnPostUpdate(); } /// <summary> /// The %IK position. /// </summary> [HideInInspector] public Vector3 IKPosition; /// <summary> /// The %IK position weight. /// </summary> [Range(0f, 1f)] public float IKPositionWeight = 1f; /// <summary> /// Gets the %IK position. NOTE: You are welcome to read IKPosition directly, this method is here only to match the Unity's built in %IK API. /// </summary> public Vector3 GetIKPosition() { return IKPosition; } /// <summary> /// Sets the %IK position. NOTE: You are welcome to set IKPosition directly, this method is here only to match the Unity's built in %IK API. /// </summary> public void SetIKPosition(Vector3 position) { IKPosition = position; } /// <summary> /// Gets the %IK position weight. NOTE: You are welcome to read IKPositionWeight directly, this method is here only to match the Unity's built in %IK API. /// </summary> public float GetIKPositionWeight() { return IKPositionWeight; } /// <summary> /// Sets the %IK position weight. NOTE: You are welcome to set IKPositionWeight directly, this method is here only to match the Unity's built in %IK API. /// </summary> public void SetIKPositionWeight(float weight) { IKPositionWeight = Mathf.Clamp(weight, 0f, 1f); } /// <summary> /// Gets the root Transform. /// </summary> public Transform GetRoot() { return root; } /// <summary> /// Gets a value indicating whether this <see cref="IKSolver"/> has successfully initiated. /// </summary> public bool initiated { get; private set; } /// <summary> /// Gets all the points used by the solver. /// </summary> public abstract IKSolver.Point[] GetPoints(); /// <summary> /// Gets the point with the specified Transform. /// </summary> public abstract IKSolver.Point GetPoint(Transform transform); /// <summary> /// Fixes all the Transforms used by the solver to their initial state. /// </summary> public abstract void FixTransforms(); /// <summary> /// Stores the default local state for the bones used by the solver. /// </summary> public abstract void StoreDefaultLocalState(); /// <summary> /// The most basic element type in the %IK chain that all other types extend from. /// </summary> [System.Serializable] public class Point { /// <summary> /// The transform. /// </summary> public Transform transform; /// <summary> /// The weight of this bone in the solver. /// </summary> [Range(0f, 1f)] public float weight = 1f; /// <summary> /// Virtual position in the %IK solver. /// </summary> public Vector3 solverPosition; /// <summary> /// Virtual rotation in the %IK solver. /// </summary> public Quaternion solverRotation = Quaternion.identity; /// <summary> /// The default local position of the Transform. /// </summary> public Vector3 defaultLocalPosition; /// <summary> /// The default local rotation of the Transform. /// </summary> public Quaternion defaultLocalRotation; /// <summary> /// Stores the default local state of the point. /// </summary> public void StoreDefaultLocalState() { defaultLocalPosition = transform.localPosition; defaultLocalRotation = transform.localRotation; } /// <summary> /// Fixes the transform to it's default local state. /// </summary> public void FixTransform() { if (transform.localPosition != defaultLocalPosition) transform.localPosition = defaultLocalPosition; if (transform.localRotation != defaultLocalRotation) transform.localRotation = defaultLocalRotation; } } /// <summary> /// %Bone type of element in the %IK chain. Used in the case of skeletal Transform hierarchies. /// </summary> [System.Serializable] public class Bone: Point { /// <summary> /// The length of the bone. /// </summary> public float length; /// <summary> /// Local axis to target/child bone. /// </summary> public Vector3 axis = -Vector3.right; /// <summary> /// Gets the rotation limit component from the Transform if there is any. /// </summary> public RotationLimit rotationLimit { get { if (!isLimited) return null; if (_rotationLimit == null) _rotationLimit = transform.GetComponent<RotationLimit>(); isLimited = _rotationLimit != null; return _rotationLimit; } set { _rotationLimit = value; isLimited = value != null; } } /* * Swings the Transform's axis towards the swing target * */ public void Swing(Vector3 swingTarget, float weight = 1f) { if (weight <= 0f) return; Quaternion r = Quaternion.FromToRotation(transform.rotation * axis, swingTarget - transform.position); if (weight >= 1f) { transform.rotation = r * transform.rotation; return; } transform.rotation = Quaternion.Lerp(Quaternion.identity, r, weight) * transform.rotation; } /* * Swings the Transform's axis towards the swing target * */ public Quaternion GetSolverSwing(Vector3 swingTarget, float weight = 1f) { if (weight <= 0f) return Quaternion.identity; Quaternion r = Quaternion.FromToRotation(solverRotation * axis, swingTarget - solverPosition); if (weight >= 1f) return r; return Quaternion.Lerp(Quaternion.identity, r, weight); } /* * Moves the bone to the solver position * */ public void SetToSolverPosition() { transform.position = solverPosition; } public Bone() {} public Bone (Transform transform) { this.transform = transform; } public Bone (Transform transform, float weight) { this.transform = transform; this.weight = weight; } private RotationLimit _rotationLimit; private bool isLimited = true; } /// <summary> /// %Node type of element in the %IK chain. Used in the case of mixed/non-hierarchical %IK systems /// </summary> [System.Serializable] public class Node: Point { /// <summary> /// Distance to child node. /// </summary> public float length; /// <summary> /// The effector position weight. /// </summary> public float effectorPositionWeight; /// <summary> /// The effector rotation weight. /// </summary> public float effectorRotationWeight; /// <summary> /// Position offset. /// </summary> public Vector3 offset; public Node() {} public Node (Transform transform) { this.transform = transform; } public Node (Transform transform, float weight) { this.transform = transform; this.weight = weight; } } /// <summary> /// Delegates solver update events. /// </summary> public delegate void UpdateDelegate(); /// <summary> /// Delegates solver iteration events. /// </summary> public delegate void IterationDelegate(int i); /// <summary> /// Called before initiating the solver. /// </summary> public UpdateDelegate OnPreInitiate; /// <summary> /// Called after initiating the solver. /// </summary> public UpdateDelegate OnPostInitiate; /// <summary> /// Called before updating. /// </summary> public UpdateDelegate OnPreUpdate; /// <summary> /// Called after writing the solved pose /// </summary> public UpdateDelegate OnPostUpdate; #endregion Main Interface protected abstract void OnInitiate(); protected abstract void OnUpdate(); protected bool firstInitiation = true; [SerializeField] protected Transform root; protected void LogWarning(string message) { Warning.Log(message, root, true); } #region Class Methods /// <summary> /// Checks if an array of objects contains any duplicates. /// </summary> public static Transform ContainsDuplicateBone(Bone[] bones) { for (int i = 0; i < bones.Length; i++) { for (int i2 = 0; i2 < bones.Length; i2++) { if (i != i2 && bones[i].transform == bones[i2].transform) return bones[i].transform; } } return null; } /* * Make sure the bones are in valid Hierarchy * */ public static bool HierarchyIsValid(IKSolver.Bone[] bones) { for (int i = 1; i < bones.Length; i++) { // If parent bone is not an ancestor of bone, the hierarchy is invalid if (!Hierarchy.IsAncestor(bones[i].transform, bones[i - 1].transform)) { return false; } } return true; } #endregion Class Methods } }
namespace java.lang { [global::MonoJavaBridge.JavaClass()] public sealed partial class Long : java.lang.Number, Comparable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal Long(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public static int numberOfLeadingZeros(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m0.native == global::System.IntPtr.Zero) global::java.lang.Long._m0 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "numberOfLeadingZeros", "(J)I"); return @__env.CallStaticIntMethod(java.lang.Long.staticClass, global::java.lang.Long._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; public static int numberOfTrailingZeros(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m1.native == global::System.IntPtr.Zero) global::java.lang.Long._m1 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "numberOfTrailingZeros", "(J)I"); return @__env.CallStaticIntMethod(java.lang.Long.staticClass, global::java.lang.Long._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m2; public static int bitCount(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m2.native == global::System.IntPtr.Zero) global::java.lang.Long._m2 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "bitCount", "(J)I"); return @__env.CallStaticIntMethod(java.lang.Long.staticClass, global::java.lang.Long._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m3; public sealed override bool equals(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.lang.Long.staticClass, "equals", "(Ljava/lang/Object;)Z", ref global::java.lang.Long._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m4; public sealed override global::java.lang.String toString() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.lang.Long.staticClass, "toString", "()Ljava/lang/String;", ref global::java.lang.Long._m4) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m5; public static global::java.lang.String toString(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m5.native == global::System.IntPtr.Zero) global::java.lang.Long._m5 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "toString", "(J)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m6; public static global::java.lang.String toString(long arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m6.native == global::System.IntPtr.Zero) global::java.lang.Long._m6 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "toString", "(JI)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m7; public sealed override int hashCode() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.lang.Long.staticClass, "hashCode", "()I", ref global::java.lang.Long._m7); } private static global::MonoJavaBridge.MethodId _m8; public static long reverseBytes(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m8.native == global::System.IntPtr.Zero) global::java.lang.Long._m8 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "reverseBytes", "(J)J"); return @__env.CallStaticLongMethod(java.lang.Long.staticClass, global::java.lang.Long._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m9; public int compareTo(java.lang.Long arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.lang.Long.staticClass, "compareTo", "(Ljava/lang/Long;)I", ref global::java.lang.Long._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m10; public int compareTo(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.lang.Long.staticClass, "compareTo", "(Ljava/lang/Object;)I", ref global::java.lang.Long._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m11; public static global::java.lang.Long getLong(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m11.native == global::System.IntPtr.Zero) global::java.lang.Long._m11 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "getLong", "(Ljava/lang/String;)Ljava/lang/Long;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Long>(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Long; } private static global::MonoJavaBridge.MethodId _m12; public static global::java.lang.Long getLong(java.lang.String arg0, long arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m12.native == global::System.IntPtr.Zero) global::java.lang.Long._m12 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "getLong", "(Ljava/lang/String;J)Ljava/lang/Long;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Long>(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Long; } private static global::MonoJavaBridge.MethodId _m13; public static global::java.lang.Long getLong(java.lang.String arg0, java.lang.Long arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m13.native == global::System.IntPtr.Zero) global::java.lang.Long._m13 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "getLong", "(Ljava/lang/String;Ljava/lang/Long;)Ljava/lang/Long;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Long>(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Long; } private static global::MonoJavaBridge.MethodId _m14; public static global::java.lang.String toHexString(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m14.native == global::System.IntPtr.Zero) global::java.lang.Long._m14 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "toHexString", "(J)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m15; public static global::java.lang.Long valueOf(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m15.native == global::System.IntPtr.Zero) global::java.lang.Long._m15 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "valueOf", "(J)Ljava/lang/Long;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Long>(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Long; } private static global::MonoJavaBridge.MethodId _m16; public static global::java.lang.Long valueOf(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m16.native == global::System.IntPtr.Zero) global::java.lang.Long._m16 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "valueOf", "(Ljava/lang/String;)Ljava/lang/Long;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Long>(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Long; } private static global::MonoJavaBridge.MethodId _m17; public static global::java.lang.Long valueOf(java.lang.String arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m17.native == global::System.IntPtr.Zero) global::java.lang.Long._m17 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "valueOf", "(Ljava/lang/String;I)Ljava/lang/Long;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Long>(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Long; } private static global::MonoJavaBridge.MethodId _m18; public static global::java.lang.Long decode(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m18.native == global::System.IntPtr.Zero) global::java.lang.Long._m18 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "decode", "(Ljava/lang/String;)Ljava/lang/Long;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Long>(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Long; } private static global::MonoJavaBridge.MethodId _m19; public static long reverse(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m19.native == global::System.IntPtr.Zero) global::java.lang.Long._m19 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "reverse", "(J)J"); return @__env.CallStaticLongMethod(java.lang.Long.staticClass, global::java.lang.Long._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m20; public sealed override byte byteValue() { return global::MonoJavaBridge.JavaBridge.CallByteMethod(this, global::java.lang.Long.staticClass, "byteValue", "()B", ref global::java.lang.Long._m20); } private static global::MonoJavaBridge.MethodId _m21; public sealed override short shortValue() { return global::MonoJavaBridge.JavaBridge.CallShortMethod(this, global::java.lang.Long.staticClass, "shortValue", "()S", ref global::java.lang.Long._m21); } private static global::MonoJavaBridge.MethodId _m22; public sealed override int intValue() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.lang.Long.staticClass, "intValue", "()I", ref global::java.lang.Long._m22); } private static global::MonoJavaBridge.MethodId _m23; public sealed override long longValue() { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.lang.Long.staticClass, "longValue", "()J", ref global::java.lang.Long._m23); } private static global::MonoJavaBridge.MethodId _m24; public sealed override float floatValue() { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::java.lang.Long.staticClass, "floatValue", "()F", ref global::java.lang.Long._m24); } private static global::MonoJavaBridge.MethodId _m25; public sealed override double doubleValue() { return global::MonoJavaBridge.JavaBridge.CallDoubleMethod(this, global::java.lang.Long.staticClass, "doubleValue", "()D", ref global::java.lang.Long._m25); } private static global::MonoJavaBridge.MethodId _m26; public static global::java.lang.String toOctalString(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m26.native == global::System.IntPtr.Zero) global::java.lang.Long._m26 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "toOctalString", "(J)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m27; public static global::java.lang.String toBinaryString(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m27.native == global::System.IntPtr.Zero) global::java.lang.Long._m27 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "toBinaryString", "(J)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m28; public static long highestOneBit(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m28.native == global::System.IntPtr.Zero) global::java.lang.Long._m28 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "highestOneBit", "(J)J"); return @__env.CallStaticLongMethod(java.lang.Long.staticClass, global::java.lang.Long._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m29; public static long lowestOneBit(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m29.native == global::System.IntPtr.Zero) global::java.lang.Long._m29 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "lowestOneBit", "(J)J"); return @__env.CallStaticLongMethod(java.lang.Long.staticClass, global::java.lang.Long._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m30; public static long rotateLeft(long arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m30.native == global::System.IntPtr.Zero) global::java.lang.Long._m30 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "rotateLeft", "(JI)J"); return @__env.CallStaticLongMethod(java.lang.Long.staticClass, global::java.lang.Long._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m31; public static long rotateRight(long arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m31.native == global::System.IntPtr.Zero) global::java.lang.Long._m31 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "rotateRight", "(JI)J"); return @__env.CallStaticLongMethod(java.lang.Long.staticClass, global::java.lang.Long._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m32; public static int signum(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m32.native == global::System.IntPtr.Zero) global::java.lang.Long._m32 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "signum", "(J)I"); return @__env.CallStaticIntMethod(java.lang.Long.staticClass, global::java.lang.Long._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m33; public static long parseLong(java.lang.String arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m33.native == global::System.IntPtr.Zero) global::java.lang.Long._m33 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "parseLong", "(Ljava/lang/String;I)J"); return @__env.CallStaticLongMethod(java.lang.Long.staticClass, global::java.lang.Long._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m34; public static long parseLong(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m34.native == global::System.IntPtr.Zero) global::java.lang.Long._m34 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "parseLong", "(Ljava/lang/String;)J"); return @__env.CallStaticLongMethod(java.lang.Long.staticClass, global::java.lang.Long._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m35; public Long(long arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m35.native == global::System.IntPtr.Zero) global::java.lang.Long._m35 = @__env.GetMethodIDNoThrow(global::java.lang.Long.staticClass, "<init>", "(J)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Long.staticClass, global::java.lang.Long._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m36; public Long(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.Long._m36.native == global::System.IntPtr.Zero) global::java.lang.Long._m36 = @__env.GetMethodIDNoThrow(global::java.lang.Long.staticClass, "<init>", "(Ljava/lang/String;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Long.staticClass, global::java.lang.Long._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } public static long MIN_VALUE { get { return -9223372036854775808L; } } public static long MAX_VALUE { get { return 9223372036854775807L; } } internal static global::MonoJavaBridge.FieldId _TYPE6376; public static global::java.lang.Class TYPE { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Class>(@__env.GetStaticObjectField(global::java.lang.Long.staticClass, _TYPE6376)) as java.lang.Class; } } public static int SIZE { get { return 64; } } static Long() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.lang.Long.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/Long")); global::java.lang.Long._TYPE6376 = @__env.GetStaticFieldIDNoThrow(global::java.lang.Long.staticClass, "TYPE", "Ljava/lang/Class;"); } } }
using UnityEngine; using System.Collections; [AddComponentMenu("2D Toolkit/Sprite/tk2dTiledSprite")] [RequireComponent(typeof(MeshRenderer))] [RequireComponent(typeof(MeshFilter))] [ExecuteInEditMode] /// <summary> /// Sprite implementation that tiles a sprite to fill given dimensions. /// </summary> public class tk2dTiledSprite : tk2dBaseSprite { Mesh mesh; Vector2[] meshUvs; Vector3[] meshVertices; Color32[] meshColors; Vector3[] meshNormals = null; Vector4[] meshTangents = null; int[] meshIndices; [SerializeField] Vector2 _dimensions = new Vector2(50.0f, 50.0f); [SerializeField] Anchor _anchor = Anchor.LowerLeft; /// <summary> /// Gets or sets the dimensions. /// </summary> /// <value> /// Use this to change the dimensions of the sliced sprite in pixel units /// </value> public Vector2 dimensions { get { return _dimensions; } set { if (value != _dimensions) { _dimensions = value; UpdateVertices(); #if UNITY_EDITOR EditMode__CreateCollider(); #endif UpdateCollider(); } } } /// <summary> /// The anchor position for this tiled sprite /// </summary> public Anchor anchor { get { return _anchor; } set { if (value != _anchor) { _anchor = value; UpdateVertices(); #if UNITY_EDITOR EditMode__CreateCollider(); #endif UpdateCollider(); } } } [SerializeField] protected bool _createBoxCollider = false; /// <summary> /// Create a trimmed box collider for this sprite /// </summary> public bool CreateBoxCollider { get { return _createBoxCollider; } set { if (_createBoxCollider != value) { _createBoxCollider = value; UpdateCollider(); } } } new void Awake() { base.Awake(); // Create mesh, independently to everything else mesh = new Mesh(); mesh.hideFlags = HideFlags.DontSave; GetComponent<MeshFilter>().mesh = mesh; // This will not be set when instantiating in code // In that case, Build will need to be called if (Collection) { // reset spriteId if outside bounds // this is when the sprite collection data is corrupt if (_spriteId < 0 || _spriteId >= Collection.Count) _spriteId = 0; Build(); if (boxCollider == null) boxCollider = GetComponent<BoxCollider>(); #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) if (boxCollider2D == null) { boxCollider2D = GetComponent<BoxCollider2D>(); } #endif } } protected void OnDestroy() { if (mesh) { #if UNITY_EDITOR DestroyImmediate(mesh); #else Destroy(mesh); #endif } } new protected void SetColors(Color32[] dest) { int numVertices; int numIndices; tk2dSpriteGeomGen.GetTiledSpriteGeomDesc(out numVertices, out numIndices, CurrentSprite, dimensions); tk2dSpriteGeomGen.SetSpriteColors (dest, 0, numVertices, _color, collectionInst.premultipliedAlpha); } // Calculated center and extents Vector3 boundsCenter = Vector3.zero, boundsExtents = Vector3.zero; public override void Build() { var spriteDef = CurrentSprite; int numVertices; int numIndices; tk2dSpriteGeomGen.GetTiledSpriteGeomDesc(out numVertices, out numIndices, spriteDef, dimensions); if (meshUvs == null || meshUvs.Length != numVertices) { meshUvs = new Vector2[numVertices]; meshVertices = new Vector3[numVertices]; meshColors = new Color32[numVertices]; } if (meshIndices == null || meshIndices.Length != numIndices) { meshIndices = new int[numIndices]; } meshNormals = new Vector3[0]; meshTangents = new Vector4[0]; if (spriteDef.normals != null && spriteDef.normals.Length > 0) { meshNormals = new Vector3[numVertices]; } if (spriteDef.tangents != null && spriteDef.tangents.Length > 0) { meshTangents = new Vector4[numVertices]; } float colliderOffsetZ = ( boxCollider != null ) ? ( boxCollider.center.z ) : 0.0f; float colliderExtentZ = ( boxCollider != null ) ? ( boxCollider.size.z * 0.5f ) : 0.5f; tk2dSpriteGeomGen.SetTiledSpriteGeom(meshVertices, meshUvs, 0, out boundsCenter, out boundsExtents, spriteDef, _scale, dimensions, anchor, colliderOffsetZ, colliderExtentZ); tk2dSpriteGeomGen.SetTiledSpriteIndices(meshIndices, 0, 0, spriteDef, dimensions); if (meshNormals.Length > 0 || meshTangents.Length > 0) { Vector3 meshVertexMin = new Vector3(spriteDef.positions[0].x * dimensions.x * spriteDef.texelSize.x * scale.x, spriteDef.positions[0].y * dimensions.y * spriteDef.texelSize.y * scale.y); Vector3 meshVertexMax = new Vector3(spriteDef.positions[3].x * dimensions.x * spriteDef.texelSize.x * scale.x, spriteDef.positions[3].y * dimensions.y * spriteDef.texelSize.y * scale.y); tk2dSpriteGeomGen.SetSpriteVertexNormals(meshVertices, meshVertexMin, meshVertexMax, spriteDef.normals, spriteDef.tangents, meshNormals, meshTangents); } SetColors(meshColors); if (mesh == null) { mesh = new Mesh(); mesh.hideFlags = HideFlags.DontSave; } else { mesh.Clear(); } mesh.vertices = meshVertices; mesh.colors32 = meshColors; mesh.uv = meshUvs; mesh.normals = meshNormals; mesh.tangents = meshTangents; mesh.triangles = meshIndices; mesh.RecalculateBounds(); mesh.bounds = AdjustedMeshBounds( mesh.bounds, renderLayer ); GetComponent<MeshFilter>().mesh = mesh; UpdateCollider(); UpdateMaterial(); } protected override void UpdateGeometry() { UpdateGeometryImpl(); } protected override void UpdateColors() { UpdateColorsImpl(); } protected override void UpdateVertices() { UpdateGeometryImpl(); } protected void UpdateColorsImpl() { #if UNITY_EDITOR // This can happen with prefabs in the inspector if (meshColors == null || meshColors.Length == 0) return; #endif if (meshColors == null || meshColors.Length == 0) { Build(); } else { SetColors(meshColors); mesh.colors32 = meshColors; } } protected void UpdateGeometryImpl() { #if UNITY_EDITOR // This can happen with prefabs in the inspector if (mesh == null) return; #endif Build(); } #region Collider protected override void UpdateCollider() { if (CreateBoxCollider) { if (CurrentSprite.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics3D) { if (boxCollider != null) { boxCollider.size = 2 * boundsExtents; boxCollider.center = boundsCenter; } } else if (CurrentSprite.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics2D) { #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) if (boxCollider2D != null) { boxCollider2D.size = 2 * boundsExtents; boxCollider2D.center = boundsCenter; } #endif } } } #if UNITY_EDITOR void OnDrawGizmos() { if (mesh != null) { Bounds b = mesh.bounds; Gizmos.color = Color.clear; Gizmos.matrix = transform.localToWorldMatrix; Gizmos.DrawCube(b.center, b.extents * 2); Gizmos.matrix = Matrix4x4.identity; Gizmos.color = Color.white; } } #endif protected override void CreateCollider() { UpdateCollider(); } #if UNITY_EDITOR public override void EditMode__CreateCollider() { if (CreateBoxCollider) { base.CreateSimpleBoxCollider(); } UpdateCollider(); } #endif #endregion protected override void UpdateMaterial() { if (renderer.sharedMaterial != collectionInst.spriteDefinitions[spriteId].materialInst) renderer.material = collectionInst.spriteDefinitions[spriteId].materialInst; } protected override int GetCurrentVertexCount() { #if UNITY_EDITOR if (meshVertices == null) return 0; #endif return 16; } public override void ReshapeBounds(Vector3 dMin, Vector3 dMax) { // Identical to tk2dSlicedSprite.ReshapeBounds float minSizeClampTexelScale = 0.1f; // Can't shrink sprite smaller than this many texels // Irrespective of transform var sprite = CurrentSprite; Vector2 boundsSize = new Vector2(_dimensions.x * sprite.texelSize.x, _dimensions.y * sprite.texelSize.y); Vector3 oldSize = new Vector3(boundsSize.x * _scale.x, boundsSize.y * _scale.y); Vector3 oldMin = Vector3.zero; switch (_anchor) { case Anchor.LowerLeft: oldMin.Set(0,0,0); break; case Anchor.LowerCenter: oldMin.Set(0.5f,0,0); break; case Anchor.LowerRight: oldMin.Set(1,0,0); break; case Anchor.MiddleLeft: oldMin.Set(0,0.5f,0); break; case Anchor.MiddleCenter: oldMin.Set(0.5f,0.5f,0); break; case Anchor.MiddleRight: oldMin.Set(1,0.5f,0); break; case Anchor.UpperLeft: oldMin.Set(0,1,0); break; case Anchor.UpperCenter: oldMin.Set(0.5f,1,0); break; case Anchor.UpperRight: oldMin.Set(1,1,0); break; } oldMin = Vector3.Scale(oldMin, oldSize) * -1; Vector3 newScale = oldSize + dMax - dMin; newScale.x /= boundsSize.x; newScale.y /= boundsSize.y; // Clamp the minimum size to avoid having the pivot move when we scale from near-zero if (Mathf.Abs(boundsSize.x * newScale.x) < sprite.texelSize.x * minSizeClampTexelScale && Mathf.Abs(newScale.x) < Mathf.Abs(_scale.x)) { dMin.x = 0; newScale.x = _scale.x; } if (Mathf.Abs(boundsSize.y * newScale.y) < sprite.texelSize.y * minSizeClampTexelScale && Mathf.Abs(newScale.y) < Mathf.Abs(_scale.y)) { dMin.y = 0; newScale.y = _scale.y; } // Add our wanted local dMin offset, while negating the positional offset caused by scaling Vector2 scaleFactor = new Vector3(Mathf.Approximately(_scale.x, 0) ? 0 : (newScale.x / _scale.x), Mathf.Approximately(_scale.y, 0) ? 0 : (newScale.y / _scale.y)); Vector3 scaledMin = new Vector3(oldMin.x * scaleFactor.x, oldMin.y * scaleFactor.y); Vector3 offset = dMin + oldMin - scaledMin; offset.z = 0; transform.position = transform.TransformPoint(offset); dimensions = new Vector2(_dimensions.x * scaleFactor.x, _dimensions.y * scaleFactor.y); } }
// ******************************* // *** INIFile class V2.1 *** // ******************************* // *** (C)2009-2013 S.T.A. snc *** // ******************************* using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace STA.Settings { internal class INIFile { #region "Declarations" // *** Lock for thread-safe access to file and local cache *** private object m_Lock = new object(); // *** File name *** private string m_FileName = null; internal string FileName { get { return m_FileName; } } // *** Lazy loading flag *** private bool m_Lazy = false; // *** Automatic flushing flag *** private bool m_AutoFlush = false; // *** Local cache *** private Dictionary<string, Dictionary<string, string>> m_Sections = new Dictionary<string, Dictionary<string, string>>(); private Dictionary<string, Dictionary<string, string>> m_Modified = new Dictionary<string, Dictionary<string, string>>(); // *** Local cache modified flag *** private bool m_CacheModified = false; #endregion #region "Methods" // *** Constructor *** public INIFile(string FileName) { Initialize(FileName, false, false); } public INIFile(string FileName, bool Lazy, bool AutoFlush) { Initialize(FileName, Lazy, AutoFlush); } // *** Initialization *** private void Initialize(string FileName, bool Lazy, bool AutoFlush) { m_FileName = FileName; m_Lazy = Lazy; m_AutoFlush = AutoFlush; if (!m_Lazy) Refresh(); } // *** Parse section name *** private string ParseSectionName(string Line) { if (!Line.StartsWith("[")) return null; if (!Line.EndsWith("]")) return null; if (Line.Length < 3) return null; return Line.Substring(1, Line.Length - 2); } // *** Parse key+value pair *** private bool ParseKeyValuePair(string Line, ref string Key, ref string Value) { // *** Check for key+value pair *** int i; if ((i = Line.IndexOf('=')) <= 0) return false; int j = Line.Length - i - 1; Key = Line.Substring(0, i).Trim(); if (Key.Length <= 0) return false; Value = (j > 0) ? (Line.Substring(i + 1, j).Trim()) : (""); return true; } // *** Read file contents into local cache *** internal void Refresh() { lock (m_Lock) { StreamReader sr = null; try { // *** Clear local cache *** m_Sections.Clear(); m_Modified.Clear(); // *** Open the INI file *** try { sr = new StreamReader(m_FileName); } catch (FileNotFoundException) { return; } // *** Read up the file content *** Dictionary<string, string> CurrentSection = null; string s; string SectionName; string Key = null; string Value = null; while ((s = sr.ReadLine()) != null) { s = s.Trim(); // *** Check for section names *** SectionName = ParseSectionName(s); if (SectionName != null) { // *** Only first occurrence of a section is loaded *** if (m_Sections.ContainsKey(SectionName)) { CurrentSection = null; } else { CurrentSection = new Dictionary<string, string>(); m_Sections.Add(SectionName, CurrentSection); } } else if (CurrentSection != null) { // *** Check for key+value pair *** if (ParseKeyValuePair(s, ref Key, ref Value)) { // *** Only first occurrence of a key is loaded *** if (!CurrentSection.ContainsKey(Key)) { CurrentSection.Add(Key, Value); } } } } } finally { // *** Cleanup: close file *** if (sr != null) sr.Close(); sr = null; } } } // *** Flush local cache content *** internal void Flush() { lock (m_Lock) { PerformFlush(); } } private void PerformFlush() { // *** If local cache was not modified, exit *** if (!m_CacheModified) return; m_CacheModified = false; // *** Check if original file exists *** bool OriginalFileExists = File.Exists(m_FileName); // *** Get temporary file name *** string TmpFileName = Path.ChangeExtension(m_FileName, "$n$"); // *** Copy content of original file to temporary file, replace modified values *** StreamWriter sw = null; // *** Create the temporary file *** sw = new StreamWriter(TmpFileName); try { Dictionary<string, string> CurrentSection = null; if (OriginalFileExists) { StreamReader sr = null; try { // *** Open the original file *** sr = new StreamReader(m_FileName); // *** Read the file original content, replace changes with local cache values *** string s; string SectionName; string Key = null; string Value = null; bool Unmodified; bool Reading = true; while (Reading) { s = sr.ReadLine(); Reading = (s != null); // *** Check for end of file *** if (Reading) { Unmodified = true; s = s.Trim(); SectionName = ParseSectionName(s); } else { Unmodified = false; SectionName = null; } // *** Check for section names *** if ((SectionName != null) || (!Reading)) { if (CurrentSection != null) { // *** Write all remaining modified values before leaving a section **** if (CurrentSection.Count > 0) { foreach (string fkey in CurrentSection.Keys) { if (CurrentSection.TryGetValue(fkey, out Value)) { sw.Write(fkey); sw.Write('='); sw.WriteLine(Value); } } sw.WriteLine(); CurrentSection.Clear(); } } if (Reading) { // *** Check if current section is in local modified cache *** if (!m_Modified.TryGetValue(SectionName, out CurrentSection)) { CurrentSection = null; } } } else if (CurrentSection != null) { // *** Check for key+value pair *** if (ParseKeyValuePair(s, ref Key, ref Value)) { if (CurrentSection.TryGetValue(Key, out Value)) { // *** Write modified value to temporary file *** Unmodified = false; CurrentSection.Remove(Key); sw.Write(Key); sw.Write('='); sw.WriteLine(Value); } } } // *** Write unmodified lines from the original file *** if (Unmodified) { sw.WriteLine(s); } } // *** Close the original file *** sr.Close(); sr = null; } finally { // *** Cleanup: close files *** if (sr != null) sr.Close(); sr = null; } } // *** Cycle on all remaining modified values *** foreach (KeyValuePair<string, Dictionary<string, string>> SectionPair in m_Modified) { CurrentSection = SectionPair.Value; if (CurrentSection.Count > 0) { sw.WriteLine(); // *** Write the section name *** sw.Write('['); sw.Write(SectionPair.Key); sw.WriteLine(']'); // *** Cycle on all key+value pairs in the section *** foreach (KeyValuePair<string, string> ValuePair in CurrentSection) { // *** Write the key+value pair *** sw.Write(ValuePair.Key); sw.Write('='); sw.WriteLine(ValuePair.Value); } CurrentSection.Clear(); } } m_Modified.Clear(); // *** Close the temporary file *** sw.Close(); sw = null; // *** Rename the temporary file *** File.Copy(TmpFileName, m_FileName, true); // *** Delete the temporary file *** File.Delete(TmpFileName); } finally { // *** Cleanup: close files *** if (sw != null) sw.Close(); sw = null; } } // *** Read a value from local cache *** internal string GetValue(string SectionName, string Key, string DefaultValue) { // *** Lazy loading *** if (m_Lazy) { m_Lazy = false; Refresh(); } lock (m_Lock) { // *** Check if the section exists *** Dictionary<string, string> Section; if (!m_Sections.TryGetValue(SectionName, out Section)) return DefaultValue; // *** Check if the key exists *** string Value; if (!Section.TryGetValue(Key, out Value)) return DefaultValue; // *** Return the found value *** return Value; } } // *** Insert or modify a value in local cache *** internal void SetValue(string SectionName, string Key, string Value) { // *** Lazy loading *** if (m_Lazy) { m_Lazy = false; Refresh(); } lock (m_Lock) { // *** Flag local cache modification *** m_CacheModified = true; // *** Check if the section exists *** Dictionary<string, string> Section; if (!m_Sections.TryGetValue(SectionName, out Section)) { // *** If it doesn't, add it *** Section = new Dictionary<string, string>(); m_Sections.Add(SectionName,Section); } // *** Modify the value *** if (Section.ContainsKey(Key)) Section.Remove(Key); Section.Add(Key, Value); // *** Add the modified value to local modified values cache *** if (!m_Modified.TryGetValue(SectionName, out Section)) { Section = new Dictionary<string, string>(); m_Modified.Add(SectionName, Section); } if (Section.ContainsKey(Key)) Section.Remove(Key); Section.Add(Key, Value); // *** Automatic flushing : immediately write any modification to the file *** if (m_AutoFlush) PerformFlush(); } } // *** Encode byte array *** private string EncodeByteArray(byte[] Value) { if (Value == null) return null; StringBuilder sb = new StringBuilder(); foreach (byte b in Value) { string hex = Convert.ToString(b, 16); int l = hex.Length; if (l > 2) { sb.Append(hex.Substring(l - 2, 2)); } else { if (l < 2) sb.Append("0"); sb.Append(hex); } } return sb.ToString(); } // *** Decode byte array *** private byte[] DecodeByteArray(string Value) { if (Value == null) return null; int l = Value.Length; if (l < 2) return new byte[] { }; l /= 2; byte[] Result = new byte[l]; for (int i = 0; i < l; i++) Result[i] = Convert.ToByte(Value.Substring(i * 2, 2), 16); return Result; } // *** Getters for various types *** internal bool GetValue(string SectionName, string Key, bool DefaultValue) { string StringValue = GetValue(SectionName, Key, DefaultValue.ToString(System.Globalization.CultureInfo.InvariantCulture)); int Value; if (int.TryParse(StringValue, out Value)) return (Value != 0); return DefaultValue; } internal int GetValue(string SectionName, string Key, int DefaultValue) { string StringValue = GetValue(SectionName, Key, DefaultValue.ToString(CultureInfo.InvariantCulture)); int Value; if (int.TryParse(StringValue, NumberStyles.Any, CultureInfo.InvariantCulture, out Value)) return Value; return DefaultValue; } internal long GetValue(string SectionName, string Key, long DefaultValue) { string StringValue = GetValue(SectionName, Key, DefaultValue.ToString(CultureInfo.InvariantCulture)); long Value; if (long.TryParse(StringValue, NumberStyles.Any, CultureInfo.InvariantCulture, out Value)) return Value; return DefaultValue; } internal double GetValue(string SectionName, string Key, double DefaultValue) { string StringValue = GetValue(SectionName, Key, DefaultValue.ToString(CultureInfo.InvariantCulture)); double Value; if (double.TryParse(StringValue, NumberStyles.Any, CultureInfo.InvariantCulture, out Value)) return Value; return DefaultValue; } internal byte[] GetValue(string SectionName, string Key, byte[] DefaultValue) { string StringValue = GetValue(SectionName, Key, EncodeByteArray(DefaultValue)); try { return DecodeByteArray(StringValue); } catch (FormatException) { return DefaultValue; } } internal DateTime GetValue(string SectionName, string Key, DateTime DefaultValue) { string StringValue = GetValue(SectionName, Key, DefaultValue.ToString(CultureInfo.InvariantCulture)); DateTime Value; if (DateTime.TryParse(StringValue, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.NoCurrentDateDefault | DateTimeStyles.AssumeLocal, out Value)) return Value; return DefaultValue; } // *** Setters for various types *** internal void SetValue(string SectionName, string Key, bool Value) { SetValue(SectionName, Key, (Value) ? ("1") : ("0")); } internal void SetValue(string SectionName, string Key, int Value) { SetValue(SectionName, Key, Value.ToString(CultureInfo.InvariantCulture)); } internal void SetValue(string SectionName, string Key, long Value) { SetValue(SectionName, Key, Value.ToString(CultureInfo.InvariantCulture)); } internal void SetValue(string SectionName, string Key, double Value) { SetValue(SectionName, Key, Value.ToString(CultureInfo.InvariantCulture)); } internal void SetValue(string SectionName, string Key, byte[] Value) { SetValue(SectionName, Key, EncodeByteArray(Value)); } internal void SetValue(string SectionName, string Key, DateTime Value) { SetValue(SectionName, Key, Value.ToString(CultureInfo.InvariantCulture)); } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Xml; using System.Linq; using ICSharpCode.SharpZipLib.Zip; using Umbraco.Core; using Umbraco.Core.Auditing; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Packaging; using umbraco.cms.businesslogic.web; using umbraco.BusinessLogic; using System.Diagnostics; using umbraco.cms.businesslogic.macro; using umbraco.cms.businesslogic.template; using umbraco.interfaces; namespace umbraco.cms.businesslogic.packager { /// <summary> /// The packager is a component which enables sharing of both data and functionality components between different umbraco installations. /// /// The output is a .umb (a zip compressed file) which contains the exported documents/medias/macroes/documenttypes (etc.) /// in a Xml document, along with the physical files used (images/usercontrols/xsl documents etc.) /// /// Partly implemented, import of packages is done, the export is *under construction*. /// </summary> /// <remarks> /// Ruben Verborgh 31/12/2007: I had to change some code, I marked my changes with "DATALAYER". /// Reason: @@IDENTITY can't be used with the new datalayer. /// I wasn't able to test the code, since I'm not aware how the code functions. /// </remarks> public class Installer { private const string PackageServer = "packages.umbraco.org"; private readonly List<string> _unsecureFiles = new List<string>(); private readonly Dictionary<string, string> _conflictingMacroAliases = new Dictionary<string, string>(); private readonly Dictionary<string, string> _conflictingTemplateAliases = new Dictionary<string, string>(); private readonly Dictionary<string, string> _conflictingStyleSheetNames = new Dictionary<string, string>(); private readonly List<string> _binaryFileErrors = new List<string>(); private int _currentUserId = -1; public string Name { get; private set; } public string Version { get; private set; } public string Url { get; private set; } public string License { get; private set; } public string LicenseUrl { get; private set; } public string Author { get; private set; } public string AuthorUrl { get; private set; } public string ReadMe { get; private set; } public string Control { get; private set; } public bool ContainsMacroConflict { get; private set; } public IDictionary<string, string> ConflictingMacroAliases { get { return _conflictingMacroAliases; } } public bool ContainsUnsecureFiles { get; private set; } public List<string> UnsecureFiles { get { return _unsecureFiles; } } public bool ContainsTemplateConflicts { get; private set; } public IDictionary<string, string> ConflictingTemplateAliases { get { return _conflictingTemplateAliases; } } /// <summary> /// Indicates that the package contains assembly reference errors /// </summary> public bool ContainsBinaryFileErrors { get; private set; } /// <summary> /// List each assembly reference error /// </summary> public List<string> BinaryFileErrors { get { return _binaryFileErrors; } } /// <summary> /// Indicates that the package contains legacy property editors /// </summary> public bool ContainsLegacyPropertyEditors { get; private set; } public bool ContainsStyleSheeConflicts { get; private set; } public IDictionary<string, string> ConflictingStyleSheetNames { get { return _conflictingStyleSheetNames; } } public int RequirementsMajor { get; private set; } public int RequirementsMinor { get; private set; } public int RequirementsPatch { get; private set; } public RequirementsType RequirementsType { get; private set; } public string IconUrl { get; private set; } /// <summary> /// The xmldocument, describing the contents of a package. /// </summary> public XmlDocument Config { get; private set; } /// <summary> /// Constructor /// </summary> public Installer() { Initialize(); } public Installer(int currentUserId) { Initialize(); _currentUserId = currentUserId; } private void Initialize() { ContainsBinaryFileErrors = false; ContainsTemplateConflicts = false; ContainsUnsecureFiles = false; ContainsMacroConflict = false; ContainsStyleSheeConflicts = false; } [Obsolete("Use the ctor with all parameters")] [EditorBrowsable(EditorBrowsableState.Never)] public Installer(string name, string version, string url, string license, string licenseUrl, string author, string authorUrl, int requirementsMajor, int requirementsMinor, int requirementsPatch, string readme, string control) { } /// <summary> /// Constructor /// </summary> /// <param name="name">The name of the package</param> /// <param name="version">The version of the package</param> /// <param name="url">The url to a descriptionpage</param> /// <param name="license">The license under which the package is released (preferably GPL ;))</param> /// <param name="licenseUrl">The url to a licensedescription</param> /// <param name="author">The original author of the package</param> /// <param name="authorUrl">The url to the Authors website</param> /// <param name="requirementsMajor">Umbraco version major</param> /// <param name="requirementsMinor">Umbraco version minor</param> /// <param name="requirementsPatch">Umbraco version patch</param> /// <param name="readme">The readme text</param> /// <param name="control">The name of the usercontrol used to configure the package after install</param> /// <param name="requirementsType"></param> /// <param name="iconUrl"></param> public Installer(string name, string version, string url, string license, string licenseUrl, string author, string authorUrl, int requirementsMajor, int requirementsMinor, int requirementsPatch, string readme, string control, RequirementsType requirementsType, string iconUrl) { ContainsBinaryFileErrors = false; ContainsTemplateConflicts = false; ContainsUnsecureFiles = false; ContainsMacroConflict = false; ContainsStyleSheeConflicts = false; this.Name = name; this.Version = version; this.Url = url; this.License = license; this.LicenseUrl = licenseUrl; this.RequirementsMajor = requirementsMajor; this.RequirementsMinor = requirementsMinor; this.RequirementsPatch = requirementsPatch; this.RequirementsType = requirementsType; this.Author = author; this.AuthorUrl = authorUrl; this.IconUrl = iconUrl; ReadMe = readme; this.Control = control; } #region Public Methods /// <summary> /// Imports the specified package /// </summary> /// <param name="inputFile">Filename of the umbracopackage</param> /// <param name="deleteFile">true if the input file should be deleted after import</param> /// <returns></returns> public string Import(string inputFile, bool deleteFile) { using (DisposableTimer.DebugDuration<Installer>( () => "Importing package file " + inputFile, () => "Package file " + inputFile + "imported")) { var tempDir = ""; if (File.Exists(IOHelper.MapPath(SystemDirectories.Data + Path.DirectorySeparatorChar + inputFile))) { var fi = new FileInfo(IOHelper.MapPath(SystemDirectories.Data + Path.DirectorySeparatorChar + inputFile)); // Check if the file is a valid package if (fi.Extension.ToLower() == ".umb") { try { tempDir = UnPack(fi.FullName, deleteFile); LoadConfig(tempDir); } catch (Exception exception) { LogHelper.Error<Installer>(string.Format("Error importing file {0}", fi.FullName), exception); throw; } } else throw new Exception("Error - file isn't a package (doesn't have a .umb extension). Check if the file automatically got named '.zip' upon download."); } else throw new Exception("Error - file not found. Could find file named '" + IOHelper.MapPath(SystemDirectories.Data + Path.DirectorySeparatorChar + inputFile) + "'"); return tempDir; } } /// <summary> /// Imports the specified package /// </summary> /// <param name="inputFile">Filename of the umbracopackage</param> /// <returns></returns> public string Import(string inputFile) { return Import(inputFile, true); } public int CreateManifest(string tempDir, string guid, string repoGuid) { //This is the new improved install rutine, which chops up the process into 3 steps, creating the manifest, moving files, and finally handling umb objects var packName = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/name")); var packAuthor = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/author/name")); var packAuthorUrl = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/author/website")); var packVersion = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/version")); var packReadme = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/readme")); var packLicense = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/license ")); var packUrl = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/url ")); var iconUrl = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/iconUrl")); var enableSkins = false; var skinRepoGuid = ""; if (Config.DocumentElement.SelectSingleNode("/umbPackage/enableSkins") != null) { var skinNode = Config.DocumentElement.SelectSingleNode("/umbPackage/enableSkins"); enableSkins = bool.Parse(XmlHelper.GetNodeValue(skinNode)); if (skinNode.Attributes["repository"] != null && string.IsNullOrEmpty(skinNode.Attributes["repository"].Value) == false) skinRepoGuid = skinNode.Attributes["repository"].Value; } //Create a new package instance to record all the installed package adds - this is the same format as the created packages has. //save the package meta data var insPack = InstalledPackage.MakeNew(packName); insPack.Data.Author = packAuthor; insPack.Data.AuthorUrl = packAuthorUrl; insPack.Data.Version = packVersion; insPack.Data.Readme = packReadme; insPack.Data.License = packLicense; insPack.Data.Url = packUrl; insPack.Data.IconUrl = iconUrl; //skinning insPack.Data.EnableSkins = enableSkins; insPack.Data.SkinRepoGuid = string.IsNullOrEmpty(skinRepoGuid) ? Guid.Empty : new Guid(skinRepoGuid); insPack.Data.PackageGuid = guid; //the package unique key. insPack.Data.RepositoryGuid = repoGuid; //the repository unique key, if the package is a file install, the repository will not get logged. insPack.Save(); return insPack.Data.Id; } public void InstallFiles(int packageId, string tempDir) { using (DisposableTimer.DebugDuration<Installer>( () => "Installing package files for package id " + packageId + " into temp folder " + tempDir, () => "Package file installation complete for package id " + packageId)) { //retrieve the manifest to continue installation var insPack = InstalledPackage.GetById(packageId); //TODO: Depending on some files, some files should be installed differently. //i.e. if stylsheets should probably be installed via business logic, media items should probably use the media IFileSystem! // Move files //string virtualBasePath = System.Web.HttpContext.Current.Request.ApplicationPath; string basePath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath; try { foreach (XmlNode n in Config.DocumentElement.SelectNodes("//file")) { var destPath = GetFileName(basePath, XmlHelper.GetNodeValue(n.SelectSingleNode("orgPath"))); var sourceFile = GetFileName(tempDir, XmlHelper.GetNodeValue(n.SelectSingleNode("guid"))); var destFile = GetFileName(destPath, XmlHelper.GetNodeValue(n.SelectSingleNode("orgName"))); // Create the destination directory if it doesn't exist if (Directory.Exists(destPath) == false) Directory.CreateDirectory(destPath); //If a file with this name exists, delete it else if (File.Exists(destFile)) File.Delete(destFile); // Copy the file // SJ: Note - this used to do a move but some packages included the same file to be // copied to multiple locations like so: // // <file> // <guid>my-icon.png</guid> // <orgPath>/umbraco/Images/</orgPath> // <orgName>my-icon.png</orgName> // </file> // <file> // <guid>my-icon.png</guid> // <orgPath>/App_Plugins/MyPlugin/Images</orgPath> // <orgName>my-icon.png</orgName> // </file> // // Since this file unzips as a flat list of files, moving the file the first time means // that when you try to do that a second time, it would result in a FileNotFoundException File.Copy(sourceFile, destFile); //PPH log file install insPack.Data.Files.Add(XmlHelper.GetNodeValue(n.SelectSingleNode("orgPath")) + "/" + XmlHelper.GetNodeValue(n.SelectSingleNode("orgName"))); } // Once we're done copying, remove all the files foreach (XmlNode n in Config.DocumentElement.SelectNodes("//file")) { var sourceFile = GetFileName(tempDir, XmlHelper.GetNodeValue(n.SelectSingleNode("guid"))); if (File.Exists(sourceFile)) File.Delete(sourceFile); } } catch (Exception exception) { LogHelper.Error<Installer>("Package install error", exception); throw; } // log that a user has install files if (_currentUserId > -1) { Audit.Add(AuditTypes.PackagerInstall, string.Format("Package '{0}' installed. Package guid: {1}", insPack.Data.Name, insPack.Data.PackageGuid), _currentUserId, -1); } insPack.Save(); } } public void InstallBusinessLogic(int packageId, string tempDir) { using (DisposableTimer.DebugDuration<Installer>( () => "Installing business logic for package id " + packageId + " into temp folder " + tempDir, () => "Package business logic installation complete for package id " + packageId)) { InstalledPackage insPack; try { //retrieve the manifest to continue installation insPack = InstalledPackage.GetById(packageId); //bool saveNeeded = false; // Get current user, with a fallback var currentUser = new User(0); //if there's a context, try to resolve the user - this will return null if there is a context but no // user found when there are old/invalid cookies lying around most likely during installation. // in that case we'll keep using the admin user if (string.IsNullOrEmpty(BasePages.UmbracoEnsuredPage.umbracoUserContextID) == false) { if (BasePages.UmbracoEnsuredPage.ValidateUserContextID(BasePages.UmbracoEnsuredPage.umbracoUserContextID)) { var userById = User.GetCurrent(); if (userById != null) currentUser = userById; } } //Xml as XElement which is used with the new PackagingService var rootElement = Config.DocumentElement.GetXElement(); var packagingService = ApplicationContext.Current.Services.PackagingService; //Perhaps it would have been a good idea to put the following into methods eh?!? #region DataTypes var dataTypeElement = rootElement.Descendants("DataTypes").FirstOrDefault(); if (dataTypeElement != null) { var dataTypeDefinitions = packagingService.ImportDataTypeDefinitions(dataTypeElement, currentUser.Id); foreach (var dataTypeDefinition in dataTypeDefinitions) { insPack.Data.DataTypes.Add(dataTypeDefinition.Id.ToString(CultureInfo.InvariantCulture)); } } #endregion #region Languages var languageItemsElement = rootElement.Descendants("Languages").FirstOrDefault(); if (languageItemsElement != null) { var insertedLanguages = packagingService.ImportLanguages(languageItemsElement); insPack.Data.Languages.AddRange(insertedLanguages.Select(l => l.Id.ToString(CultureInfo.InvariantCulture))); } #endregion #region Dictionary items var dictionaryItemsElement = rootElement.Descendants("DictionaryItems").FirstOrDefault(); if (dictionaryItemsElement != null) { var insertedDictionaryItems = packagingService.ImportDictionaryItems(dictionaryItemsElement); insPack.Data.DictionaryItems.AddRange(insertedDictionaryItems.Select(d => d.Id.ToString(CultureInfo.InvariantCulture))); } #endregion #region Macros var macroItemsElement = rootElement.Descendants("Macros").FirstOrDefault(); if (macroItemsElement != null) { var insertedMacros = packagingService.ImportMacros(macroItemsElement); insPack.Data.Macros.AddRange(insertedMacros.Select(m => m.Id.ToString(CultureInfo.InvariantCulture))); } #endregion #region Templates var templateElement = rootElement.Descendants("Templates").FirstOrDefault(); if (templateElement != null) { var templates = packagingService.ImportTemplates(templateElement, currentUser.Id); foreach (var template in templates) { insPack.Data.Templates.Add(template.Id.ToString(CultureInfo.InvariantCulture)); } } #endregion #region DocumentTypes //Check whether the root element is a doc type rather then a complete package var docTypeElement = rootElement.Name.LocalName.Equals("DocumentType") || rootElement.Name.LocalName.Equals("DocumentTypes") ? rootElement : rootElement.Descendants("DocumentTypes").FirstOrDefault(); if (docTypeElement != null) { var contentTypes = packagingService.ImportContentTypes(docTypeElement, currentUser.Id); foreach (var contentType in contentTypes) { insPack.Data.Documenttypes.Add(contentType.Id.ToString(CultureInfo.InvariantCulture)); //saveNeeded = true; } } #endregion #region Stylesheets foreach (XmlNode n in Config.DocumentElement.SelectNodes("Stylesheets/Stylesheet")) { StyleSheet s = StyleSheet.Import(n, currentUser); insPack.Data.Stylesheets.Add(s.Id.ToString(CultureInfo.InvariantCulture)); //saveNeeded = true; } //if (saveNeeded) { insPack.Save(); saveNeeded = false; } #endregion #region Documents var documentElement = rootElement.Descendants("DocumentSet").FirstOrDefault(); if (documentElement != null) { var content = packagingService.ImportContent(documentElement, -1, currentUser.Id); var firstContentItem = content.First(); insPack.Data.ContentNodeId = firstContentItem.Id.ToString(CultureInfo.InvariantCulture); } #endregion #region Package Actions foreach (XmlNode n in Config.DocumentElement.SelectNodes("Actions/Action")) { if (n.Attributes["undo"] == null || n.Attributes["undo"].Value == "true") { insPack.Data.Actions += n.OuterXml; } //Run the actions tagged only for 'install' if (n.Attributes["runat"] != null && n.Attributes["runat"].Value == "install") { var alias = n.Attributes["alias"] != null ? n.Attributes["alias"].Value : ""; if (alias.IsNullOrWhiteSpace() == false) { PackageAction.RunPackageAction(insPack.Data.Name, alias, n); } } } #endregion // Trigger update of Apps / Trees config. // (These are ApplicationStartupHandlers so just instantiating them will trigger them) new ApplicationRegistrar(); new ApplicationTreeRegistrar(); insPack.Save(); } catch (Exception exception) { LogHelper.Error<Installer>("Error installing businesslogic", exception); throw; } OnPackageBusinessLogicInstalled(insPack); } } /// <summary> /// Remove the temp installation folder /// </summary> /// <param name="packageId"></param> /// <param name="tempDir"></param> public void InstallCleanUp(int packageId, string tempDir) { if (Directory.Exists(tempDir)) { Directory.Delete(tempDir, true); } } /// <summary> /// Reads the configuration of the package from the configuration xmldocument /// </summary> /// <param name="tempDir">The folder to which the contents of the package is extracted</param> public void LoadConfig(string tempDir) { Config = new XmlDocument(); Config.Load(tempDir + Path.DirectorySeparatorChar + "package.xml"); Name = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/name").FirstChild.Value; Version = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/version").FirstChild.Value; Url = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/url").FirstChild.Value; License = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/license").FirstChild.Value; LicenseUrl = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/license").Attributes.GetNamedItem("url").Value; RequirementsMajor = int.Parse(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/requirements/major").FirstChild.Value); RequirementsMinor = int.Parse(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/requirements/minor").FirstChild.Value); RequirementsPatch = int.Parse(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/requirements/patch").FirstChild.Value); var reqNode = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/requirements"); RequirementsType = reqNode != null && reqNode.Attributes != null && reqNode.Attributes["type"] != null ? Enum<RequirementsType>.Parse(reqNode.Attributes["type"].Value, true) : RequirementsType.Legacy; var iconNode = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/iconUrl"); if (iconNode != null && iconNode.FirstChild != null) { IconUrl = iconNode.FirstChild.Value; } Author = Config.DocumentElement.SelectSingleNode("/umbPackage/info/author/name").FirstChild.Value; AuthorUrl = Config.DocumentElement.SelectSingleNode("/umbPackage/info/author/website").FirstChild.Value; var basePath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath; var dllBinFiles = new List<string>(); foreach (XmlNode n in Config.DocumentElement.SelectNodes("//file")) { var badFile = false; var destPath = GetFileName(basePath, XmlHelper.GetNodeValue(n.SelectSingleNode("orgPath"))); var orgName = XmlHelper.GetNodeValue(n.SelectSingleNode("orgName")); var destFile = GetFileName(destPath, orgName); if (destPath.ToLower().Contains(IOHelper.DirSepChar + "app_code")) { badFile = true; } if (destPath.ToLower().Contains(IOHelper.DirSepChar + "bin")) { badFile = true; } if (destFile.ToLower().EndsWith(".dll")) { badFile = true; dllBinFiles.Add(Path.Combine(tempDir, orgName)); } if (badFile) { ContainsUnsecureFiles = true; _unsecureFiles.Add(XmlHelper.GetNodeValue(n.SelectSingleNode("orgName"))); } } if (ContainsUnsecureFiles) { //Now we want to see if the DLLs contain any legacy data types since we want to warn people about that string[] assemblyErrors; var assembliesWithReferences = PackageBinaryInspector.ScanAssembliesForTypeReference<IDataType>(tempDir, out assemblyErrors).ToArray(); if (assemblyErrors.Any()) { ContainsBinaryFileErrors = true; BinaryFileErrors.AddRange(assemblyErrors); } if (assembliesWithReferences.Any()) { ContainsLegacyPropertyEditors = true; } } //this will check for existing macros with the same alias //since we will not overwrite on import it's a good idea to inform the user what will be overwritten foreach (XmlNode n in Config.DocumentElement.SelectNodes("//macro")) { var alias = n.SelectSingleNode("alias").InnerText; if (!string.IsNullOrEmpty(alias)) { var m = ApplicationContext.Current.Services.MacroService.GetByAlias(alias); if (m != null) { ContainsMacroConflict = true; if (_conflictingMacroAliases.ContainsKey(m.Name) == false) { _conflictingMacroAliases.Add(m.Name, alias); } } } } foreach (XmlNode n in Config.DocumentElement.SelectNodes("Templates/Template")) { var alias = n.SelectSingleNode("Alias").InnerText; if (!string.IsNullOrEmpty(alias)) { var t = Template.GetByAlias(alias); if (t != null) { ContainsTemplateConflicts = true; if (_conflictingTemplateAliases.ContainsKey(t.Text) == false) { _conflictingTemplateAliases.Add(t.Text, alias); } } } } foreach (XmlNode n in Config.DocumentElement.SelectNodes("Stylesheets/Stylesheet")) { var alias = n.SelectSingleNode("Name").InnerText; if (!string.IsNullOrEmpty(alias)) { var s = StyleSheet.GetByName(alias); if (s != null) { ContainsStyleSheeConflicts = true; if (_conflictingStyleSheetNames.ContainsKey(s.Text) == false) { _conflictingStyleSheetNames.Add(s.Text, alias); } } } } var readmeNode = Config.DocumentElement.SelectSingleNode("/umbPackage/info/readme"); if (readmeNode != null) { ReadMe = XmlHelper.GetNodeValue(readmeNode); } var controlNode = Config.DocumentElement.SelectSingleNode("/umbPackage/control"); if (controlNode != null) { Control = XmlHelper.GetNodeValue(controlNode); } } /// <summary> /// This uses the old method of fetching and only supports the packages.umbraco.org repository. /// </summary> /// <param name="Package"></param> /// <returns></returns> public string Fetch(Guid Package) { // Check for package directory if (Directory.Exists(IOHelper.MapPath(SystemDirectories.Packages)) == false) Directory.CreateDirectory(IOHelper.MapPath(SystemDirectories.Packages)); var wc = new System.Net.WebClient(); wc.DownloadFile( "http://" + PackageServer + "/fetch?package=" + Package.ToString(), IOHelper.MapPath(SystemDirectories.Packages + "/" + Package + ".umb")); return "packages\\" + Package + ".umb"; } #endregion #region Private Methods /// <summary> /// Gets the name of the file in the specified path. /// Corrects possible problems with slashes that would result from a simple concatenation. /// Can also be used to concatenate paths. /// </summary> /// <param name="path">The path.</param> /// <param name="fileName">Name of the file.</param> /// <returns>The name of the file in the specified path.</returns> private static string GetFileName(string path, string fileName) { // virtual dir support fileName = IOHelper.FindFile(fileName); if (path.Contains("[$")) { //this is experimental and undocumented... path = path.Replace("[$UMBRACO]", SystemDirectories.Umbraco); path = path.Replace("[$UMBRACOCLIENT]", SystemDirectories.UmbracoClient); path = path.Replace("[$CONFIG]", SystemDirectories.Config); path = path.Replace("[$DATA]", SystemDirectories.Data); } //to support virtual dirs we try to lookup the file... path = IOHelper.FindFile(path); Debug.Assert(path != null && path.Length >= 1); Debug.Assert(fileName != null && fileName.Length >= 1); path = path.Replace('/', '\\'); fileName = fileName.Replace('/', '\\'); // Does filename start with a slash? Does path end with one? bool fileNameStartsWithSlash = (fileName[0] == Path.DirectorySeparatorChar); bool pathEndsWithSlash = (path[path.Length - 1] == Path.DirectorySeparatorChar); // Path ends with a slash if (pathEndsWithSlash) { if (!fileNameStartsWithSlash) // No double slash, just concatenate return path + fileName; return path + fileName.Substring(1); } if (fileNameStartsWithSlash) // Required slash specified, just concatenate return path + fileName; return path + Path.DirectorySeparatorChar + fileName; } private static string UnPack(string zipName, bool deleteFile) { // Unzip //the temp directory will be the package GUID - this keeps it consistent! //the zipName is always the package Guid.umb var packageFileName = Path.GetFileNameWithoutExtension(zipName); var packageId = Guid.NewGuid(); Guid.TryParse(packageFileName, out packageId); string tempDir = IOHelper.MapPath(SystemDirectories.Data) + Path.DirectorySeparatorChar + packageId.ToString(); //clear the directory if it exists if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true); Directory.CreateDirectory(tempDir); var s = new ZipInputStream(File.OpenRead(zipName)); ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { string fileName = Path.GetFileName(theEntry.Name); if (fileName != String.Empty) { FileStream streamWriter = File.Create(tempDir + Path.DirectorySeparatorChar + fileName); int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } streamWriter.Close(); } } // Clean up s.Close(); if (deleteFile) { File.Delete(zipName); } return tempDir; } #endregion internal static event EventHandler<InstalledPackage> PackageBusinessLogicInstalled; private static void OnPackageBusinessLogicInstalled(InstalledPackage e) { EventHandler<InstalledPackage> handler = PackageBusinessLogicInstalled; if (handler != null) handler(null, e); } } }
//#define ASTARDEBUG #if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9 #define UNITY_4 #endif using UnityEngine; using System.Collections; using System.Collections.Generic; using Pathfinding.Serialization.JsonFx; namespace Pathfinding { [System.Serializable] [JsonOptIn] /** Automatically generates navmesh graphs based on world geometry. The recast graph is based on Recast (http://code.google.com/p/recastnavigation/).\n I have translated a good portion of it to C# to run it natively in Unity. The Recast process is described as follows: - The voxel mold is build from the input triangle mesh by rasterizing the triangles into a multi-layer heightfield. Some simple filters are then applied to the mold to prune out locations where the character would not be able to move. - The walkable areas described by the mold are divided into simple overlayed 2D regions. The resulting regions have only one non-overlapping contour, which simplifies the final step of the process tremendously. - The navigation polygons are peeled off from the regions by first tracing the boundaries and then simplifying them. The resulting polygons are finally converted to convex polygons which makes them perfect for pathfinding and spatial reasoning about the level. It works exactly like that in the C# version as well, except that everything is triangulated to triangles instead of n-gons. The recast generation process completely ignores colliders since it only works on an existing "polygon soup". This is usually a good thing though, because world geometry is usually more detailed than the colliders. \section export Exporting for manual editing In the editor there is a button for exporting the generated graph to a .obj file. Usually the generation process is good enough for the game directly, but in some cases you might want to edit some minor details. So you can export the graph to a .obj file, open it in your favourite 3D application, edit it, and export it to a mesh which Unity can import. Then you assign that new mesh to the "Replacement Mesh" field right below the export button. That mesh will then be used to calculate the graph. Since many 3D modelling programs use different axis systems (unity uses X=right, Y=up, Z=forward), it can be a bit tricky to get the rotation and scaling right. For blender for example, what you have to do is to first import the mesh using the .obj importer. Don't change anything related to axes in the settings. Then select the mesh, open the transform tab (usually the thin toolbar to the right of the 3D view) and set Scale -> Z to -1. If you transform it using the S (scale) hotkey, it seems to set both Z and Y to -1 of some reason. Then make the edits you need and export it as an .obj file to somewhere in the Unity project. But this time, edit the setting named "Forward" to "Z forward" (not -Z as it is per default). \shadowimage{recastgraph_graph.png} \shadowimage{recastgraph_inspector.png} * \ingroup graphs * \astarpro */ public class RecastGraph : NavGraph, INavmesh, ISerializableGraph, IRaycastableGraph, IFunnelGraph, IUpdatableGraph { public override Node[] CreateNodes (int number) { MeshNode[] tmp = new MeshNode[number]; for (int i=0;i<number;i++) { tmp[i] = new MeshNode (); tmp[i].penalty = initialPenalty; } return tmp as Node[]; } //public int erosionRadius = 2; /*< Voxels to erode away from the edges of the mesh */ [JsonMember] public float characterRadius = 0.5F; [JsonMember] public float contourMaxError = 2F; /**< Max distance from simplified edge to real edge */ [JsonMember] public float cellSize = 0.5F; /**< Voxel sample size (x,z) */ [JsonMember] public float cellHeight = 0.4F; /**< Voxel sample size (y) */ [JsonMember] public float walkableHeight = 2F; /**< Character height*/ [JsonMember] public float walkableClimb = 0.5F; /**< Height the character can climb */ [JsonMember] public float maxSlope = 30; /**< Max slope in degrees the character can traverse */ [JsonMember] public float maxEdgeLength = 20; /**< Longer edges will be subdivided. Reducing this value can improve path quality since similarly sized polygons yield better paths than really large and really small next to each other */ [JsonMember] public int regionMinSize = 8; /** Use a C++ version of Recast. * The C++ version is faster and has more features, though right now the features are quite similar because I haven't added support for them yet.\n * The C++ version can only be used in the editor or in standalones and it requires a special file to be placed inside the executable for standalones.\n * When deploying for mac, the Recast file (which can be found in the AstarPathfindingProject folder) should be copied to a new folder myApplication.app/Contents/Recast/ * \shadowimage{recastMacPlacement.png} * When deploying for windows, the Recast file should be copied to the data folder/Recast/ * \shadowimage{recastWindowsPlacement.png} * You can however save a cache of the graph scanned in the editor and use that in a webplayer but you cannot rescann any graphs in the webplayer\n * I have no information on whether or not it would work using iPhone or Android, so I would refrain form trying to use it there (though you can still cache graphs as you can with the webplayer) */ [JsonMember] public bool useCRecast = false; [JsonMember] /** Use colliders to calculate the navmesh */ public bool rasterizeColliders = false; [JsonMember] /** Use scene meshes to calculate the navmesh */ public bool rasterizeMeshes = true; /** Include the Terrain in the scene. */ [JsonMember] public bool rasterizeTerrain = true; /** Rasterize tree colliders on terrains. * * If the tree prefab has a collider, that collider will be rasterized. * Otherwise a simple box collider will be used and the script will * try to adjust it to the tree's scale, it might not do a very good job though so * an attached collider is preferable. * * \see rasterizeTerrain * \see colliderRasterizeDetail */ public bool rasterizeTrees = true; [JsonMember] /** Controls detail on rasterization of sphere and capsule colliders. * This controls the number of rows and columns on the generated meshes. * A higher value does not necessarily increase quality of the mesh, but a lower * value will often speed it up. * * You should try to keep this value as low as possible without affecting the mesh quality since * that will yield the fastest scan times. * * \see rasterizeColliders */ public float colliderRasterizeDetail = 10; [JsonMember] /** Include voxels which were out of bounds of the graph. * This is usually not desireable, but might be in some cases */ public bool includeOutOfBounds = false; /** Center of the bounding box. * Scanning will only be done inside the bounding box */ [JsonMember] public Vector3 forcedBoundsCenter; /** Size of the bounding box. */ [JsonMember] public Vector3 forcedBoundsSize = new Vector3 (100,40,100); /** Masks which objects to include. * \see tagMask */ [JsonMember] public LayerMask mask = -1; [JsonMember] /** Objects tagged with any of these tags will be rasterized. * \see mask */ public List<string> tagMask = new List<string>(); /** Show an outline of the polygons in the Unity Editor */ [JsonMember] public bool showMeshOutline = false; /** Controls how large the sample size for the terrain is. * A higher value is faster to scan but less accurate */ [JsonMember] public int terrainSampleSize = 3; /** More accurate nearest node queries. * When on, looks for the closest point on every triangle instead of if point is inside the node triangle in XZ space. * This is slower, but a lot better if your mesh contains overlaps (e.g bridges over other areas of the mesh). * Note that for maximum effect the Full Get Nearest Node Search setting should be toggled in A* Inspector Settings. */ [JsonMember] public bool accurateNearestNode = true; /** World bounds for the graph. * Defined as a bounds object with size #forceBoundsSize and centered at #forcedBoundsCenter */ public Bounds forcedBounds { get { return new Bounds (forcedBoundsCenter,forcedBoundsSize); } } /** Bounding Box Tree. Enables really fast lookups of nodes. * \astarpro */ BBTree _bbTree; public BBTree bbTree { get { return _bbTree; } set { _bbTree = value;} } Int3[] _vertices; public Int3[] vertices { get { return _vertices; } set { _vertices = value; } } Vector3[] _vectorVertices; public Vector3[] vectorVertices { get { if (_vectorVertices != null && _vectorVertices.Length == vertices.Length) { return _vectorVertices; } if (vertices == null) return null; _vectorVertices = new Vector3[vertices.Length]; for (int i=0;i<_vectorVertices.Length;i++) { _vectorVertices[i] = (Vector3)vertices[i]; } return _vectorVertices; } } public void SnapForceBoundsToScene () { List<MeshFilter> filteredFilters = GetSceneMeshes (); if (filteredFilters.Count == 0) { return; } Bounds bounds = new Bounds (); for (int i=0;i<filteredFilters.Count;i++) { if (filteredFilters[i].renderer != null) { bounds = filteredFilters[i].renderer.bounds; break; } } for (int i=0;i<filteredFilters.Count;i++) { if (filteredFilters[i].renderer != null) { bounds.Encapsulate (filteredFilters[i].renderer.bounds); } } forcedBoundsCenter = bounds.center; forcedBoundsSize = bounds.size; } public List<MeshFilter> GetSceneMeshes () { MeshFilter[] filters = GameObject.FindObjectsOfType(typeof(MeshFilter)) as MeshFilter[]; List<MeshFilter> filteredFilters = new List<MeshFilter> (filters.Length/3); for (int i=0;i<filters.Length;i++) { MeshFilter filter = filters[i]; if (filter.renderer != null && filter.renderer.enabled && (((1 << filter.gameObject.layer) & mask) == (1 << filter.gameObject.layer) || tagMask.Contains (filter.tag))) { filteredFilters.Add (filter); } } List<SceneMesh> meshes = new List<SceneMesh>(); #if UNITY_4 bool containedStatic = false; #else HashSet<Mesh> staticMeshes = new HashSet<Mesh>(); #endif foreach (MeshFilter filter in filteredFilters) { //Workaround for statically batched meshes if (filter.renderer.isPartOfStaticBatch) { #if UNITY_4 containedStatic = true; #else Mesh mesh = filter.sharedMesh; if (!staticMeshes.Contains (mesh)) { staticMeshes.Add (mesh); SceneMesh smesh = new SceneMesh(); smesh.mesh = mesh; //This is not the real bounds, it will be expanded later as more renderers are found smesh.bounds = filter.renderer.bounds; smesh.matrix = Matrix4x4.identity; meshes.Add (smesh); } else { SceneMesh smesh; for (int i=0;i<meshes.Count;i++) { if (meshes[i].mesh == mesh) { smesh = meshes[i]; break; } } smesh.bounds.Encapsulate (filter.renderer.bounds); } #endif } else { //Only include it if it intersects with the graph if (filter.renderer.bounds.Intersects (forcedBounds)) { Mesh mesh = filter.sharedMesh; SceneMesh smesh = new SceneMesh(); smesh.matrix = filter.renderer.localToWorldMatrix; smesh.mesh = mesh; smesh.bounds = filter.renderer.bounds; meshes.Add (smesh); } } #if UNITY_4 if (containedStatic) Debug.LogWarning ("Some meshes were statically batched. These meshes can not be used for navmesh calculation" + " due to technical constraints."); #endif } #if ASTARDEBUG int y = 0; foreach (SceneMesh smesh in meshes) { y++; Vector3[] vecs = smesh.mesh.vertices; int[] tris = smesh.mesh.triangles; for (int i=0;i<tris.Length;i+=3) { Vector3 p1 = smesh.matrix.MultiplyPoint3x4(vecs[tris[i+0]]); Vector3 p2 = smesh.matrix.MultiplyPoint3x4(vecs[tris[i+1]]); Vector3 p3 = smesh.matrix.MultiplyPoint3x4(vecs[tris[i+2]]); Debug.DrawLine (p1,p2,Color.red,1); Debug.DrawLine (p2,p3,Color.red,1); Debug.DrawLine (p3,p1,Color.red,1); } } #endif return filteredFilters; } public void UpdateArea (GraphUpdateObject guo) { NavMeshGraph.UpdateArea (guo, this); } public override NNInfo GetNearest (Vector3 position, NNConstraint constraint, Node hint) { return NavMeshGraph.GetNearest (this, nodes,position, constraint, accurateNearestNode); } public override NNInfo GetNearestForce (Vector3 position, NNConstraint constraint) { return NavMeshGraph.GetNearestForce (nodes,vertices,position,constraint, accurateNearestNode); } public void BuildFunnelCorridor (List<Node> path, int startIndex, int endIndex, List<Vector3> left, List<Vector3> right) { NavMeshGraph.BuildFunnelCorridor (this,path,startIndex,endIndex,left,right); } public void AddPortal (Node n1, Node n2, List<Vector3> left, List<Vector3> right) { } /** Represents a unity mesh * * \see ExtraMesh */ public struct SceneMesh { public Mesh mesh; public Matrix4x4 matrix; public Bounds bounds; } /** Represents a custom mesh. * The vertices will be multiplied with the matrix when rasterizing it to voxels. * The vertices and triangles array may be used in multiple instances, it is not changed when voxelizing. * * \see SceneMesh */ public struct ExtraMesh { public Vector3[] vertices; public int[] triangles; /** Assumed to already be multiplied with the matrix */ public Bounds bounds; public Matrix4x4 matrix; public ExtraMesh (Vector3[] v, int[] t, Bounds b) { matrix = Matrix4x4.identity; vertices = v; triangles = t; bounds = b; } public ExtraMesh (Vector3[] v, int[] t, Bounds b, Matrix4x4 matrix) { this.matrix = matrix; vertices = v; triangles = t; bounds = b; } /** Recalculate the bounds based on vertices and matrix */ public void RecalculateBounds () { Bounds b = new Bounds(matrix.MultiplyPoint3x4(vertices[0]),Vector3.zero); for (int i=1;i<vertices.Length;i++) { b.Encapsulate (matrix.MultiplyPoint3x4(vertices[i])); } //Assigned here to avoid changing bounds if vertices would happen to be null bounds = b; } } #if UNITY_EDITOR public static bool IsJsEnabled () { if (System.IO.Directory.Exists (Application.dataPath+"/AstarPathfindingEditor/Editor")) { return true; } return false; } #endif public static string GetRecastPath () { #if UNITY_EDITOR if (IsJsEnabled ()) { return Application.dataPath + "/Plugins/AstarPathfindingProject/recast"; } else { return Application.dataPath + "/AstarPathfindingProject/recast"; } #else return Application.dataPath + "/Recast/recast"; #endif } #if !PhotonImplementation public override void Scan () { AstarProfiler.Reset (); //AstarProfiler.StartProfile ("Base Scan"); //base.Scan (); //AstarProfiler.EndProfile ("Base Scan"); if (useCRecast) { ScanCRecast (); } else { #if ASTARDEBUG Console.WriteLine ("Recast Graph -- Collecting Meshes"); #endif AstarProfiler.StartProfile ("Collecting Meshes"); AstarProfiler.StartProfile ("Collecting Meshes"); MeshFilter[] filters; ExtraMesh[] extraMeshes; if (!CollectMeshes (out filters, out extraMeshes)) { nodes = new Node[0]; return; } AstarProfiler.EndProfile ("Collecting Meshes"); #if ASTARDEBUG Console.WriteLine ("Recast Graph -- Creating Voxel Base"); #endif Voxelize vox = new Voxelize (cellHeight, cellSize, walkableClimb, walkableHeight, maxSlope); vox.maxEdgeLength = maxEdgeLength; vox.forcedBounds = forcedBounds; vox.includeOutOfBounds = includeOutOfBounds; #if ASTARDEBUG Console.WriteLine ("Recast Graph -- Voxelizing"); #endif AstarProfiler.EndProfile ("Collecting Meshes"); //g.GetComponent<Voxelize>(); vox.VoxelizeMesh (filters, extraMeshes); /*bool[,] open = new bool[width,depth]; int[,] visited = new int[width+1,depth+1]; for (int z=0;z<depth;z++) { for (int x = 0;x < width;x++) { open[x,z] = graphNodes[z*width+x].walkable; } }*/ /*for (int i=0;i<depth*width;i++) { open[i] = graphNodes[i].walkable; } int wd = width*depth; List<int> boundary = new List<int>(); int p = 0; for (int i=0;i<wd;i++) { if (!open[i]) { boundary.Add (i); p = i; int backtrack = i-1; }*/ #if ASTARDEBUG Console.WriteLine ("Recast Graph -- Eroding"); #endif vox.ErodeWalkableArea (Mathf.CeilToInt (2*characterRadius/cellSize)); #if ASTARDEBUG Console.WriteLine ("Recast Graph -- Building Distance Field"); #endif vox.BuildDistanceField (); #if ASTARDEBUG Console.WriteLine ("Recast Graph -- Building Regions"); #endif vox.BuildRegions (); #if ASTARDEBUG Console.WriteLine ("Recast Graph -- Building Contours"); #endif VoxelContourSet cset = new VoxelContourSet (); vox.BuildContours (contourMaxError,1,cset,Voxelize.RC_CONTOUR_TESS_WALL_EDGES); #if ASTARDEBUG Console.WriteLine ("Recast Graph -- Building Poly Mesh"); #endif VoxelMesh mesh; vox.BuildPolyMesh (cset,3,out mesh); #if ASTARDEBUG Console.WriteLine ("Recast Graph -- Building Nodes"); #endif Vector3[] vertices = new Vector3[mesh.verts.Length]; AstarProfiler.StartProfile ("Build Nodes"); for (int i=0;i<vertices.Length;i++) { vertices[i] = (Vector3)mesh.verts[i]; } matrix = Matrix4x4.TRS (vox.voxelOffset,Quaternion.identity,Int3.Precision*Voxelize.CellScale); //Int3.Precision*Voxelize.CellScale+(Int3)vox.voxelOffset //GenerateNodes (this,vectorVertices,triangles, out originalVertices, out _vertices); #if ASTARDEBUG Console.WriteLine ("Recast Graph -- Generating Nodes"); #endif NavMeshGraph.GenerateNodes (this,vertices,mesh.tris, out _vectorVertices, out _vertices); AstarProfiler.EndProfile ("Build Nodes"); AstarProfiler.PrintResults (); #if ASTARDEBUG Console.WriteLine ("Recast Graph -- Done"); #endif } } public void ScanCRecast () { //#if (!UNITY_EDITOR && !UNITY_STANDALONE_OSX && !UNITY_STANDALONE_WIN) || UNITY_WEBPLAYER || UNITY_IPHONE || UNITY_ANDROID || UNITY_DASHBOARD_WIDGET || UNITY_XBOX360 || UNITY_PS3 #if (UNITY_STANDALONE_OSX) System.Diagnostics.Process myProcess = new System.Diagnostics.Process(); myProcess.StartInfo.FileName = GetRecastPath ();//"/Users/arong/Recast/build/Debug/Recast"; //System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo (); //startInfo.UseShellExecute = true; myProcess.StartInfo.UseShellExecute = false; myProcess.StartInfo.RedirectStandardInput = true; myProcess.StartInfo.RedirectStandardOutput = true; myProcess.StartInfo.Arguments = ""; MeshFilter[] filters; ExtraMesh[] extraMeshes; //Get all meshes which should be used CollectMeshes (out filters, out extraMeshes); Vector3[] inputVerts; int[] inputTris; //Get polygon soup from meshes Voxelize.CollectMeshes (filters,extraMeshes,forcedBounds,out inputVerts, out inputTris); //Bild .obj file System.Text.StringBuilder arguments = new System.Text.StringBuilder (); arguments.Append ("o recastMesh.obj\n"); for (int i=0;i<inputVerts.Length;i++) { arguments.Append ("v "+inputVerts[i].x.ToString ("0.000")+" ").Append (inputVerts[i].y.ToString ("0.000")+" ").Append (inputVerts[i].z.ToString ("0.000")); arguments.Append ("\n"); } //Build .obj file tris for (int i=0;i<inputTris.Length;i+=3) { arguments.Append ("f "+(inputTris[i]+1)+"//0 ").Append ((inputTris[i+1]+1)+"//0 ").Append ((inputTris[i+2]+1)+"//0"); #if ASTARDEBUG Debug.DrawLine (inputVerts[inputTris[i]],inputVerts[inputTris[i+1]],Color.red); Debug.DrawLine (inputVerts[inputTris[i+1]],inputVerts[inputTris[i+2]],Color.red); Debug.DrawLine (inputVerts[inputTris[i+2]],inputVerts[inputTris[i]],Color.red); #endif arguments.Append ("\n"); } string tmpPath = System.IO.Path.GetTempPath (); tmpPath += "recastMesh.obj"; try { using (System.IO.StreamWriter outfile = new System.IO.StreamWriter(tmpPath)) { outfile.Write (arguments.ToString ()); } myProcess.StartInfo.Arguments = tmpPath +"\n"+cellSize+"\n"+ cellHeight+"\n"+ walkableHeight+"\n"+ walkableClimb+"\n"+ maxSlope+"\n"+ maxEdgeLength+"\n"+ contourMaxError+"\n"+ regionMinSize+"\n"+ characterRadius; /* public int erosionRadius = 2; /< Voxels to erode away from the edges of the mesh / public float contourMaxError = 2F; /< Max distance from simplified edge to real edge / public float cellSize = 0.5F; /< Voxel sample size (x,z) / public float cellHeight = 0.4F; /< Voxel sample size (y) / public float walkableHeight = 2F; /< Character height/ public float walkableClimb = 0.5F; /< Height the character can climb / public float maxSlope = 30; /< Max slope in degrees the character can traverse / public float maxEdgeLength = 20; /< Longer edges will be subdivided. Reducing this value can im public bool useCRecast = true; public bool includeOutOfBounds = false;*/ myProcess.Start (); System.IO.StreamReader sOut = myProcess.StandardOutput; //string result = sOut.ReadToEnd (); //Debug.Log (result); //return; bool failed = false; bool startedVerts = false; int readVerts = 0; bool startedTris = false; int vCount = -1; int readTris = 0; int trisCount = 0; Vector3[] verts = null; int[] tris = null; int internalVertCount = 0; Vector3 bmin = Vector3.zero; float cs = 1F; float ch = 1F; while (sOut.Peek() >= 0) { string line = sOut.ReadLine(); int resultInt; if (line == "") { continue; } if (!int.TryParse (line, out resultInt)) { //Debug.Log ("Syntax Error at '"+line+"'"); failed = true; break; } if (!startedVerts) { verts = new Vector3[resultInt]; if (resultInt == 0) { failed = true; break; } bmin.x = float.Parse (sOut.ReadLine()); bmin.y = float.Parse (sOut.ReadLine()); bmin.z = float.Parse (sOut.ReadLine()); cs = float.Parse (sOut.ReadLine()); ch = float.Parse (sOut.ReadLine()); startedVerts = true; //Debug.Log ("Starting Reading "+resultInt+" verts "+bmin.ToString ()+" - "+cs+" * "+ch); } else if (readVerts < verts.Length) { resultInt *= 1; if (internalVertCount == 0) { verts[readVerts].x = resultInt*cs + bmin.x; } else if (internalVertCount == 1) { verts[readVerts].y = resultInt*ch + bmin.y; } else { verts[readVerts].z = resultInt*cs + bmin.z; } internalVertCount++; if (internalVertCount == 3) { internalVertCount = 0; readVerts++; } } else if (!startedTris) { trisCount = resultInt; startedTris = true; } else if (vCount == -1) { vCount = resultInt; tris = new int[trisCount*vCount]; //Debug.Log ("Starting Reading "+trisCount+" - "+tris.Length+" tris at vertsCount "+readVerts); //Debug.Log ("Max vertices per polygon: "+vCount); } else if (readTris < tris.Length) { tris[readTris] = resultInt; readTris++; } } if (!myProcess.HasExited) { try { myProcess.Kill(); } catch {} } sOut.Close(); myProcess.Close(); if (failed) { Debug.LogError ("C Recast Failed"); return; } matrix = Matrix4x4.TRS (Vector3.zero,Quaternion.identity,Vector3.one); NavMeshGraph.GenerateNodes (this,verts,tris, out _vectorVertices, out _vertices); } finally { //Debug.Log (tmpPath); System.IO.File.Delete (tmpPath); } #else Debug.LogError ("The C++ version of recast can only be used in editor or osx standalone mode, I'm sure it cannot be used in the webplayer, but other platforms are not tested yet\n" + "If you are in the Unity Editor, try switching Platform to OSX Standalone just when scanning, scanned graphs can be cached to enable them to be used in a webplayer"); _vectorVertices = new Vector3[0]; _vertices = new Int3[0]; nodes = new Node[0]; #endif } public void CollectTreeMeshes (List<ExtraMesh> extraMeshes, Terrain terrain) { TerrainData data = terrain.terrainData; for (int i=0;i<data.treeInstances.Length;i++) { TreeInstance instance = data.treeInstances[i]; TreePrototype prot = data.treePrototypes[instance.prototypeIndex]; if (prot.prefab.collider == null) { Bounds b = new Bounds(terrain.transform.position + Vector3.Scale(instance.position,data.size), new Vector3(instance.widthScale,instance.heightScale,instance.widthScale)); Matrix4x4 matrix = Matrix4x4.TRS (terrain.transform.position + Vector3.Scale(instance.position,data.size), Quaternion.identity, new Vector3(instance.widthScale,instance.heightScale,instance.widthScale)*0.5f); ExtraMesh m = new ExtraMesh(BoxColliderVerts,BoxColliderTris, b, matrix); #if ASTARDEBUG Debug.DrawRay (instance.position, Vector3.up, Color.red,1); #endif extraMeshes.Add (m); } else { //The prefab has a collider, use that instead Vector3 pos = terrain.transform.position + Vector3.Scale(instance.position,data.size); Vector3 scale = new Vector3(instance.widthScale,instance.heightScale,instance.widthScale); //Generate a mesh from the collider ExtraMesh m = RasterizeCollider (prot.prefab.collider,Matrix4x4.TRS (pos,Quaternion.identity,scale)); //Make sure a valid mesh was generated if (m.vertices != null) { #if ASTARDEBUG Debug.DrawRay (pos, Vector3.up, Color.yellow,1); #endif //The bounds are incorrectly based on collider.bounds m.RecalculateBounds (); extraMeshes.Add (m); } } } } public bool CollectMeshes (out MeshFilter[] filters, out ExtraMesh[] extraMeshes) { List<MeshFilter> filteredFilters; if (rasterizeMeshes) { filteredFilters = GetSceneMeshes (); } else { filteredFilters = new List<MeshFilter>(); } List<ExtraMesh> extraMeshesList = new List<ExtraMesh> (); Terrain[] terrains = MonoBehaviour.FindObjectsOfType(typeof(Terrain)) as Terrain[]; if (rasterizeTerrain && terrains.Length > 0) { for (int j=0;j<terrains.Length;j++) { TerrainData terrainData = terrains[j].terrainData; if (terrainData == null) continue; Vector3 offset = terrains[j].GetPosition (); Vector3 center = offset + terrainData.size * 0.5F; Bounds b = new Bounds (center, terrainData.size); //Only include terrains which intersects the graph if (!b.Intersects (this.forcedBounds)) continue; float[,] heights = terrainData.GetHeights (0,0,terrainData.heightmapWidth,terrainData.heightmapHeight); terrainSampleSize = terrainSampleSize < 1 ? 1 : terrainSampleSize;//Clamp to at least 1 int hWidth = terrainData.heightmapWidth / terrainSampleSize; int hHeight = terrainData.heightmapHeight / terrainSampleSize; Vector3[] terrainVertices = new Vector3[hWidth*hHeight]; Vector3 hSampleSize = terrainData.heightmapScale; float heightScale = terrainData.size.y; for (int z = 0, nz = 0;nz < hHeight;z+= terrainSampleSize, nz++) { for (int x = 0, nx = 0; nx < hWidth;x+= terrainSampleSize, nx++) { terrainVertices[nz*hWidth + nx] = new Vector3 (z * hSampleSize.z,heights[x,z]*heightScale, x * hSampleSize.x) + offset; } } int[] tris = new int[(hWidth-1)*(hHeight-1)*2*3]; int c = 0; for (int z = 0;z < hHeight-1;z++) { for (int x = 0; x < hWidth-1;x++) { tris[c] = z*hWidth + x; tris[c+1] = z*hWidth + x+1; tris[c+2] = (z+1)*hWidth + x+1; c += 3; tris[c] = z*hWidth + x; tris[c+1] = (z+1)*hWidth + x+1; tris[c+2] = (z+1)*hWidth + x; c += 3; } } #if ASTARDEBUG for (int i=0;i<tris.Length;i+=3) { Debug.DrawLine (terrainVertices[tris[i]],terrainVertices[tris[i+1]],Color.red); Debug.DrawLine (terrainVertices[tris[i+1]],terrainVertices[tris[i+2]],Color.red); Debug.DrawLine (terrainVertices[tris[i+2]],terrainVertices[tris[i]],Color.red); } #endif extraMeshesList.Add (new ExtraMesh (terrainVertices,tris,b)); if (rasterizeTrees) { //Rasterize all tree colliders on this terrain object CollectTreeMeshes (extraMeshesList, terrains[j]); } } } if (rasterizeColliders) { Collider[] colls = MonoBehaviour.FindObjectsOfType (typeof(Collider)) as Collider[]; foreach (Collider col in colls) { if (((1 << col.gameObject.layer) & mask) == (1 << col.gameObject.layer) && col.enabled) { ExtraMesh emesh = RasterizeCollider (col); //Make sure a valid ExtraMesh was returned if (emesh.vertices != null) extraMeshesList.Add (emesh); } } //Clear cache to avoid memory leak capsuleCache.Clear(); } if (filteredFilters.Count == 0 && extraMeshesList.Count == 0) { Debug.LogWarning ("No MeshFilters where found contained in the layers specified by the 'mask' variable"); filters = null; extraMeshes = null; return false; } filters = filteredFilters.ToArray (); extraMeshes = extraMeshesList.ToArray (); return true; } /** Box Collider triangle indices can be reused for multiple instances. * \warning This array should never be changed */ private readonly int[] BoxColliderTris = { 0, 1, 2, 0, 2, 3, 6, 5, 4, 7, 6, 4, 0, 5, 1, 0, 4, 5, 1, 6, 2, 1, 5, 6, 2, 7, 3, 2, 6, 7, 3, 4, 0, 3, 7, 4 }; /** Box Collider vertices can be reused for multiple instances. * \warning This array should never be changed */ private readonly Vector3[] BoxColliderVerts = { new Vector3(-1,-1,-1), new Vector3( 1,-1,-1), new Vector3( 1,-1, 1), new Vector3(-1,-1, 1), new Vector3(-1, 1,-1), new Vector3( 1, 1,-1), new Vector3( 1, 1, 1), new Vector3(-1, 1, 1), }; private List<CapsuleCache> capsuleCache = new List<CapsuleCache>(); class CapsuleCache { public int rows; public float height; public Vector3[] verts; public int[] tris; } /** Rasterizes a collider to a mesh. * This will pass the col.transform.localToWorldMatrix to the other overload of this function. */ public ExtraMesh RasterizeCollider (Collider col) { return RasterizeCollider (col, col.transform.localToWorldMatrix); } /** Rasterizes a collider to a mesh assuming it's vertices should be multiplied with the matrix. * Note that the bounds of the returned ExtraMesh is based on collider.bounds. So you might want to * call myExtraMesh.RecalculateBounds on the returned mesh to recalculate it if the collider.bounds would * not give the correct value. * */ public ExtraMesh RasterizeCollider (Collider col, Matrix4x4 localToWorldMatrix) { if (col is BoxCollider) { BoxCollider collider = col as BoxCollider; Matrix4x4 matrix = Matrix4x4.TRS (collider.center, Quaternion.identity, collider.size*0.5f); matrix = localToWorldMatrix * matrix; Bounds b = collider.bounds; ExtraMesh m = new ExtraMesh(BoxColliderVerts,BoxColliderTris, b, matrix); #if ASTARDEBUG Vector3[] verts = BoxColliderVerts; int[] tris = BoxColliderTris; for (int i=0;i<tris.Length;i+=3) { Debug.DrawLine (matrix.MultiplyPoint3x4(verts[tris[i]]),matrix.MultiplyPoint3x4(verts[tris[i+1]]), Color.yellow); Debug.DrawLine (matrix.MultiplyPoint3x4(verts[tris[i+2]]),matrix.MultiplyPoint3x4(verts[tris[i+1]]), Color.yellow); Debug.DrawLine (matrix.MultiplyPoint3x4(verts[tris[i]]),matrix.MultiplyPoint3x4(verts[tris[i+2]]), Color.yellow); //Normal debug /*Vector3 va = matrix.MultiplyPoint3x4(verts[tris[i]]); Vector3 vb = matrix.MultiplyPoint3x4(verts[tris[i+1]]); Vector3 vc = matrix.MultiplyPoint3x4(verts[tris[i+2]]); Debug.DrawRay ((va+vb+vc)/3, Vector3.Cross(vb-va,vc-va).normalized,Color.blue);*/ } #endif return m; } else if (col is SphereCollider || col is CapsuleCollider) { SphereCollider scollider = col as SphereCollider; CapsuleCollider ccollider = col as CapsuleCollider; float radius = (scollider != null ? scollider.radius : ccollider.radius); float height = scollider != null ? 0 : (ccollider.height*0.5f/radius) - 1; Matrix4x4 matrix = Matrix4x4.TRS (scollider != null ? scollider.center : ccollider.center, Quaternion.identity, Vector3.one*radius); matrix = localToWorldMatrix * matrix; //Calculate the number of rows to use //grows as sqrt(x) to the radius of the sphere/capsule which I have found works quite good int rows = Mathf.Max (4,Mathf.RoundToInt(colliderRasterizeDetail*Mathf.Sqrt(matrix.MultiplyVector(Vector3.one).magnitude))); if (rows > 100) { Debug.LogWarning ("Very large detail for some collider meshes. Consider decreasing Collider Rasterize Detail (RecastGraph)"); } int cols = rows; Vector3[] verts; int[] trisArr; //Check if we have already calculated a similar capsule CapsuleCache cached = null; for (int i=0;i<capsuleCache.Count;i++) { CapsuleCache c = capsuleCache[i]; if (c.rows == rows && Mathf.Approximately (c.height, height)) { cached = c; } } if (cached == null) { //Generate a sphere/capsule mesh verts = new Vector3[(rows)*cols + 2]; List<int> tris = new List<int>(); verts[verts.Length-1] = Vector3.up; for (int r=0;r<rows;r++) { for (int c=0;c<cols;c++) { verts[c + r*cols] = new Vector3 (Mathf.Cos (c*Mathf.PI*2/cols)*Mathf.Sin ((r*Mathf.PI/(rows-1))), Mathf.Cos ((r*Mathf.PI/(rows-1))) + (r < rows/2 ? height : -height) , Mathf.Sin (c*Mathf.PI*2/cols)*Mathf.Sin ((r*Mathf.PI/(rows-1)))); } } verts[verts.Length-2] = Vector3.down; for (int i=0, j = cols-1;i<cols; j = i++) { tris.Add (verts.Length-1); tris.Add (0*cols + j); tris.Add (0*cols + i); } for (int r=1;r<rows;r++) { for (int i=0, j = cols-1;i<cols; j = i++) { tris.Add (r*cols + i); tris.Add (r*cols + j); tris.Add ((r-1)*cols + i); tris.Add ((r-1)*cols + j); tris.Add ((r-1)*cols + i); tris.Add (r*cols + j); } } for (int i=0, j = cols-1;i<cols; j = i++) { tris.Add (verts.Length-2); tris.Add ((rows-1)*cols + j); tris.Add ((rows-1)*cols + i); } //Add calculated mesh to the cache cached = new CapsuleCache (); cached.rows = rows; cached.height = height; cached.verts = verts; cached.tris = tris.ToArray(); capsuleCache.Add (cached); } //Read from cache verts = cached.verts; trisArr = cached.tris; Bounds b = col.bounds; ExtraMesh m = new ExtraMesh(verts,trisArr, b, matrix); #if ASTARDEBUG for (int i=0;i<trisArr.Length;i+=3) { Debug.DrawLine (matrix.MultiplyPoint3x4(verts[trisArr[i]]),matrix.MultiplyPoint3x4(verts[trisArr[i+1]]), Color.yellow); Debug.DrawLine (matrix.MultiplyPoint3x4(verts[trisArr[i+2]]),matrix.MultiplyPoint3x4(verts[trisArr[i+1]]), Color.yellow); Debug.DrawLine (matrix.MultiplyPoint3x4(verts[trisArr[i]]),matrix.MultiplyPoint3x4(verts[trisArr[i+2]]), Color.yellow); //Normal debug /*Vector3 va = matrix.MultiplyPoint3x4(verts[trisArr[i]]); Vector3 vb = matrix.MultiplyPoint3x4(verts[trisArr[i+1]]); Vector3 vc = matrix.MultiplyPoint3x4(verts[trisArr[i+2]]); Debug.DrawRay ((va+vb+vc)/3, Vector3.Cross(vb-va,vc-va).normalized,Color.blue);*/ } #endif return m; } else if (col is MeshCollider) { MeshCollider collider = col as MeshCollider; ExtraMesh m = new ExtraMesh(collider.sharedMesh.vertices, collider.sharedMesh.triangles, collider.bounds, localToWorldMatrix); return m; } return new ExtraMesh(); } #endif public bool Linecast (Vector3 origin, Vector3 end) { return Linecast (origin, end, GetNearest (origin, NNConstraint.None).node); } public bool Linecast (Vector3 origin, Vector3 end, Node hint, out GraphHitInfo hit) { return NavMeshGraph.Linecast (this as INavmesh, origin,end,hint,false,0, out hit); } public bool Linecast (Vector3 origin, Vector3 end, Node hint) { GraphHitInfo hit; return NavMeshGraph.Linecast (this as INavmesh, origin,end,hint,false,0, out hit); } public void Sort (Int3[] a) { bool changed = true; while (changed) { changed = false; for (int i=0;i<a.Length-1;i++) { if (a[i].x > a[i+1].x || (a[i].x == a[i+1].x && (a[i].y > a[i+1].y || (a[i].y == a[i+1].y && a[i].z > a[i+1].z)))) { Int3 tmp = a[i]; a[i] = a[i+1]; a[i+1] = tmp; changed = true; } } } } #if !PhotonImplementation public override void OnDrawGizmos (bool drawNodes) { if (!drawNodes) { return; } if (bbTree != null) { bbTree.OnDrawGizmos (); } Gizmos.DrawWireCube (forcedBounds.center,forcedBounds.size); //base.OnDrawGizmos (drawNodes); if (nodes == null) { //Scan (AstarPath.active.GetGraphIndex (this)); } if (nodes == null) { return; } for (int i=0;i<nodes.Length;i++) { //AstarColor.NodeConnection; MeshNode node = (MeshNode)nodes[i]; if (AstarPath.active.debugPathData != null && AstarPath.active.showSearchTree && node.GetNodeRun(AstarPath.active.debugPathData).parent != null) { //Gizmos.color = new Color (0,1,0,0.7F); Gizmos.color = NodeColor (node,AstarPath.active.debugPathData); Gizmos.DrawLine ((Vector3)node.position,(Vector3)node.GetNodeRun(AstarPath.active.debugPathData).parent.node.position); } else { //for (int q=0;q<node.connections.Length;q++) { // Gizmos.DrawLine (node.position,node.connections[q].position); //} } /*Gizmos.color = AstarColor.MeshEdgeColor; for (int q=0;q<node.connections.Length;q++) { //Gizmos.color = Color.Lerp (Color.green,Color.red,node.connectionCosts[q]/8000F); Gizmos.DrawLine (node.position,node.connections[q].position); }*/ //Gizmos.color = NodeColor (node); //Gizmos.color.a = 0.2F; if (showMeshOutline) { Gizmos.color = NodeColor (node,AstarPath.active.debugPathData); Gizmos.DrawLine ((Vector3)vertices[node.v1],(Vector3)vertices[node.v2]); Gizmos.DrawLine ((Vector3)vertices[node.v2],(Vector3)vertices[node.v3]); Gizmos.DrawLine ((Vector3)vertices[node.v3],(Vector3)vertices[node.v1]); } } } #endif public override byte[] SerializeExtraInfo () { return NavMeshGraph.SerializeMeshNodes (this,nodes); } public override void DeserializeExtraInfo (byte[] bytes) { NavMeshGraph.DeserializeMeshNodes (this,nodes,bytes); } #region OldSerializer public void SerializeNodes (Node[] nodes, AstarSerializer serializer) { NavMeshGraph.SerializeMeshNodes (this as INavmesh, nodes, serializer); } public void DeSerializeNodes (Node[] nodes, AstarSerializer serializer) { NavMeshGraph.DeSerializeMeshNodes (this as INavmesh, nodes, serializer); } public void SerializeSettings (AstarSerializer serializer) { //serializer.AddValue ("erosionRadius",erosionRadius); serializer.AddValue ("contourMaxError",contourMaxError); serializer.AddValue ("cellSize",cellSize); serializer.AddValue ("cellHeight",cellHeight); serializer.AddValue ("walkableHeight",walkableHeight); serializer.AddValue ("walkableClimb",walkableClimb); serializer.AddValue ("maxSlope",maxSlope); serializer.AddValue ("maxEdgeLength",maxEdgeLength); serializer.AddValue ("forcedBoundsCenter",forcedBoundsCenter); serializer.AddValue ("forcedBoundsSize",forcedBoundsSize); serializer.AddValue ("mask",mask.value); serializer.AddValue ("showMeshOutline",showMeshOutline); serializer.AddValue ("includeOutOfBounds",includeOutOfBounds); serializer.AddValue ("regionMinSize",regionMinSize); serializer.AddValue ("characterRadius",characterRadius); serializer.AddValue ("useCRecast",useCRecast); } public void DeSerializeSettings (AstarSerializer serializer) { //erosionRadius = (int)serializer.GetValue ("erosionRadius",typeof(int)); contourMaxError = (float)serializer.GetValue ("contourMaxError",typeof(float)); cellSize = (float)serializer.GetValue ("cellSize",typeof(float)); cellHeight = (float)serializer.GetValue ("cellHeight",typeof(float)); walkableHeight = (float)serializer.GetValue ("walkableHeight",typeof(float)); walkableClimb = (float)serializer.GetValue ("walkableClimb",typeof(float)); maxSlope = (float)serializer.GetValue ("maxSlope",typeof(float)); maxEdgeLength = (float)serializer.GetValue ("maxEdgeLength",typeof(float)); forcedBoundsCenter = (Vector3)serializer.GetValue ("forcedBoundsCenter",typeof(Vector3)); forcedBoundsSize = (Vector3)serializer.GetValue ("forcedBoundsSize",typeof(Vector3)); mask.value = (int)serializer.GetValue ("mask",typeof(int)); showMeshOutline = (bool)serializer.GetValue ("showMeshOutline",typeof(bool)); includeOutOfBounds = (bool)serializer.GetValue ("includeOutOfBounds",typeof(bool)); regionMinSize = (int)serializer.GetValue ("regionMinSize",typeof(int)); characterRadius = (float)serializer.GetValue ("characterRadius",typeof(float)); useCRecast = (bool)serializer.GetValue ("useCRecast",typeof(bool)); } #endregion public struct Int2 { public int x; public int z; public Int2 (int _x, int _z) { x = _x; z = _z; } } } /*------- From Wikipedia ------- Input: A square tessellation, T, containing a connected component P of black cells. Output: A sequence B (b1, b2 ,..., bk) of boundary pixels i.e. the contour. Define M(a) to be the Moore neighborhood of pixel a. Let p denote the current boundary pixel. Let c denote the current pixel under consideration i.e. c is in M(p). */ /*Begin Set B to be empty. From bottom to top and left to right scan the cells of T until a black pixel, s, of P is found. Insert s in B. Set the current boundary point p to s i.e. p=s Backtrack i.e. move to the pixel from which s was entered. Set c to be the next clockwise pixel in M(p). While c not equal to s do If c is black insert c in B set p=c backtrack (move the current pixel c to the pixel from which p was entered) else advance the current pixel c to the next clockwise pixel in M(p) end While End*/ }
using System; using System.ComponentModel; using System.Windows.Forms; using FileHelpers; namespace FileHelpersSamples { /// <summary> /// Run the engine over a fixed length file /// and display the result in a grid /// </summary> public class frmEasySampleFixed : frmFather { private TextBox txtClass; private TextBox txtData; private PropertyGrid grid1; private Button cmdRun; private Label label2; private Label label1; private Label label3; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label4; /// <summary> /// Required designer variable. /// </summary> private Container components = null; public frmEasySampleFixed() { // // Required for Windows Form Designer support // InitializeComponent(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof (frmEasySampleFixed)); this.txtClass = new System.Windows.Forms.TextBox(); this.txtData = new System.Windows.Forms.TextBox(); this.grid1 = new System.Windows.Forms.PropertyGrid(); this.cmdRun = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // pictureBox3 // // // txtClass // this.txtClass.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.txtClass.Location = new System.Drawing.Point(8, 136); this.txtClass.Multiline = true; this.txtClass.Name = "txtClass"; this.txtClass.ReadOnly = true; this.txtClass.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtClass.Size = new System.Drawing.Size(328, 160); this.txtClass.TabIndex = 0; this.txtClass.Text = resources.GetString("txtClass.Text"); this.txtClass.WordWrap = false; // // txtData // this.txtData.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.txtData.Location = new System.Drawing.Point(8, 320); this.txtData.Multiline = true; this.txtData.Name = "txtData"; this.txtData.ReadOnly = true; this.txtData.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.txtData.Size = new System.Drawing.Size(664, 144); this.txtData.TabIndex = 1; this.txtData.Text = resources.GetString("txtData.Text"); this.txtData.WordWrap = false; // // grid1 // this.grid1.HelpVisible = false; this.grid1.LineColor = System.Drawing.SystemColors.ScrollBar; this.grid1.Location = new System.Drawing.Point(344, 136); this.grid1.Name = "grid1"; this.grid1.PropertySort = System.Windows.Forms.PropertySort.Alphabetical; this.grid1.Size = new System.Drawing.Size(320, 160); this.grid1.TabIndex = 2; this.grid1.ToolbarVisible = false; // // cmdRun // this.cmdRun.BackColor = System.Drawing.Color.FromArgb(((int) (((byte) (0)))), ((int) (((byte) (0)))), ((int) (((byte) (110))))); this.cmdRun.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.cmdRun.ForeColor = System.Drawing.Color.Gainsboro; this.cmdRun.Location = new System.Drawing.Point(336, 8); this.cmdRun.Name = "cmdRun"; this.cmdRun.Size = new System.Drawing.Size(152, 32); this.cmdRun.TabIndex = 0; this.cmdRun.Text = "RUN >>"; this.cmdRun.UseVisualStyleBackColor = false; this.cmdRun.Click += new System.EventHandler(this.cmdRun_Click); // // label2 // this.label2.BackColor = System.Drawing.Color.Transparent; this.label2.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label2.ForeColor = System.Drawing.Color.White; this.label2.Location = new System.Drawing.Point(8, 120); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(216, 16); this.label2.TabIndex = 7; this.label2.Text = "Code of the Mapping Class"; // // label1 // this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label1.ForeColor = System.Drawing.Color.White; this.label1.Location = new System.Drawing.Point(344, 120); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(216, 16); this.label1.TabIndex = 8; this.label1.Text = "Output Array"; // // label3 // this.label3.BackColor = System.Drawing.Color.Transparent; this.label3.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label3.ForeColor = System.Drawing.Color.White; this.label3.Location = new System.Drawing.Point(8, 304); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(264, 16); this.label3.TabIndex = 9; this.label3.Text = "Input Data to the FileHelperEngine"; // // textBox1 // this.textBox1.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.textBox1.Location = new System.Drawing.Point(8, 72); this.textBox1.Multiline = true; this.textBox1.Name = "textBox1"; this.textBox1.ReadOnly = true; this.textBox1.Size = new System.Drawing.Size(656, 40); this.textBox1.TabIndex = 13; this.textBox1.Text = "var engine = new FileHelperEngine<CustomersFixed>();\r\n ... = engine.ReadFile(\"in" + "file.txt\")"; this.textBox1.WordWrap = false; // // label4 // this.label4.BackColor = System.Drawing.Color.Transparent; this.label4.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this.label4.ForeColor = System.Drawing.Color.White; this.label4.Location = new System.Drawing.Point(8, 56); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(152, 16); this.label4.TabIndex = 12; this.label4.Text = "Code to Read the File"; // // frmEasySampleFixed // this.AutoScaleBaseSize = new System.Drawing.Size(5, 14); this.ClientSize = new System.Drawing.Size(680, 496); this.Controls.Add(this.label4); this.Controls.Add(this.label1); this.Controls.Add(this.label2); this.Controls.Add(this.cmdRun); this.Controls.Add(this.grid1); this.Controls.Add(this.txtData); this.Controls.Add(this.txtClass); this.Controls.Add(this.label3); this.Controls.Add(this.textBox1); this.Name = "frmEasySampleFixed"; this.Text = "FileHelpers - Easy Fixed Length Example"; this.Controls.SetChildIndex(this.textBox1, 0); this.Controls.SetChildIndex(this.label3, 0); this.Controls.SetChildIndex(this.txtClass, 0); this.Controls.SetChildIndex(this.txtData, 0); this.Controls.SetChildIndex(this.grid1, 0); this.Controls.SetChildIndex(this.cmdRun, 0); this.Controls.SetChildIndex(this.label2, 0); this.Controls.SetChildIndex(this.label1, 0); this.Controls.SetChildIndex(this.label4, 0); this.ResumeLayout(false); this.PerformLayout(); } #endregion /// <summary> /// Run the engine over a grid and display /// the result in a grid /// </summary> private void cmdRun_Click(object sender, EventArgs e) { var engine = new FileHelperEngine<CustomersFixed>(); grid1.SelectedObject = engine.ReadString(txtData.Text); ; } } }
// // (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. // namespace Revit.SDK.Samples.NewRebar.CS { partial class NewRebarForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.okButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.rebarShapesGroupBox = new System.Windows.Forms.GroupBox(); this.shapesComboBox = new System.Windows.Forms.ComboBox(); this.createShapeButton = new System.Windows.Forms.Button(); this.rebarBarTypeGroupBox = new System.Windows.Forms.GroupBox(); this.barTypesComboBox = new System.Windows.Forms.ComboBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.nameLabel = new System.Windows.Forms.Label(); this.nameTextBox = new System.Windows.Forms.TextBox(); this.arcTypecomboBox = new System.Windows.Forms.ComboBox(); this.segmentCountTextBox = new System.Windows.Forms.TextBox(); this.bySegmentsradioButton = new System.Windows.Forms.RadioButton(); this.byArcradioButton = new System.Windows.Forms.RadioButton(); this.rebarShapesGroupBox.SuspendLayout(); this.rebarBarTypeGroupBox.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // okButton // this.okButton.Location = new System.Drawing.Point(141, 233); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(89, 26); this.okButton.TabIndex = 4; this.okButton.Text = "&OK"; this.okButton.UseVisualStyleBackColor = true; this.okButton.Click += new System.EventHandler(this.okButton_Click); // // cancelButton // this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Location = new System.Drawing.Point(252, 233); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(89, 26); this.cancelButton.TabIndex = 5; this.cancelButton.Text = "&Cancel"; this.cancelButton.UseVisualStyleBackColor = true; this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); // // rebarShapesGroupBox // this.rebarShapesGroupBox.Controls.Add(this.shapesComboBox); this.rebarShapesGroupBox.Location = new System.Drawing.Point(26, 12); this.rebarShapesGroupBox.Name = "rebarShapesGroupBox"; this.rebarShapesGroupBox.Size = new System.Drawing.Size(204, 77); this.rebarShapesGroupBox.TabIndex = 7; this.rebarShapesGroupBox.TabStop = false; this.rebarShapesGroupBox.Text = "RebarShape"; // // shapesComboBox // this.shapesComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.shapesComboBox.FormattingEnabled = true; this.shapesComboBox.Location = new System.Drawing.Point(31, 31); this.shapesComboBox.Name = "shapesComboBox"; this.shapesComboBox.Size = new System.Drawing.Size(149, 21); this.shapesComboBox.TabIndex = 8; // // createShapeButton // this.createShapeButton.Location = new System.Drawing.Point(20, 151); this.createShapeButton.Name = "createShapeButton"; this.createShapeButton.Size = new System.Drawing.Size(162, 29); this.createShapeButton.TabIndex = 9; this.createShapeButton.Text = "Create Rebar &Shape ..."; this.createShapeButton.UseVisualStyleBackColor = true; this.createShapeButton.Click += new System.EventHandler(this.createShapeButton_Click); // // rebarBarTypeGroupBox // this.rebarBarTypeGroupBox.Controls.Add(this.barTypesComboBox); this.rebarBarTypeGroupBox.Location = new System.Drawing.Point(26, 116); this.rebarBarTypeGroupBox.Name = "rebarBarTypeGroupBox"; this.rebarBarTypeGroupBox.Size = new System.Drawing.Size(204, 82); this.rebarBarTypeGroupBox.TabIndex = 8; this.rebarBarTypeGroupBox.TabStop = false; this.rebarBarTypeGroupBox.Text = "RebarBarType"; // // barTypesComboBox // this.barTypesComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.barTypesComboBox.FormattingEnabled = true; this.barTypesComboBox.Location = new System.Drawing.Point(30, 35); this.barTypesComboBox.Name = "barTypesComboBox"; this.barTypesComboBox.Size = new System.Drawing.Size(150, 21); this.barTypesComboBox.TabIndex = 1; // // groupBox2 // this.groupBox2.Controls.Add(this.nameLabel); this.groupBox2.Controls.Add(this.nameTextBox); this.groupBox2.Controls.Add(this.arcTypecomboBox); this.groupBox2.Controls.Add(this.segmentCountTextBox); this.groupBox2.Controls.Add(this.bySegmentsradioButton); this.groupBox2.Controls.Add(this.byArcradioButton); this.groupBox2.Controls.Add(this.createShapeButton); this.groupBox2.Location = new System.Drawing.Point(249, 12); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(213, 186); this.groupBox2.TabIndex = 11; this.groupBox2.TabStop = false; this.groupBox2.Text = "Create Rebar Shape"; // // nameLabel // this.nameLabel.AutoSize = true; this.nameLabel.Location = new System.Drawing.Point(20, 36); this.nameLabel.Name = "nameLabel"; this.nameLabel.Size = new System.Drawing.Size(35, 13); this.nameLabel.TabIndex = 21; this.nameLabel.Text = "Name"; // // nameTextBox // this.nameTextBox.Location = new System.Drawing.Point(79, 31); this.nameTextBox.Name = "nameTextBox"; this.nameTextBox.Size = new System.Drawing.Size(103, 20); this.nameTextBox.TabIndex = 20; // // arcTypecomboBox // this.arcTypecomboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.arcTypecomboBox.FormattingEnabled = true; this.arcTypecomboBox.Location = new System.Drawing.Point(79, 68); this.arcTypecomboBox.Name = "arcTypecomboBox"; this.arcTypecomboBox.Size = new System.Drawing.Size(103, 21); this.arcTypecomboBox.TabIndex = 19; // // segmentCountTextBox // this.segmentCountTextBox.Enabled = false; this.segmentCountTextBox.Location = new System.Drawing.Point(108, 103); this.segmentCountTextBox.Name = "segmentCountTextBox"; this.segmentCountTextBox.Size = new System.Drawing.Size(74, 20); this.segmentCountTextBox.TabIndex = 18; // // bySegmentsradioButton // this.bySegmentsradioButton.AutoSize = true; this.bySegmentsradioButton.Location = new System.Drawing.Point(20, 104); this.bySegmentsradioButton.Name = "bySegmentsradioButton"; this.bySegmentsradioButton.Size = new System.Drawing.Size(87, 17); this.bySegmentsradioButton.TabIndex = 17; this.bySegmentsradioButton.Text = "By Segments"; this.bySegmentsradioButton.UseVisualStyleBackColor = true; this.bySegmentsradioButton.CheckedChanged += new System.EventHandler(this.bySegmentsradioButton_CheckedChanged); // // byArcradioButton // this.byArcradioButton.AutoSize = true; this.byArcradioButton.Checked = true; this.byArcradioButton.Location = new System.Drawing.Point(20, 72); this.byArcradioButton.Name = "byArcradioButton"; this.byArcradioButton.Size = new System.Drawing.Size(56, 17); this.byArcradioButton.TabIndex = 16; this.byArcradioButton.TabStop = true; this.byArcradioButton.Text = "By Arc"; this.byArcradioButton.UseVisualStyleBackColor = true; this.byArcradioButton.CheckedChanged += new System.EventHandler(this.byArcradioButton_CheckedChanged); // // NewRebarForm // this.AcceptButton = this.okButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.cancelButton; this.ClientSize = new System.Drawing.Size(484, 281); this.Controls.Add(this.groupBox2); this.Controls.Add(this.rebarBarTypeGroupBox); this.Controls.Add(this.rebarShapesGroupBox); this.Controls.Add(this.cancelButton); this.Controls.Add(this.okButton); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "NewRebarForm"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Create Rebar"; this.Load += new System.EventHandler(this.NewRebarForm_Load); this.rebarShapesGroupBox.ResumeLayout(false); this.rebarBarTypeGroupBox.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button okButton; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.GroupBox rebarShapesGroupBox; private System.Windows.Forms.Button createShapeButton; private System.Windows.Forms.ComboBox shapesComboBox; private System.Windows.Forms.GroupBox rebarBarTypeGroupBox; private System.Windows.Forms.ComboBox barTypesComboBox; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Label nameLabel; private System.Windows.Forms.TextBox nameTextBox; private System.Windows.Forms.ComboBox arcTypecomboBox; private System.Windows.Forms.TextBox segmentCountTextBox; private System.Windows.Forms.RadioButton bySegmentsradioButton; private System.Windows.Forms.RadioButton byArcradioButton; } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.Serialization.Formatters; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; using System.Runtime.Serialization; using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; namespace Newtonsoft.Json { /// <summary> /// Serializes and deserializes objects into and from the JSON format. /// The <see cref="JsonSerializer"/> enables you to control how objects are encoded into JSON. /// </summary> public class JsonSerializer { internal TypeNameHandling _typeNameHandling; internal TypeNameAssemblyFormatHandling _typeNameAssemblyFormatHandling; internal PreserveReferencesHandling _preserveReferencesHandling; internal ReferenceLoopHandling _referenceLoopHandling; internal MissingMemberHandling _missingMemberHandling; internal ObjectCreationHandling _objectCreationHandling; internal NullValueHandling _nullValueHandling; internal DefaultValueHandling _defaultValueHandling; internal ConstructorHandling _constructorHandling; internal MetadataPropertyHandling _metadataPropertyHandling; internal JsonConverterCollection _converters; internal IContractResolver _contractResolver; internal ITraceWriter _traceWriter; internal IEqualityComparer _equalityComparer; internal ISerializationBinder _serializationBinder; internal StreamingContext _context; private IReferenceResolver _referenceResolver; private Formatting? _formatting; private DateFormatHandling? _dateFormatHandling; private DateTimeZoneHandling? _dateTimeZoneHandling; private DateParseHandling? _dateParseHandling; private FloatFormatHandling? _floatFormatHandling; private FloatParseHandling? _floatParseHandling; private StringEscapeHandling? _stringEscapeHandling; private CultureInfo _culture; private int? _maxDepth; private bool _maxDepthSet; private bool? _checkAdditionalContent; private string _dateFormatString; private bool _dateFormatStringSet; /// <summary> /// Occurs when the <see cref="JsonSerializer"/> errors during serialization and deserialization. /// </summary> public virtual event EventHandler<ErrorEventArgs> Error; /// <summary> /// Gets or sets the <see cref="IReferenceResolver"/> used by the serializer when resolving references. /// </summary> public virtual IReferenceResolver ReferenceResolver { get => GetReferenceResolver(); set { if (value == null) { throw new ArgumentNullException(nameof(value), "Reference resolver cannot be null."); } _referenceResolver = value; } } /// <summary> /// Gets or sets the <see cref="SerializationBinder"/> used by the serializer when resolving type names. /// </summary> [Obsolete("Binder is obsolete. Use SerializationBinder instead.")] public virtual SerializationBinder Binder { get { if (_serializationBinder == null) { return null; } if (_serializationBinder is SerializationBinder legacySerializationBinder) { return legacySerializationBinder; } if (_serializationBinder is SerializationBinderAdapter adapter) { return adapter.SerializationBinder; } throw new InvalidOperationException("Cannot get SerializationBinder because an ISerializationBinder was previously set."); } set { if (value == null) { throw new ArgumentNullException(nameof(value), "Serialization binder cannot be null."); } _serializationBinder = value as ISerializationBinder ?? new SerializationBinderAdapter(value); } } /// <summary> /// Gets or sets the <see cref="ISerializationBinder"/> used by the serializer when resolving type names. /// </summary> public virtual ISerializationBinder SerializationBinder { get => _serializationBinder; set { if (value == null) { throw new ArgumentNullException(nameof(value), "Serialization binder cannot be null."); } _serializationBinder = value; } } /// <summary> /// Gets or sets the <see cref="ITraceWriter"/> used by the serializer when writing trace messages. /// </summary> /// <value>The trace writer.</value> public virtual ITraceWriter TraceWriter { get => _traceWriter; set => _traceWriter = value; } /// <summary> /// Gets or sets the equality comparer used by the serializer when comparing references. /// </summary> /// <value>The equality comparer.</value> public virtual IEqualityComparer EqualityComparer { get => _equalityComparer; set => _equalityComparer = value; } /// <summary> /// Gets or sets how type name writing and reading is handled by the serializer. /// The default value is <see cref="Json.TypeNameHandling.None" />. /// </summary> /// <remarks> /// <see cref="JsonSerializer.TypeNameHandling"/> should be used with caution when your application deserializes JSON from an external source. /// Incoming types should be validated with a custom <see cref="JsonSerializer.SerializationBinder"/> /// when deserializing with a value other than <see cref="TypeNameHandling.None"/>. /// </remarks> public virtual TypeNameHandling TypeNameHandling { get => _typeNameHandling; set { if (value < TypeNameHandling.None || value > TypeNameHandling.Auto) { throw new ArgumentOutOfRangeException(nameof(value)); } _typeNameHandling = value; } } /// <summary> /// Gets or sets how a type name assembly is written and resolved by the serializer. /// The default value is <see cref="FormatterAssemblyStyle.Simple" />. /// </summary> /// <value>The type name assembly format.</value> [Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")] public virtual FormatterAssemblyStyle TypeNameAssemblyFormat { get => (FormatterAssemblyStyle)_typeNameAssemblyFormatHandling; set { if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full) { throw new ArgumentOutOfRangeException(nameof(value)); } _typeNameAssemblyFormatHandling = (TypeNameAssemblyFormatHandling)value; } } /// <summary> /// Gets or sets how a type name assembly is written and resolved by the serializer. /// The default value is <see cref="Json.TypeNameAssemblyFormatHandling.Simple" />. /// </summary> /// <value>The type name assembly format.</value> public virtual TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling { get => _typeNameAssemblyFormatHandling; set { if (value < TypeNameAssemblyFormatHandling.Simple || value > TypeNameAssemblyFormatHandling.Full) { throw new ArgumentOutOfRangeException(nameof(value)); } _typeNameAssemblyFormatHandling = value; } } /// <summary> /// Gets or sets how object references are preserved by the serializer. /// The default value is <see cref="Json.PreserveReferencesHandling.None" />. /// </summary> public virtual PreserveReferencesHandling PreserveReferencesHandling { get => _preserveReferencesHandling; set { if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All) { throw new ArgumentOutOfRangeException(nameof(value)); } _preserveReferencesHandling = value; } } /// <summary> /// Gets or sets how reference loops (e.g. a class referencing itself) is handled. /// The default value is <see cref="Json.ReferenceLoopHandling.Error" />. /// </summary> public virtual ReferenceLoopHandling ReferenceLoopHandling { get => _referenceLoopHandling; set { if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize) { throw new ArgumentOutOfRangeException(nameof(value)); } _referenceLoopHandling = value; } } /// <summary> /// Gets or sets how missing members (e.g. JSON contains a property that isn't a member on the object) are handled during deserialization. /// The default value is <see cref="Json.MissingMemberHandling.Ignore" />. /// </summary> public virtual MissingMemberHandling MissingMemberHandling { get => _missingMemberHandling; set { if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error) { throw new ArgumentOutOfRangeException(nameof(value)); } _missingMemberHandling = value; } } /// <summary> /// Gets or sets how null values are handled during serialization and deserialization. /// The default value is <see cref="Json.NullValueHandling.Include" />. /// </summary> public virtual NullValueHandling NullValueHandling { get => _nullValueHandling; set { if (value < NullValueHandling.Include || value > NullValueHandling.Ignore) { throw new ArgumentOutOfRangeException(nameof(value)); } _nullValueHandling = value; } } /// <summary> /// Gets or sets how default values are handled during serialization and deserialization. /// The default value is <see cref="Json.DefaultValueHandling.Include" />. /// </summary> public virtual DefaultValueHandling DefaultValueHandling { get => _defaultValueHandling; set { if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate) { throw new ArgumentOutOfRangeException(nameof(value)); } _defaultValueHandling = value; } } /// <summary> /// Gets or sets how objects are created during deserialization. /// The default value is <see cref="Json.ObjectCreationHandling.Auto" />. /// </summary> /// <value>The object creation handling.</value> public virtual ObjectCreationHandling ObjectCreationHandling { get => _objectCreationHandling; set { if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace) { throw new ArgumentOutOfRangeException(nameof(value)); } _objectCreationHandling = value; } } /// <summary> /// Gets or sets how constructors are used during deserialization. /// The default value is <see cref="Json.ConstructorHandling.Default" />. /// </summary> /// <value>The constructor handling.</value> public virtual ConstructorHandling ConstructorHandling { get => _constructorHandling; set { if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor) { throw new ArgumentOutOfRangeException(nameof(value)); } _constructorHandling = value; } } /// <summary> /// Gets or sets how metadata properties are used during deserialization. /// The default value is <see cref="Json.MetadataPropertyHandling.Default" />. /// </summary> /// <value>The metadata properties handling.</value> public virtual MetadataPropertyHandling MetadataPropertyHandling { get => _metadataPropertyHandling; set { if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore) { throw new ArgumentOutOfRangeException(nameof(value)); } _metadataPropertyHandling = value; } } /// <summary> /// Gets a collection <see cref="JsonConverter"/> that will be used during serialization. /// </summary> /// <value>Collection <see cref="JsonConverter"/> that will be used during serialization.</value> public virtual JsonConverterCollection Converters { get { if (_converters == null) { _converters = new JsonConverterCollection(); } return _converters; } } /// <summary> /// Gets or sets the contract resolver used by the serializer when /// serializing .NET objects to JSON and vice versa. /// </summary> public virtual IContractResolver ContractResolver { get => _contractResolver; set => _contractResolver = value ?? DefaultContractResolver.Instance; } /// <summary> /// Gets or sets the <see cref="StreamingContext"/> used by the serializer when invoking serialization callback methods. /// </summary> /// <value>The context.</value> public virtual StreamingContext Context { get => _context; set => _context = value; } /// <summary> /// Indicates how JSON text output is formatted. /// The default value is <see cref="Json.Formatting.None" />. /// </summary> public virtual Formatting Formatting { get => _formatting ?? JsonSerializerSettings.DefaultFormatting; set => _formatting = value; } /// <summary> /// Gets or sets how dates are written to JSON text. /// The default value is <see cref="Json.DateFormatHandling.IsoDateFormat" />. /// </summary> public virtual DateFormatHandling DateFormatHandling { get => _dateFormatHandling ?? JsonSerializerSettings.DefaultDateFormatHandling; set => _dateFormatHandling = value; } /// <summary> /// Gets or sets how <see cref="DateTime"/> time zones are handled during serialization and deserialization. /// The default value is <see cref="Json.DateTimeZoneHandling.RoundtripKind" />. /// </summary> public virtual DateTimeZoneHandling DateTimeZoneHandling { get => _dateTimeZoneHandling ?? JsonSerializerSettings.DefaultDateTimeZoneHandling; set => _dateTimeZoneHandling = value; } /// <summary> /// Gets or sets how date formatted strings, e.g. <c>"\/Date(1198908717056)\/"</c> and <c>"2012-03-21T05:40Z"</c>, are parsed when reading JSON. /// The default value is <see cref="Json.DateParseHandling.DateTime" />. /// </summary> public virtual DateParseHandling DateParseHandling { get => _dateParseHandling ?? JsonSerializerSettings.DefaultDateParseHandling; set => _dateParseHandling = value; } /// <summary> /// Gets or sets how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text. /// The default value is <see cref="Json.FloatParseHandling.Double" />. /// </summary> public virtual FloatParseHandling FloatParseHandling { get => _floatParseHandling ?? JsonSerializerSettings.DefaultFloatParseHandling; set => _floatParseHandling = value; } /// <summary> /// Gets or sets how special floating point numbers, e.g. <see cref="Double.NaN"/>, /// <see cref="Double.PositiveInfinity"/> and <see cref="Double.NegativeInfinity"/>, /// are written as JSON text. /// The default value is <see cref="Json.FloatFormatHandling.String" />. /// </summary> public virtual FloatFormatHandling FloatFormatHandling { get => _floatFormatHandling ?? JsonSerializerSettings.DefaultFloatFormatHandling; set => _floatFormatHandling = value; } /// <summary> /// Gets or sets how strings are escaped when writing JSON text. /// The default value is <see cref="Json.StringEscapeHandling.Default" />. /// </summary> public virtual StringEscapeHandling StringEscapeHandling { get => _stringEscapeHandling ?? JsonSerializerSettings.DefaultStringEscapeHandling; set => _stringEscapeHandling = value; } /// <summary> /// Gets or sets how <see cref="DateTime"/> and <see cref="DateTimeOffset"/> values are formatted when writing JSON text, /// and the expected date format when reading JSON text. /// The default value is <c>"yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"</c>. /// </summary> public virtual string DateFormatString { get => _dateFormatString ?? JsonSerializerSettings.DefaultDateFormatString; set { _dateFormatString = value; _dateFormatStringSet = true; } } /// <summary> /// Gets or sets the culture used when reading JSON. /// The default value is <see cref="CultureInfo.InvariantCulture"/>. /// </summary> public virtual CultureInfo Culture { get => _culture ?? JsonSerializerSettings.DefaultCulture; set => _culture = value; } /// <summary> /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>. /// A null value means there is no maximum. /// The default value is <c>null</c>. /// </summary> public virtual int? MaxDepth { get => _maxDepth; set { if (value <= 0) { throw new ArgumentException("Value must be positive.", nameof(value)); } _maxDepth = value; _maxDepthSet = true; } } /// <summary> /// Gets a value indicating whether there will be a check for additional JSON content after deserializing an object. /// The default value is <c>false</c>. /// </summary> /// <value> /// <c>true</c> if there will be a check for additional JSON content after deserializing an object; otherwise, <c>false</c>. /// </value> public virtual bool CheckAdditionalContent { get => _checkAdditionalContent ?? JsonSerializerSettings.DefaultCheckAdditionalContent; set => _checkAdditionalContent = value; } internal bool IsCheckAdditionalContentSet() { return (_checkAdditionalContent != null); } /// <summary> /// Initializes a new instance of the <see cref="JsonSerializer"/> class. /// </summary> public JsonSerializer() { _referenceLoopHandling = JsonSerializerSettings.DefaultReferenceLoopHandling; _missingMemberHandling = JsonSerializerSettings.DefaultMissingMemberHandling; _nullValueHandling = JsonSerializerSettings.DefaultNullValueHandling; _defaultValueHandling = JsonSerializerSettings.DefaultDefaultValueHandling; _objectCreationHandling = JsonSerializerSettings.DefaultObjectCreationHandling; _preserveReferencesHandling = JsonSerializerSettings.DefaultPreserveReferencesHandling; _constructorHandling = JsonSerializerSettings.DefaultConstructorHandling; _typeNameHandling = JsonSerializerSettings.DefaultTypeNameHandling; _metadataPropertyHandling = JsonSerializerSettings.DefaultMetadataPropertyHandling; _context = JsonSerializerSettings.DefaultContext; _serializationBinder = DefaultSerializationBinder.Instance; _culture = JsonSerializerSettings.DefaultCulture; _contractResolver = DefaultContractResolver.Instance; } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will not use default settings /// from <see cref="JsonConvert.DefaultSettings"/>. /// </summary> /// <returns> /// A new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will not use default settings /// from <see cref="JsonConvert.DefaultSettings"/>. /// </returns> public static JsonSerializer Create() { return new JsonSerializer(); } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>. /// The <see cref="JsonSerializer"/> will not use default settings /// from <see cref="JsonConvert.DefaultSettings"/>. /// </summary> /// <param name="settings">The settings to be applied to the <see cref="JsonSerializer"/>.</param> /// <returns> /// A new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>. /// The <see cref="JsonSerializer"/> will not use default settings /// from <see cref="JsonConvert.DefaultSettings"/>. /// </returns> public static JsonSerializer Create(JsonSerializerSettings settings) { JsonSerializer serializer = Create(); if (settings != null) { ApplySerializerSettings(serializer, settings); } return serializer; } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will use default settings /// from <see cref="JsonConvert.DefaultSettings"/>. /// </summary> /// <returns> /// A new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will use default settings /// from <see cref="JsonConvert.DefaultSettings"/>. /// </returns> public static JsonSerializer CreateDefault() { // copy static to local variable to avoid concurrency issues JsonSerializerSettings defaultSettings = JsonConvert.DefaultSettings?.Invoke(); return Create(defaultSettings); } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>. /// The <see cref="JsonSerializer"/> will use default settings /// from <see cref="JsonConvert.DefaultSettings"/> as well as the specified <see cref="JsonSerializerSettings"/>. /// </summary> /// <param name="settings">The settings to be applied to the <see cref="JsonSerializer"/>.</param> /// <returns> /// A new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>. /// The <see cref="JsonSerializer"/> will use default settings /// from <see cref="JsonConvert.DefaultSettings"/> as well as the specified <see cref="JsonSerializerSettings"/>. /// </returns> public static JsonSerializer CreateDefault(JsonSerializerSettings settings) { JsonSerializer serializer = CreateDefault(); if (settings != null) { ApplySerializerSettings(serializer, settings); } return serializer; } private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings) { if (!CollectionUtils.IsNullOrEmpty(settings.Converters)) { // insert settings converters at the beginning so they take precedence // if user wants to remove one of the default converters they will have to do it manually for (int i = 0; i < settings.Converters.Count; i++) { serializer.Converters.Insert(i, settings.Converters[i]); } } // serializer specific if (settings._typeNameHandling != null) { serializer.TypeNameHandling = settings.TypeNameHandling; } if (settings._metadataPropertyHandling != null) { serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling; } if (settings._typeNameAssemblyFormatHandling != null) { serializer.TypeNameAssemblyFormatHandling = settings.TypeNameAssemblyFormatHandling; } if (settings._preserveReferencesHandling != null) { serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling; } if (settings._referenceLoopHandling != null) { serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling; } if (settings._missingMemberHandling != null) { serializer.MissingMemberHandling = settings.MissingMemberHandling; } if (settings._objectCreationHandling != null) { serializer.ObjectCreationHandling = settings.ObjectCreationHandling; } if (settings._nullValueHandling != null) { serializer.NullValueHandling = settings.NullValueHandling; } if (settings._defaultValueHandling != null) { serializer.DefaultValueHandling = settings.DefaultValueHandling; } if (settings._constructorHandling != null) { serializer.ConstructorHandling = settings.ConstructorHandling; } if (settings._context != null) { serializer.Context = settings.Context; } if (settings._checkAdditionalContent != null) { serializer._checkAdditionalContent = settings._checkAdditionalContent; } if (settings.Error != null) { serializer.Error += settings.Error; } if (settings.ContractResolver != null) { serializer.ContractResolver = settings.ContractResolver; } if (settings.ReferenceResolverProvider != null) { serializer.ReferenceResolver = settings.ReferenceResolverProvider(); } if (settings.TraceWriter != null) { serializer.TraceWriter = settings.TraceWriter; } if (settings.EqualityComparer != null) { serializer.EqualityComparer = settings.EqualityComparer; } if (settings.SerializationBinder != null) { serializer.SerializationBinder = settings.SerializationBinder; } // reader/writer specific // unset values won't override reader/writer set values if (settings._formatting != null) { serializer._formatting = settings._formatting; } if (settings._dateFormatHandling != null) { serializer._dateFormatHandling = settings._dateFormatHandling; } if (settings._dateTimeZoneHandling != null) { serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling; } if (settings._dateParseHandling != null) { serializer._dateParseHandling = settings._dateParseHandling; } if (settings._dateFormatStringSet) { serializer._dateFormatString = settings._dateFormatString; serializer._dateFormatStringSet = settings._dateFormatStringSet; } if (settings._floatFormatHandling != null) { serializer._floatFormatHandling = settings._floatFormatHandling; } if (settings._floatParseHandling != null) { serializer._floatParseHandling = settings._floatParseHandling; } if (settings._stringEscapeHandling != null) { serializer._stringEscapeHandling = settings._stringEscapeHandling; } if (settings._culture != null) { serializer._culture = settings._culture; } if (settings._maxDepthSet) { serializer._maxDepth = settings._maxDepth; serializer._maxDepthSet = settings._maxDepthSet; } } /// <summary> /// Populates the JSON values onto the target object. /// </summary> /// <param name="reader">The <see cref="TextReader"/> that contains the JSON structure to reader values from.</param> /// <param name="target">The target object to populate values onto.</param> public void Populate(TextReader reader, object target) { Populate(new JsonTextReader(reader), target); } /// <summary> /// Populates the JSON values onto the target object. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to reader values from.</param> /// <param name="target">The target object to populate values onto.</param> public void Populate(JsonReader reader, object target) { PopulateInternal(reader, target); } internal virtual void PopulateInternal(JsonReader reader, object target) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); ValidationUtils.ArgumentNotNull(target, nameof(target)); // set serialization options onto reader CultureInfo previousCulture; DateTimeZoneHandling? previousDateTimeZoneHandling; DateParseHandling? previousDateParseHandling; FloatParseHandling? previousFloatParseHandling; int? previousMaxDepth; string previousDateFormatString; SetupReader(reader, out previousCulture, out previousDateTimeZoneHandling, out previousDateParseHandling, out previousFloatParseHandling, out previousMaxDepth, out previousDateFormatString); TraceJsonReader traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null; JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this); serializerReader.Populate(traceJsonReader ?? reader, target); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); } /// <summary> /// Deserializes the JSON structure contained by the specified <see cref="JsonReader"/>. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to deserialize.</param> /// <returns>The <see cref="Object"/> being deserialized.</returns> public object Deserialize(JsonReader reader) { return Deserialize(reader, null); } /// <summary> /// Deserializes the JSON structure contained by the specified <see cref="StringReader"/> /// into an instance of the specified type. /// </summary> /// <param name="reader">The <see cref="TextReader"/> containing the object.</param> /// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param> /// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns> public object Deserialize(TextReader reader, Type objectType) { return Deserialize(new JsonTextReader(reader), objectType); } /// <summary> /// Deserializes the JSON structure contained by the specified <see cref="JsonReader"/> /// into an instance of the specified type. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> containing the object.</param> /// <typeparam name="T">The type of the object to deserialize.</typeparam> /// <returns>The instance of <typeparamref name="T"/> being deserialized.</returns> public T Deserialize<T>(JsonReader reader) { return (T)Deserialize(reader, typeof(T)); } /// <summary> /// Deserializes the JSON structure contained by the specified <see cref="JsonReader"/> /// into an instance of the specified type. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> containing the object.</param> /// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param> /// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns> public object Deserialize(JsonReader reader, Type objectType) { return DeserializeInternal(reader, objectType); } internal virtual object DeserializeInternal(JsonReader reader, Type objectType) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); // set serialization options onto reader CultureInfo previousCulture; DateTimeZoneHandling? previousDateTimeZoneHandling; DateParseHandling? previousDateParseHandling; FloatParseHandling? previousFloatParseHandling; int? previousMaxDepth; string previousDateFormatString; SetupReader(reader, out previousCulture, out previousDateTimeZoneHandling, out previousDateParseHandling, out previousFloatParseHandling, out previousMaxDepth, out previousDateFormatString); TraceJsonReader traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null; JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this); object value = serializerReader.Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); return value; } private void SetupReader(JsonReader reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString) { if (_culture != null && !_culture.Equals(reader.Culture)) { previousCulture = reader.Culture; reader.Culture = _culture; } else { previousCulture = null; } if (_dateTimeZoneHandling != null && reader.DateTimeZoneHandling != _dateTimeZoneHandling) { previousDateTimeZoneHandling = reader.DateTimeZoneHandling; reader.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } else { previousDateTimeZoneHandling = null; } if (_dateParseHandling != null && reader.DateParseHandling != _dateParseHandling) { previousDateParseHandling = reader.DateParseHandling; reader.DateParseHandling = _dateParseHandling.GetValueOrDefault(); } else { previousDateParseHandling = null; } if (_floatParseHandling != null && reader.FloatParseHandling != _floatParseHandling) { previousFloatParseHandling = reader.FloatParseHandling; reader.FloatParseHandling = _floatParseHandling.GetValueOrDefault(); } else { previousFloatParseHandling = null; } if (_maxDepthSet && reader.MaxDepth != _maxDepth) { previousMaxDepth = reader.MaxDepth; reader.MaxDepth = _maxDepth; } else { previousMaxDepth = null; } if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString) { previousDateFormatString = reader.DateFormatString; reader.DateFormatString = _dateFormatString; } else { previousDateFormatString = null; } if (reader is JsonTextReader textReader) { if (_contractResolver is DefaultContractResolver resolver) { textReader.NameTable = resolver.GetNameTable(); } } } private void ResetReader(JsonReader reader, CultureInfo previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string previousDateFormatString) { // reset reader back to previous options if (previousCulture != null) { reader.Culture = previousCulture; } if (previousDateTimeZoneHandling != null) { reader.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault(); } if (previousDateParseHandling != null) { reader.DateParseHandling = previousDateParseHandling.GetValueOrDefault(); } if (previousFloatParseHandling != null) { reader.FloatParseHandling = previousFloatParseHandling.GetValueOrDefault(); } if (_maxDepthSet) { reader.MaxDepth = previousMaxDepth; } if (_dateFormatStringSet) { reader.DateFormatString = previousDateFormatString; } if (reader is JsonTextReader textReader) { textReader.NameTable = null; } } /// <summary> /// Serializes the specified <see cref="Object"/> and writes the JSON structure /// using the specified <see cref="TextWriter"/>. /// </summary> /// <param name="textWriter">The <see cref="TextWriter"/> used to write the JSON structure.</param> /// <param name="value">The <see cref="Object"/> to serialize.</param> public void Serialize(TextWriter textWriter, object value) { Serialize(new JsonTextWriter(textWriter), value); } /// <summary> /// Serializes the specified <see cref="Object"/> and writes the JSON structure /// using the specified <see cref="JsonWriter"/>. /// </summary> /// <param name="jsonWriter">The <see cref="JsonWriter"/> used to write the JSON structure.</param> /// <param name="value">The <see cref="Object"/> to serialize.</param> /// <param name="objectType"> /// The type of the value being serialized. /// This parameter is used when <see cref="JsonSerializer.TypeNameHandling"/> is <see cref="Json.TypeNameHandling.Auto"/> to write out the type name if the type of the value does not match. /// Specifying the type is optional. /// </param> public void Serialize(JsonWriter jsonWriter, object value, Type objectType) { SerializeInternal(jsonWriter, value, objectType); } /// <summary> /// Serializes the specified <see cref="Object"/> and writes the JSON structure /// using the specified <see cref="TextWriter"/>. /// </summary> /// <param name="textWriter">The <see cref="TextWriter"/> used to write the JSON structure.</param> /// <param name="value">The <see cref="Object"/> to serialize.</param> /// <param name="objectType"> /// The type of the value being serialized. /// This parameter is used when <see cref="TypeNameHandling"/> is Auto to write out the type name if the type of the value does not match. /// Specifying the type is optional. /// </param> public void Serialize(TextWriter textWriter, object value, Type objectType) { Serialize(new JsonTextWriter(textWriter), value, objectType); } /// <summary> /// Serializes the specified <see cref="Object"/> and writes the JSON structure /// using the specified <see cref="JsonWriter"/>. /// </summary> /// <param name="jsonWriter">The <see cref="JsonWriter"/> used to write the JSON structure.</param> /// <param name="value">The <see cref="Object"/> to serialize.</param> public void Serialize(JsonWriter jsonWriter, object value) { SerializeInternal(jsonWriter, value, null); } private TraceJsonReader CreateTraceJsonReader(JsonReader reader) { TraceJsonReader traceReader = new TraceJsonReader(reader); if (reader.TokenType != JsonToken.None) { traceReader.WriteCurrentToken(); } return traceReader; } internal virtual void SerializeInternal(JsonWriter jsonWriter, object value, Type objectType) { ValidationUtils.ArgumentNotNull(jsonWriter, nameof(jsonWriter)); // set serialization options onto writer Formatting? previousFormatting = null; if (_formatting != null && jsonWriter.Formatting != _formatting) { previousFormatting = jsonWriter.Formatting; jsonWriter.Formatting = _formatting.GetValueOrDefault(); } DateFormatHandling? previousDateFormatHandling = null; if (_dateFormatHandling != null && jsonWriter.DateFormatHandling != _dateFormatHandling) { previousDateFormatHandling = jsonWriter.DateFormatHandling; jsonWriter.DateFormatHandling = _dateFormatHandling.GetValueOrDefault(); } DateTimeZoneHandling? previousDateTimeZoneHandling = null; if (_dateTimeZoneHandling != null && jsonWriter.DateTimeZoneHandling != _dateTimeZoneHandling) { previousDateTimeZoneHandling = jsonWriter.DateTimeZoneHandling; jsonWriter.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } FloatFormatHandling? previousFloatFormatHandling = null; if (_floatFormatHandling != null && jsonWriter.FloatFormatHandling != _floatFormatHandling) { previousFloatFormatHandling = jsonWriter.FloatFormatHandling; jsonWriter.FloatFormatHandling = _floatFormatHandling.GetValueOrDefault(); } StringEscapeHandling? previousStringEscapeHandling = null; if (_stringEscapeHandling != null && jsonWriter.StringEscapeHandling != _stringEscapeHandling) { previousStringEscapeHandling = jsonWriter.StringEscapeHandling; jsonWriter.StringEscapeHandling = _stringEscapeHandling.GetValueOrDefault(); } CultureInfo previousCulture = null; if (_culture != null && !_culture.Equals(jsonWriter.Culture)) { previousCulture = jsonWriter.Culture; jsonWriter.Culture = _culture; } string previousDateFormatString = null; if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString) { previousDateFormatString = jsonWriter.DateFormatString; jsonWriter.DateFormatString = _dateFormatString; } TraceJsonWriter traceJsonWriter = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonWriter(jsonWriter) : null; JsonSerializerInternalWriter serializerWriter = new JsonSerializerInternalWriter(this); serializerWriter.Serialize(traceJsonWriter ?? jsonWriter, value, objectType); if (traceJsonWriter != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null); } // reset writer back to previous options if (previousFormatting != null) { jsonWriter.Formatting = previousFormatting.GetValueOrDefault(); } if (previousDateFormatHandling != null) { jsonWriter.DateFormatHandling = previousDateFormatHandling.GetValueOrDefault(); } if (previousDateTimeZoneHandling != null) { jsonWriter.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault(); } if (previousFloatFormatHandling != null) { jsonWriter.FloatFormatHandling = previousFloatFormatHandling.GetValueOrDefault(); } if (previousStringEscapeHandling != null) { jsonWriter.StringEscapeHandling = previousStringEscapeHandling.GetValueOrDefault(); } if (_dateFormatStringSet) { jsonWriter.DateFormatString = previousDateFormatString; } if (previousCulture != null) { jsonWriter.Culture = previousCulture; } } internal IReferenceResolver GetReferenceResolver() { if (_referenceResolver == null) { _referenceResolver = new DefaultReferenceResolver(); } return _referenceResolver; } internal JsonConverter GetMatchingConverter(Type type) { return GetMatchingConverter(_converters, type); } internal static JsonConverter GetMatchingConverter(IList<JsonConverter> converters, Type objectType) { #if DEBUG ValidationUtils.ArgumentNotNull(objectType, nameof(objectType)); #endif if (converters != null) { for (int i = 0; i < converters.Count; i++) { JsonConverter converter = converters[i]; if (converter.CanConvert(objectType)) { return converter; } } } return null; } internal void OnError(ErrorEventArgs e) { Error?.Invoke(this, e); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace IoTLab.WebApp.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Xunit.Performance; using System; using System.Linq; using System.Runtime.CompilerServices; using System.Reflection; using System.Collections.Generic; using Xunit; [assembly: OptimizeForBenchmarks] [assembly: MeasureInstructionsRetired] public static class ConstantArgsDouble { #if DEBUG public const int Iterations = 1; #else public const int Iterations = 100000; #endif // Doubles feeding math operations. // // Inlining in Bench0xp should enable constant folding // Inlining in Bench0xn will not enable constant folding static double Five = 5; static double Ten = 10; static double Id(double x) { return x; } static double F00(double x) { return x * x; } static bool Bench00p() { double t = 10; double f = F00(t); return (f == 100); } static bool Bench00n() { double t = Ten; double f = F00(t); return (f == 100); } static bool Bench00p1() { double t = Id(10); double f = F00(t); return (f == 100); } static bool Bench00n1() { double t = Id(Ten); double f = F00(t); return (f == 100); } static bool Bench00p2() { double t = Id(10); double f = F00(Id(t)); return (f == 100); } static bool Bench00n2() { double t = Id(Ten); double f = F00(Id(t)); return (f == 100); } static bool Bench00p3() { double t = 10; double f = F00(Id(Id(t))); return (f == 100); } static bool Bench00n3() { double t = Ten; double f = F00(Id(Id(t))); return (f == 100); } static bool Bench00p4() { double t = 5; double f = F00(2 * t); return (f == 100); } static bool Bench00n4() { double t = Five; double f = F00(2 * t); return (f == 100); } static double F01(double x) { return 1000 / x; } static bool Bench01p() { double t = 10; double f = F01(t); return (f == 100); } static bool Bench01n() { double t = Ten; double f = F01(t); return (f == 100); } static double F02(double x) { return 20 * (x / 2); } static bool Bench02p() { double t = 10; double f = F02(t); return (f == 100); } static bool Bench02n() { double t = Ten; double f = F02(t); return (f == 100); } static double F03(double x) { return 91 + 1009 % x; } static bool Bench03p() { double t = 10; double f = F03(t); return (f == 100); } static bool Bench03n() { double t = Ten; double f = F03(t); return (f == 100); } static double F04(double x) { return 50 * (x % 4); } static bool Bench04p() { double t = 10; double f = F04(t); return (f == 100); } static bool Bench04n() { double t = Ten; double f = F04(t); return (f == 100); } static double F06(double x) { return -x + 110; } static bool Bench06p() { double t = 10; double f = F06(t); return (f == 100); } static bool Bench06n() { double t = Ten; double f = F06(t); return (f == 100); } // Doubles feeding comparisons. // // Inlining in Bench1xp should enable branch optimization // Inlining in Bench1xn will not enable branch optimization static double F10(double x) { return x == 10 ? 100 : 0; } static bool Bench10p() { double t = 10; double f = F10(t); return (f == 100); } static bool Bench10n() { double t = Ten; double f = F10(t); return (f == 100); } static double F101(double x) { return x != 10 ? 0 : 100; } static bool Bench10p1() { double t = 10; double f = F101(t); return (f == 100); } static bool Bench10n1() { double t = Ten; double f = F101(t); return (f == 100); } static double F102(double x) { return x >= 10 ? 100 : 0; } static bool Bench10p2() { double t = 10; double f = F102(t); return (f == 100); } static bool Bench10n2() { double t = Ten; double f = F102(t); return (f == 100); } static double F103(double x) { return x <= 10 ? 100 : 0; } static bool Bench10p3() { double t = 10; double f = F103(t); return (f == 100); } static bool Bench10n3() { double t = Ten; double f = F102(t); return (f == 100); } static double F11(double x) { if (x == 10) { return 100; } else { return 0; } } static bool Bench11p() { double t = 10; double f = F11(t); return (f == 100); } static bool Bench11n() { double t = Ten; double f = F11(t); return (f == 100); } static double F111(double x) { if (x != 10) { return 0; } else { return 100; } } static bool Bench11p1() { double t = 10; double f = F111(t); return (f == 100); } static bool Bench11n1() { double t = Ten; double f = F111(t); return (f == 100); } static double F112(double x) { if (x > 10) { return 0; } else { return 100; } } static bool Bench11p2() { double t = 10; double f = F112(t); return (f == 100); } static bool Bench11n2() { double t = Ten; double f = F112(t); return (f == 100); } static double F113(double x) { if (x < 10) { return 0; } else { return 100; } } static bool Bench11p3() { double t = 10; double f = F113(t); return (f == 100); } static bool Bench11n3() { double t = Ten; double f = F113(t); return (f == 100); } // Ununsed (or effectively unused) parameters // // Simple callee analysis may overstate inline benefit static double F20(double x) { return 100; } static bool Bench20p() { double t = 10; double f = F20(t); return (f == 100); } static bool Bench20p1() { double t = Ten; double f = F20(t); return (f == 100); } static double F21(double x) { return -x + 100 + x; } static bool Bench21p() { double t = 10; double f = F21(t); return (f == 100); } static bool Bench21n() { double t = Ten; double f = F21(t); return (f == 100); } static double F211(double x) { return x - x + 100; } static bool Bench21p1() { double t = 10; double f = F211(t); return (f == 100); } static bool Bench21n1() { double t = Ten; double f = F211(t); return (f == 100); } static double F22(double x) { if (x > 0) { return 100; } return 100; } static bool Bench22p() { double t = 10; double f = F22(t); return (f == 100); } static bool Bench22p1() { double t = Ten; double f = F22(t); return (f == 100); } static double F23(double x) { if (x > 0) { return 90 + x; } return 100; } static bool Bench23p() { double t = 10; double f = F23(t); return (f == 100); } static bool Bench23n() { double t = Ten; double f = F23(t); return (f == 100); } // Multiple parameters static double F30(double x, double y) { return y * y; } static bool Bench30p() { double t = 10; double f = F30(t, t); return (f == 100); } static bool Bench30n() { double t = Ten; double f = F30(t, t); return (f == 100); } static bool Bench30p1() { double s = Ten; double t = 10; double f = F30(s, t); return (f == 100); } static bool Bench30n1() { double s = 10; double t = Ten; double f = F30(s, t); return (f == 100); } static bool Bench30p2() { double s = 10; double t = 10; double f = F30(s, t); return (f == 100); } static bool Bench30n2() { double s = Ten; double t = Ten; double f = F30(s, t); return (f == 100); } static bool Bench30p3() { double s = 10; double t = s; double f = F30(s, t); return (f == 100); } static bool Bench30n3() { double s = Ten; double t = s; double f = F30(s, t); return (f == 100); } static double F31(double x, double y, double z) { return z * z; } static bool Bench31p() { double t = 10; double f = F31(t, t, t); return (f == 100); } static bool Bench31n() { double t = Ten; double f = F31(t, t, t); return (f == 100); } static bool Bench31p1() { double r = Ten; double s = Ten; double t = 10; double f = F31(r, s, t); return (f == 100); } static bool Bench31n1() { double r = 10; double s = 10; double t = Ten; double f = F31(r, s, t); return (f == 100); } static bool Bench31p2() { double r = 10; double s = 10; double t = 10; double f = F31(r, s, t); return (f == 100); } static bool Bench31n2() { double r = Ten; double s = Ten; double t = Ten; double f = F31(r, s, t); return (f == 100); } static bool Bench31p3() { double r = 10; double s = r; double t = s; double f = F31(r, s, t); return (f == 100); } static bool Bench31n3() { double r = Ten; double s = r; double t = s; double f = F31(r, s, t); return (f == 100); } // Two args, both used static double F40(double x, double y) { return x * x + y * y - 100; } static bool Bench40p() { double t = 10; double f = F40(t, t); return (f == 100); } static bool Bench40n() { double t = Ten; double f = F40(t, t); return (f == 100); } static bool Bench40p1() { double s = Ten; double t = 10; double f = F40(s, t); return (f == 100); } static bool Bench40p2() { double s = 10; double t = Ten; double f = F40(s, t); return (f == 100); } static double F41(double x, double y) { return x * y; } static bool Bench41p() { double t = 10; double f = F41(t, t); return (f == 100); } static bool Bench41n() { double t = Ten; double f = F41(t, t); return (f == 100); } static bool Bench41p1() { double s = 10; double t = Ten; double f = F41(s, t); return (f == 100); } static bool Bench41p2() { double s = Ten; double t = 10; double f = F41(s, t); return (f == 100); } private static IEnumerable<object[]> MakeArgs(params string[] args) { return args.Select(arg => new object[] { arg }); } public static IEnumerable<object[]> TestFuncs = MakeArgs( "Bench00p", "Bench00n", "Bench00p1", "Bench00n1", "Bench00p2", "Bench00n2", "Bench00p3", "Bench00n3", "Bench00p4", "Bench00n4", "Bench01p", "Bench01n", "Bench02p", "Bench02n", "Bench03p", "Bench03n", "Bench04p", "Bench04n", "Bench06p", "Bench06n", "Bench10p", "Bench10n", "Bench10p1", "Bench10n1", "Bench10p2", "Bench10n2", "Bench10p3", "Bench10n3", "Bench11p", "Bench11n", "Bench11p1", "Bench11n1", "Bench11p2", "Bench11n2", "Bench11p3", "Bench11n3", "Bench20p", "Bench20p1", "Bench21p", "Bench21n", "Bench21p1", "Bench21n1", "Bench22p", "Bench22p1", "Bench23p", "Bench23n", "Bench30p", "Bench30n", "Bench30p1", "Bench30n1", "Bench30p2", "Bench30n2", "Bench30p3", "Bench30n3", "Bench31p", "Bench31n", "Bench31p1", "Bench31n1", "Bench31p2", "Bench31n2", "Bench31p3", "Bench31n3", "Bench40p", "Bench40n", "Bench40p1", "Bench40p2", "Bench41p", "Bench41n", "Bench41p1", "Bench41p2" ); static Func<bool> LookupFunc(object o) { TypeInfo t = typeof(ConstantArgsDouble).GetTypeInfo(); MethodInfo m = t.GetDeclaredMethod((string) o); return m.CreateDelegate(typeof(Func<bool>)) as Func<bool>; } [Benchmark] [MemberData(nameof(TestFuncs))] public static void Test(object funcName) { Func<bool> f = LookupFunc(funcName); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Iterations; i++) { f(); } } } } static bool TestBase(Func<bool> f) { bool result = true; for (int i = 0; i < Iterations; i++) { result &= f(); } return result; } public static int Main() { bool result = true; foreach(object[] o in TestFuncs) { string funcName = (string) o[0]; Func<bool> func = LookupFunc(funcName); bool thisResult = TestBase(func); if (!thisResult) { Console.WriteLine("{0} failed", funcName); } result &= thisResult; } return (result ? 100 : -1); } }
namespace Cronofy.Test.CronofyAccountClientTests { using System; using NUnit.Framework; internal sealed class UpsertEvent : Base { private const string CalendarId = "cal_123456_abcdef"; [Test] public void CanUpsertEvent() { const string eventId = "qTtZdczOccgaPncGJaCiLg"; const string summary = "Board meeting"; const string description = "Discuss plans for the next quarter"; const string startTimeString = "2014-08-05 15:30:00Z"; const string endTimeString = "2014-08-05 17:00:00Z"; const string locationDescription = "Board room"; const string transparency = Transparency.Opaque; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/calendars/" + CalendarId + "/events") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"event_id\":\"{0}\"," + "\"summary\":\"{1}\"," + "\"description\":\"{2}\"," + "\"start\":{{\"time\":\"{3}\",\"tzid\":\"Etc/UTC\"}}," + "\"end\":{{\"time\":\"{4}\",\"tzid\":\"Etc/UTC\"}}," + "\"location\":{{\"description\":\"{5}\"}}," + "\"transparency\":\"{6}\"" + "}}", eventId, summary, description, startTimeString, endTimeString, locationDescription, transparency) .ResponseCode(202)); var builder = new UpsertEventRequestBuilder() .EventId(eventId) .Summary(summary) .Description(description) .Start(new DateTime(2014, 8, 5, 15, 30, 0, DateTimeKind.Utc)) .End(new DateTime(2014, 8, 5, 17, 0, 0, DateTimeKind.Utc)) .Location(locationDescription) .Transparency(transparency); this.Client.UpsertEvent(CalendarId, builder); } [Test] public void CanUpsertExternalEvent() { const string eventUid = "external_event_id"; const string summary = "Board meeting"; const string description = "Discuss plans for the next quarter"; const string startTimeString = "2014-08-05 15:30:00Z"; const string endTimeString = "2014-08-05 17:00:00Z"; const string locationDescription = "Board room"; const string transparency = Transparency.Opaque; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/calendars/" + CalendarId + "/events") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"event_uid\":\"{0}\"," + "\"summary\":\"{1}\"," + "\"description\":\"{2}\"," + "\"start\":{{\"time\":\"{3}\",\"tzid\":\"Etc/UTC\"}}," + "\"end\":{{\"time\":\"{4}\",\"tzid\":\"Etc/UTC\"}}," + "\"location\":{{\"description\":\"{5}\"}}," + "\"transparency\":\"{6}\"" + "}}", eventUid, summary, description, startTimeString, endTimeString, locationDescription, transparency) .ResponseCode(202)); var builder = new UpsertEventRequestBuilder() .EventUid(eventUid) .Summary(summary) .Description(description) .Start(new DateTime(2014, 8, 5, 15, 30, 0, DateTimeKind.Utc)) .End(new DateTime(2014, 8, 5, 17, 0, 0, DateTimeKind.Utc)) .Location(locationDescription) .Transparency(transparency); this.Client.UpsertEvent(CalendarId, builder); } [Test] public void CanUpsertEventWithoutLocation() { const string eventId = "qTtZdczOccgaPncGJaCiLg"; const string summary = "Board meeting"; const string description = "Discuss plans for the next quarter"; const string startTimeString = "2014-08-05 15:30:00Z"; const string endTimeString = "2014-08-05 17:00:00Z"; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/calendars/" + CalendarId + "/events") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"event_id\":\"{0}\"," + "\"summary\":\"{1}\"," + "\"description\":\"{2}\"," + "\"start\":{{\"time\":\"{3}\",\"tzid\":\"Etc/UTC\"}}," + "\"end\":{{\"time\":\"{4}\",\"tzid\":\"Etc/UTC\"}}" + "}}", eventId, summary, description, startTimeString, endTimeString) .ResponseCode(202)); var builder = new UpsertEventRequestBuilder() .EventId(eventId) .Summary(summary) .Description(description) .Start(new DateTime(2014, 8, 5, 15, 30, 0, DateTimeKind.Utc)) .End(new DateTime(2014, 8, 5, 17, 0, 0, DateTimeKind.Utc)); this.Client.UpsertEvent(CalendarId, builder); } [Test] public void CanUpsertWithGeoLocation() { const string eventId = "qTtZdczOccgaPncGJaCiLg"; const string summary = "Board meeting"; const string description = "Discuss plans for the next quarter"; const string startTimeString = "2014-08-05 15:30:00Z"; const string endTimeString = "2014-08-05 17:00:00Z"; const string locationDescription = "Board room"; const string locationLatitude = "1.2345"; const string locationLongitude = "0.1234"; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/calendars/" + CalendarId + "/events") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"event_id\":\"{0}\"," + "\"summary\":\"{1}\"," + "\"description\":\"{2}\"," + "\"start\":{{\"time\":\"{3}\",\"tzid\":\"Etc/UTC\"}}," + "\"end\":{{\"time\":\"{4}\",\"tzid\":\"Etc/UTC\"}}," + "\"location\":{{\"description\":\"{5}\",\"lat\":\"{6}\",\"long\":\"{7}\"}}" + "}}", eventId, summary, description, startTimeString, endTimeString, locationDescription, locationLatitude, locationLongitude) .ResponseCode(202)); var builder = new UpsertEventRequestBuilder() .EventId(eventId) .Summary(summary) .Description(description) .Start(new DateTime(2014, 8, 5, 15, 30, 0, DateTimeKind.Utc)) .End(new DateTime(2014, 8, 5, 17, 0, 0, DateTimeKind.Utc)) .Location(locationDescription, locationLatitude, locationLongitude); this.Client.UpsertEvent(CalendarId, builder); } [Test] public void CanUpsertEventWithTimeZoneId() { const string eventId = "qTtZdczOccgaPncGJaCiLg"; const string summary = "Board meeting"; const string description = "Discuss plans for the next quarter"; const string startTimeString = "2014-08-05 15:30:00Z"; const string endTimeString = "2014-08-05 17:00:00Z"; const string timeZoneId = "Europe/London"; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/calendars/" + CalendarId + "/events") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"event_id\":\"{0}\"," + "\"summary\":\"{1}\"," + "\"description\":\"{2}\"," + "\"start\":{{\"time\":\"{3}\",\"tzid\":\"{5}\"}}," + "\"end\":{{\"time\":\"{4}\",\"tzid\":\"{5}\"}}," + "\"tzid\":\"{5}\"" + "}}", eventId, summary, description, startTimeString, endTimeString, timeZoneId) .ResponseCode(202)); var builder = new UpsertEventRequestBuilder() .EventId(eventId) .Summary(summary) .Description(description) .Start(new DateTime(2014, 8, 5, 15, 30, 0, DateTimeKind.Utc)) .End(new DateTime(2014, 8, 5, 17, 0, 0, DateTimeKind.Utc)) .TimeZoneId(timeZoneId); this.Client.UpsertEvent(CalendarId, builder); } [Test] public void CanUpsertEventWithSeparateTimeZoneIds() { const string eventId = "qTtZdczOccgaPncGJaCiLg"; const string summary = "Board meeting"; const string description = "Discuss plans for the next quarter"; const string startTimeString = "2014-08-05 15:30:00Z"; const string endTimeString = "2014-08-05 17:00:00Z"; const string startTimeZoneId = "Europe/London"; const string endTimeZoneId = "America/Chicago"; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/calendars/" + CalendarId + "/events") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"event_id\":\"{0}\"," + "\"summary\":\"{1}\"," + "\"description\":\"{2}\"," + "\"start\":{{\"time\":\"{3}\",\"tzid\":\"{4}\"}}," + "\"end\":{{\"time\":\"{5}\",\"tzid\":\"{6}\"}}" + "}}", eventId, summary, description, startTimeString, startTimeZoneId, endTimeString, endTimeZoneId) .ResponseCode(202)); var builder = new UpsertEventRequestBuilder() .EventId(eventId) .Summary(summary) .Description(description) .Start(new DateTime(2014, 8, 5, 15, 30, 0, DateTimeKind.Utc)) .StartTimeZoneId(startTimeZoneId) .End(new DateTime(2014, 8, 5, 17, 0, 0, DateTimeKind.Utc)) .EndTimeZoneId(endTimeZoneId); this.Client.UpsertEvent(CalendarId, builder); } [Test] public void CanUpsertAllDayEvent() { const string eventId = "qTtZdczOccgaPncGJaCiLg"; const string summary = "Board meeting"; const string description = "Discuss plans for the next quarter"; const string startTimeString = "2014-08-05"; const string endTimeString = "2014-08-06"; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/calendars/" + CalendarId + "/events") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"event_id\":\"{0}\"," + "\"summary\":\"{1}\"," + "\"description\":\"{2}\"," + "\"start\":{{\"time\":\"{3}\",\"tzid\":\"Etc/UTC\"}}," + "\"end\":{{\"time\":\"{4}\",\"tzid\":\"Etc/UTC\"}}" + "}}", eventId, summary, description, startTimeString, endTimeString) .ResponseCode(202)); var builder = new UpsertEventRequestBuilder() .EventId(eventId) .Summary(summary) .Description(description) .Start(new Date(2014, 8, 5)) .End(new Date(2014, 8, 6)); this.Client.UpsertEvent(CalendarId, builder); } [Test] public void CanUpsertAttendees() { const string eventId = "qTtZdczOccgaPncGJaCiLg"; const string summary = "Board meeting"; const string description = "Discuss plans for the next quarter"; const string startTimeString = "2014-08-05"; const string endTimeString = "2014-08-06"; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/calendars/" + CalendarId + "/events") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"event_id\":\"{0}\"," + "\"attendees\":{{\"invite\":[{{\"email\":\"[email protected]\",\"display_name\":\"Test attendee\"}}],\"remove\":[{{\"email\":\"[email protected]\",\"display_name\":\"Test removal\"}}]}}," + "\"summary\":\"{1}\"," + "\"description\":\"{2}\"," + "\"start\":{{\"time\":\"{3}\",\"tzid\":\"Etc/UTC\"}}," + "\"end\":{{\"time\":\"{4}\",\"tzid\":\"Etc/UTC\"}}" + "}}", eventId, summary, description, startTimeString, endTimeString) .ResponseCode(202)); var builder = new UpsertEventRequestBuilder() .EventId(eventId) .Summary(summary) .Description(description) .Start(new Date(2014, 8, 5)) .End(new Date(2014, 8, 6)) .AddAttendee("[email protected]", "Test attendee") .RemoveAttendee("[email protected]", "Test removal"); this.Client.UpsertEvent(CalendarId, builder); } [Test] public void CanUpsertReminders() { const string eventId = "qTtZdczOccgaPncGJaCiLg"; const string summary = "Board meeting"; const string description = "Discuss plans for the next quarter"; const string startTimeString = "2014-08-05"; const string endTimeString = "2014-08-06"; var reminders = new[] { 10, 0, 30 }; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/calendars/" + CalendarId + "/events") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"event_id\":\"{0}\"," + "\"summary\":\"{1}\"," + "\"description\":\"{2}\"," + "\"start\":{{\"time\":\"{3}\",\"tzid\":\"Etc/UTC\"}}," + "\"end\":{{\"time\":\"{4}\",\"tzid\":\"Etc/UTC\"}}," + "\"reminders\":[{{\"minutes\":10}},{{\"minutes\":0}},{{\"minutes\":30}}]" + "}}", eventId, summary, description, startTimeString, endTimeString) .ResponseCode(202)); var builder = new UpsertEventRequestBuilder() .EventId(eventId) .Summary(summary) .Description(description) .Start(new Date(2014, 8, 5)) .End(new Date(2014, 8, 6)) .Reminders(reminders); this.Client.UpsertEvent(CalendarId, builder); } [Test] public void CanUpsertExplicitNoReminders() { const string eventId = "qTtZdczOccgaPncGJaCiLg"; const string summary = "Board meeting"; const string description = "Discuss plans for the next quarter"; const string startTimeString = "2014-08-05"; const string endTimeString = "2014-08-06"; var reminders = new int[0]; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/calendars/" + CalendarId + "/events") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"event_id\":\"{0}\"," + "\"summary\":\"{1}\"," + "\"description\":\"{2}\"," + "\"start\":{{\"time\":\"{3}\",\"tzid\":\"Etc/UTC\"}}," + "\"end\":{{\"time\":\"{4}\",\"tzid\":\"Etc/UTC\"}}," + "\"reminders\":[]" + "}}", eventId, summary, description, startTimeString, endTimeString) .ResponseCode(202)); var builder = new UpsertEventRequestBuilder() .EventId(eventId) .Summary(summary) .Description(description) .Start(new Date(2014, 8, 5)) .End(new Date(2014, 8, 6)) .Reminders(reminders); this.Client.UpsertEvent(CalendarId, builder); } [Test] public void CanUpsertRemindersWithCreateOnly() { const string eventId = "qTtZdczOccgaPncGJaCiLg"; const string summary = "Board meeting"; const string description = "Discuss plans for the next quarter"; const string startTimeString = "2014-08-05"; const string endTimeString = "2014-08-06"; var reminders = new[] { 10, 0, 30 }; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/calendars/" + CalendarId + "/events") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"event_id\":\"{0}\"," + "\"reminders_create_only\":true," + "\"summary\":\"{1}\"," + "\"description\":\"{2}\"," + "\"start\":{{\"time\":\"{3}\",\"tzid\":\"Etc/UTC\"}}," + "\"end\":{{\"time\":\"{4}\",\"tzid\":\"Etc/UTC\"}}," + "\"reminders\":[{{\"minutes\":10}},{{\"minutes\":0}},{{\"minutes\":30}}]" + "}}", eventId, summary, description, startTimeString, endTimeString) .ResponseCode(202)); var builder = new UpsertEventRequestBuilder() .EventId(eventId) .Summary(summary) .Description(description) .Start(new Date(2014, 8, 5)) .End(new Date(2014, 8, 6)) .Reminders(reminders) .RemindersCreateOnly(true); this.Client.UpsertEvent(CalendarId, builder); } [Test] public void CanUpsertUrl() { const string eventId = "qTtZdczOccgaPncGJaCiLg"; const string summary = "Board meeting"; const string description = "Discuss plans for the next quarter"; const string startTimeString = "2014-08-05"; const string endTimeString = "2014-08-06"; const string url = "http://example.com"; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/calendars/" + CalendarId + "/events") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"event_id\":\"{0}\"," + "\"summary\":\"{1}\"," + "\"description\":\"{2}\"," + "\"start\":{{\"time\":\"{3}\",\"tzid\":\"Etc/UTC\"}}," + "\"end\":{{\"time\":\"{4}\",\"tzid\":\"Etc/UTC\"}}," + "\"url\":\"{5}\"" + "}}", eventId, summary, description, startTimeString, endTimeString, url) .ResponseCode(202)); var builder = new UpsertEventRequestBuilder() .EventId(eventId) .Summary(summary) .Description(description) .Start(new Date(2014, 8, 5)) .End(new Date(2014, 8, 6)) .Url(url); this.Client.UpsertEvent(CalendarId, builder); } [Test] public void CanUpsertExplicitNullUrl() { const string eventId = "qTtZdczOccgaPncGJaCiLg"; const string summary = "Board meeting"; const string description = "Discuss plans for the next quarter"; const string startTimeString = "2014-08-05"; const string endTimeString = "2014-08-06"; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/calendars/" + CalendarId + "/events") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"event_id\":\"{0}\"," + "\"summary\":\"{1}\"," + "\"description\":\"{2}\"," + "\"start\":{{\"time\":\"{3}\",\"tzid\":\"Etc/UTC\"}}," + "\"end\":{{\"time\":\"{4}\",\"tzid\":\"Etc/UTC\"}}," + "\"url\":null" + "}}", eventId, summary, description, startTimeString, endTimeString) .ResponseCode(202)); var builder = new UpsertEventRequestBuilder() .EventId(eventId) .Summary(summary) .Description(description) .Start(new Date(2014, 8, 5)) .End(new Date(2014, 8, 6)) .Url(null); this.Client.UpsertEvent(CalendarId, builder); } [Test] public void CantUpsertWithInvalidTransparency() { const string eventId = "qTtZdczOccgaPncGJaCiLg"; const string summary = "Board meeting"; const string startTimeString = "2014-08-05 15:30:00Z"; const string endTimeString = "2014-08-05 17:00:00Z"; const string transparency = Transparency.Unknown; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/calendars/" + CalendarId + "/events") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"event_id\":\"{0}\"," + "\"summary\":\"{1}\"," + "\"start\":{{\"time\":\"{2}\",\"tzid\":\"Etc/UTC\"}}," + "\"end\":{{\"time\":\"{3}\",\"tzid\":\"Etc/UTC\"}}," + "\"transparency\":\"{4}\"" + "}}", eventId, summary, startTimeString, endTimeString, transparency) .ResponseCode(202)); Assert.Throws<ArgumentException>(() => { var builder = new UpsertEventRequestBuilder() .EventId(eventId) .Summary(summary) .Start(new DateTime(2014, 8, 5, 15, 30, 0, DateTimeKind.Utc)) .End(new DateTime(2014, 8, 5, 17, 0, 0, DateTimeKind.Utc)) .Transparency(transparency); this.Client.UpsertEvent(CalendarId, builder); }); } [TestCase(true)] [TestCase(false)] public void CanUpsertEventWithPrivateFlag(bool eventPrivate) { const string eventId = "qTtZdczOccgaPncGJaCiLg"; const string summary = "Board meeting"; const string description = "Discuss plans for the next quarter"; const string startTimeString = "2014-08-05 15:30:00Z"; const string endTimeString = "2014-08-05 17:00:00Z"; const string locationDescription = "Board room"; const string transparency = Transparency.Opaque; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/calendars/" + CalendarId + "/events") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"event_id\":\"{0}\"," + "\"event_private\":{7}," + "\"summary\":\"{1}\"," + "\"description\":\"{2}\"," + "\"start\":{{\"time\":\"{3}\",\"tzid\":\"Etc/UTC\"}}," + "\"end\":{{\"time\":\"{4}\",\"tzid\":\"Etc/UTC\"}}," + "\"location\":{{\"description\":\"{5}\"}}," + "\"transparency\":\"{6}\"" + "}}", eventId, summary, description, startTimeString, endTimeString, locationDescription, transparency, eventPrivate.ToString().ToLower()) .ResponseCode(202)); var builder = new UpsertEventRequestBuilder() .EventId(eventId) .Summary(summary) .Description(description) .Start(new DateTime(2014, 8, 5, 15, 30, 0, DateTimeKind.Utc)) .End(new DateTime(2014, 8, 5, 17, 0, 0, DateTimeKind.Utc)) .Location(locationDescription) .Transparency(transparency) .EventPrivate(eventPrivate); this.Client.UpsertEvent(CalendarId, builder); } [Test] public void CanUpsertColor() { const string eventId = "qTtZdczOccgaPncGJaCiLg"; const string summary = "Board meeting"; const string description = "Discuss plans for the next quarter"; const string startTimeString = "2014-08-05"; const string endTimeString = "2014-08-06"; const string color = "#49BED8"; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/calendars/" + CalendarId + "/events") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"event_id\":\"{0}\"," + "\"summary\":\"{1}\"," + "\"description\":\"{2}\"," + "\"start\":{{\"time\":\"{3}\",\"tzid\":\"Etc/UTC\"}}," + "\"end\":{{\"time\":\"{4}\",\"tzid\":\"Etc/UTC\"}}," + "\"color\":\"{5}\"" + "}}", eventId, summary, description, startTimeString, endTimeString, color) .ResponseCode(202)); var builder = new UpsertEventRequestBuilder() .EventId(eventId) .Summary(summary) .Description(description) .Start(new Date(2014, 8, 5)) .End(new Date(2014, 8, 6)) .Color(color); this.Client.UpsertEvent(CalendarId, builder); } [Test] public void CanUpsertConferencing() { const string eventId = "qTtZdczOccgaPncGJaCiLg"; const string summary = "Board meeting"; const string description = "Discuss plans for the next quarter"; const string startTimeString = "2014-08-05"; const string endTimeString = "2014-08-06"; const string conferencingProfileId = "integrated"; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/calendars/" + CalendarId + "/events") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"event_id\":\"{0}\"," + "\"conferencing\":{{\"profile_id\":\"{5}\"}}," + "\"summary\":\"{1}\"," + "\"description\":\"{2}\"," + "\"start\":{{\"time\":\"{3}\",\"tzid\":\"Etc/UTC\"}}," + "\"end\":{{\"time\":\"{4}\",\"tzid\":\"Etc/UTC\"}}" + "}}", eventId, summary, description, startTimeString, endTimeString, conferencingProfileId) .ResponseCode(202)); var builder = new UpsertEventRequestBuilder() .EventId(eventId) .Summary(summary) .Description(description) .Start(new Date(2014, 8, 5)) .End(new Date(2014, 8, 6)) .Conferencing(conferencingProfileId); this.Client.UpsertEvent(CalendarId, builder); } [Test] public void CanUpsertExplicitConferencing() { const string eventId = "qTtZdczOccgaPncGJaCiLg"; const string summary = "Board meeting"; const string description = "Discuss plans for the next quarter"; const string startTimeString = "2014-08-05"; const string endTimeString = "2014-08-06"; const string conferencingProvider = "Meetings Co."; const string conferencingUrl = "https://meetings.co/join/abc"; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/calendars/" + CalendarId + "/events") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"event_id\":\"{0}\"," + "\"conferencing\":{{\"profile_id\":\"explicit\",\"provider_description\":\"{5}\",\"join_url\":\"{6}\"}}," + "\"summary\":\"{1}\"," + "\"description\":\"{2}\"," + "\"start\":{{\"time\":\"{3}\",\"tzid\":\"Etc/UTC\"}}," + "\"end\":{{\"time\":\"{4}\",\"tzid\":\"Etc/UTC\"}}" + "}}", eventId, summary, description, startTimeString, endTimeString, conferencingProvider, conferencingUrl) .ResponseCode(202)); var builder = new UpsertEventRequestBuilder() .EventId(eventId) .Summary(summary) .Description(description) .Start(new Date(2014, 8, 5)) .End(new Date(2014, 8, 6)) .ExplicitConferencing(conferencingProvider, conferencingUrl); this.Client.UpsertEvent(CalendarId, builder); } [Test] public void CanUpsertInteractionSubscription() { const string eventId = "qTtZdczOccgaPncGJaCiLg"; const string summary = "Board meeting"; const string description = "Discuss plans for the next quarter"; const string startTimeString = "2014-08-05"; const string endTimeString = "2014-08-06"; const string interactionType = "conferencing_assigned"; const string subscriptionUri = "https://consumer.com/webhook?state=foo"; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/calendars/" + CalendarId + "/events") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"event_id\":\"{0}\"," + "\"subscriptions\":[{{\"type\":\"webhook\",\"uri\":\"{5}\",\"interactions\":[{{\"type\":\"{6}\"}}]}}]," + "\"summary\":\"{1}\"," + "\"description\":\"{2}\"," + "\"start\":{{\"time\":\"{3}\",\"tzid\":\"Etc/UTC\"}}," + "\"end\":{{\"time\":\"{4}\",\"tzid\":\"Etc/UTC\"}}" + "}}", eventId, summary, description, startTimeString, endTimeString, subscriptionUri, interactionType) .ResponseCode(202)); var builder = new UpsertEventRequestBuilder() .EventId(eventId) .Summary(summary) .Description(description) .Start(new Date(2014, 8, 5)) .End(new Date(2014, 8, 6)) .InteractionSubscription(subscriptionUri, interactionType); this.Client.UpsertEvent(CalendarId, builder); } [Test] public void CanUpsertRemovingSubscriptions() { const string eventId = "qTtZdczOccgaPncGJaCiLg"; const string summary = "Board meeting"; const string description = "Discuss plans for the next quarter"; const string startTimeString = "2014-08-05"; const string endTimeString = "2014-08-06"; this.Http.Stub( HttpPost .Url("https://api.cronofy.com/v1/calendars/" + CalendarId + "/events") .RequestHeader("Authorization", "Bearer " + AccessToken) .RequestHeader("Content-Type", "application/json; charset=utf-8") .RequestBodyFormat( "{{\"event_id\":\"{0}\"," + "\"subscriptions\":[]," + "\"summary\":\"{1}\"," + "\"description\":\"{2}\"," + "\"start\":{{\"time\":\"{3}\",\"tzid\":\"Etc/UTC\"}}," + "\"end\":{{\"time\":\"{4}\",\"tzid\":\"Etc/UTC\"}}" + "}}", eventId, summary, description, startTimeString, endTimeString) .ResponseCode(202)); var builder = new UpsertEventRequestBuilder() .EventId(eventId) .Summary(summary) .Description(description) .Start(new Date(2014, 8, 5)) .End(new Date(2014, 8, 6)) .Subscriptions(new Requests.UpsertEventRequest.RequestSubscription[0]); this.Client.UpsertEvent(CalendarId, builder); } } }
// 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.Compute.V1.Snippets { using Google.Api.Gax; using System; using System.Linq; using System.Threading.Tasks; using lro = Google.LongRunning; /// <summary>Generated snippets.</summary> public sealed class GeneratedFirewallsClientSnippets { /// <summary>Snippet for Delete</summary> public void DeleteRequestObject() { // Snippet: Delete(DeleteFirewallRequest, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) DeleteFirewallRequest request = new DeleteFirewallRequest { RequestId = "", Project = "", Firewall = "", }; // Make the request lro::Operation<Operation, Operation> response = firewallsClient.Delete(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = firewallsClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteRequestObjectAsync() { // Snippet: DeleteAsync(DeleteFirewallRequest, CallSettings) // Additional: DeleteAsync(DeleteFirewallRequest, CancellationToken) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) DeleteFirewallRequest request = new DeleteFirewallRequest { RequestId = "", Project = "", Firewall = "", }; // Make the request lro::Operation<Operation, Operation> response = await firewallsClient.DeleteAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await firewallsClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Delete</summary> public void Delete() { // Snippet: Delete(string, string, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) string project = ""; string firewall = ""; // Make the request lro::Operation<Operation, Operation> response = firewallsClient.Delete(project, firewall); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = firewallsClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteAsync() { // Snippet: DeleteAsync(string, string, CallSettings) // Additional: DeleteAsync(string, string, CancellationToken) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string firewall = ""; // Make the request lro::Operation<Operation, Operation> response = await firewallsClient.DeleteAsync(project, firewall); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await firewallsClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Get</summary> public void GetRequestObject() { // Snippet: Get(GetFirewallRequest, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) GetFirewallRequest request = new GetFirewallRequest { Project = "", Firewall = "", }; // Make the request Firewall response = firewallsClient.Get(request); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetRequestObjectAsync() { // Snippet: GetAsync(GetFirewallRequest, CallSettings) // Additional: GetAsync(GetFirewallRequest, CancellationToken) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) GetFirewallRequest request = new GetFirewallRequest { Project = "", Firewall = "", }; // Make the request Firewall response = await firewallsClient.GetAsync(request); // End snippet } /// <summary>Snippet for Get</summary> public void Get() { // Snippet: Get(string, string, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) string project = ""; string firewall = ""; // Make the request Firewall response = firewallsClient.Get(project, firewall); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetAsync() { // Snippet: GetAsync(string, string, CallSettings) // Additional: GetAsync(string, string, CancellationToken) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string firewall = ""; // Make the request Firewall response = await firewallsClient.GetAsync(project, firewall); // End snippet } /// <summary>Snippet for Insert</summary> public void InsertRequestObject() { // Snippet: Insert(InsertFirewallRequest, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) InsertFirewallRequest request = new InsertFirewallRequest { RequestId = "", FirewallResource = new Firewall(), Project = "", }; // Make the request lro::Operation<Operation, Operation> response = firewallsClient.Insert(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = firewallsClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertRequestObjectAsync() { // Snippet: InsertAsync(InsertFirewallRequest, CallSettings) // Additional: InsertAsync(InsertFirewallRequest, CancellationToken) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) InsertFirewallRequest request = new InsertFirewallRequest { RequestId = "", FirewallResource = new Firewall(), Project = "", }; // Make the request lro::Operation<Operation, Operation> response = await firewallsClient.InsertAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await firewallsClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Insert</summary> public void Insert() { // Snippet: Insert(string, Firewall, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) string project = ""; Firewall firewallResource = new Firewall(); // Make the request lro::Operation<Operation, Operation> response = firewallsClient.Insert(project, firewallResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = firewallsClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertAsync() { // Snippet: InsertAsync(string, Firewall, CallSettings) // Additional: InsertAsync(string, Firewall, CancellationToken) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) string project = ""; Firewall firewallResource = new Firewall(); // Make the request lro::Operation<Operation, Operation> response = await firewallsClient.InsertAsync(project, firewallResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await firewallsClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for List</summary> public void ListRequestObject() { // Snippet: List(ListFirewallsRequest, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) ListFirewallsRequest request = new ListFirewallsRequest { OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<FirewallList, Firewall> response = firewallsClient.List(request); // Iterate over all response items, lazily performing RPCs as required foreach (Firewall 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 (FirewallList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Firewall 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<Firewall> 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 (Firewall 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 ListAsync</summary> public async Task ListRequestObjectAsync() { // Snippet: ListAsync(ListFirewallsRequest, CallSettings) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) ListFirewallsRequest request = new ListFirewallsRequest { OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<FirewallList, Firewall> response = firewallsClient.ListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Firewall 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((FirewallList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Firewall 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<Firewall> 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 (Firewall 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 List</summary> public void List() { // Snippet: List(string, string, int?, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) string project = ""; // Make the request PagedEnumerable<FirewallList, Firewall> response = firewallsClient.List(project); // Iterate over all response items, lazily performing RPCs as required foreach (Firewall 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 (FirewallList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Firewall 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<Firewall> 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 (Firewall 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 ListAsync</summary> public async Task ListAsync() { // Snippet: ListAsync(string, string, int?, CallSettings) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) string project = ""; // Make the request PagedAsyncEnumerable<FirewallList, Firewall> response = firewallsClient.ListAsync(project); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Firewall 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((FirewallList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Firewall 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<Firewall> 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 (Firewall 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 Patch</summary> public void PatchRequestObject() { // Snippet: Patch(PatchFirewallRequest, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) PatchFirewallRequest request = new PatchFirewallRequest { RequestId = "", FirewallResource = new Firewall(), Project = "", Firewall = "", }; // Make the request lro::Operation<Operation, Operation> response = firewallsClient.Patch(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = firewallsClient.PollOncePatch(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for PatchAsync</summary> public async Task PatchRequestObjectAsync() { // Snippet: PatchAsync(PatchFirewallRequest, CallSettings) // Additional: PatchAsync(PatchFirewallRequest, CancellationToken) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) PatchFirewallRequest request = new PatchFirewallRequest { RequestId = "", FirewallResource = new Firewall(), Project = "", Firewall = "", }; // Make the request lro::Operation<Operation, Operation> response = await firewallsClient.PatchAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await firewallsClient.PollOncePatchAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Patch</summary> public void Patch() { // Snippet: Patch(string, string, Firewall, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) string project = ""; string firewall = ""; Firewall firewallResource = new Firewall(); // Make the request lro::Operation<Operation, Operation> response = firewallsClient.Patch(project, firewall, firewallResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = firewallsClient.PollOncePatch(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for PatchAsync</summary> public async Task PatchAsync() { // Snippet: PatchAsync(string, string, Firewall, CallSettings) // Additional: PatchAsync(string, string, Firewall, CancellationToken) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string firewall = ""; Firewall firewallResource = new Firewall(); // Make the request lro::Operation<Operation, Operation> response = await firewallsClient.PatchAsync(project, firewall, firewallResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await firewallsClient.PollOncePatchAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Update</summary> public void UpdateRequestObject() { // Snippet: Update(UpdateFirewallRequest, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) UpdateFirewallRequest request = new UpdateFirewallRequest { RequestId = "", FirewallResource = new Firewall(), Project = "", Firewall = "", }; // Make the request lro::Operation<Operation, Operation> response = firewallsClient.Update(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = firewallsClient.PollOnceUpdate(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateAsync</summary> public async Task UpdateRequestObjectAsync() { // Snippet: UpdateAsync(UpdateFirewallRequest, CallSettings) // Additional: UpdateAsync(UpdateFirewallRequest, CancellationToken) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) UpdateFirewallRequest request = new UpdateFirewallRequest { RequestId = "", FirewallResource = new Firewall(), Project = "", Firewall = "", }; // Make the request lro::Operation<Operation, Operation> response = await firewallsClient.UpdateAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await firewallsClient.PollOnceUpdateAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Update</summary> public void Update() { // Snippet: Update(string, string, Firewall, CallSettings) // Create client FirewallsClient firewallsClient = FirewallsClient.Create(); // Initialize request argument(s) string project = ""; string firewall = ""; Firewall firewallResource = new Firewall(); // Make the request lro::Operation<Operation, Operation> response = firewallsClient.Update(project, firewall, firewallResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = firewallsClient.PollOnceUpdate(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateAsync</summary> public async Task UpdateAsync() { // Snippet: UpdateAsync(string, string, Firewall, CallSettings) // Additional: UpdateAsync(string, string, Firewall, CancellationToken) // Create client FirewallsClient firewallsClient = await FirewallsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string firewall = ""; Firewall firewallResource = new Firewall(); // Make the request lro::Operation<Operation, Operation> response = await firewallsClient.UpdateAsync(project, firewall, firewallResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await firewallsClient.PollOnceUpdateAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } } }
// Copyright 2010 Chris Patterson // // 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 Stact { using System; using System.Collections.Generic; using System.Threading; using Executors; using Internal; using Magnum; using Magnum.Extensions; public class ThreadFiber : Fiber { readonly OperationExecutor _executor; readonly object _lock = new object(); readonly Thread _thread; bool _isActive; IList<Action> _operations = new List<Action>(); bool _shuttingDown; bool _stopping; public ThreadFiber() : this(new BasicOperationExecutor()) { } public ThreadFiber(OperationExecutor executor) { _executor = executor; _thread = CreateThread(); _thread.Start(); } public void Add(Action operation) { if (_shuttingDown) return; // seems to be causing more problems that it solves // throw new FiberException("The fiber is no longer accepting actions"); lock (_lock) { _operations.Add(operation); Monitor.PulseAll(_lock); } } public void Shutdown(TimeSpan timeout) { if (timeout == TimeSpan.Zero) { lock (_lock) { _shuttingDown = true; Monitor.PulseAll(_lock); } return; } DateTime waitUntil = SystemUtil.Now + timeout; lock (_lock) { _shuttingDown = true; Monitor.PulseAll(_lock); while (_operations.Count > 0 || _isActive) { timeout = waitUntil - SystemUtil.Now; if (timeout < TimeSpan.Zero) throw new FiberException("Timeout expired waiting for all pending actions to complete during shutdown"); Monitor.Wait(_lock, timeout); } } _thread.Join(timeout); } public void Stop() { lock (_lock) { _shuttingDown = true; _stopping = true; _executor.Stop(); Monitor.PulseAll(_lock); } } public override string ToString() { return "{0} (Count: {1}, Id: {2})".FormatWith(typeof(ThreadFiber).Name, _operations.Count, _thread.ManagedThreadId); } Thread CreateThread() { var thread = new Thread(Run); thread.Name = typeof(ThreadFiber).Name + "-" + thread.ManagedThreadId; thread.IsBackground = false; thread.Priority = ThreadPriority.Normal; return thread; } void Run() { _isActive = true; try { while (Execute()) { } } catch { } _isActive = false; lock (_lock) { Monitor.PulseAll(_lock); } } bool Execute() { if (!WaitForActions()) return false; IList<Action> operations = RemoveAll(); if (operations == null) return false; _executor.Execute(operations, remaining => { lock (_lock) { int i = 0; foreach (Action action in remaining) _operations.Insert(i++, action); } }); lock (_lock) { if (_operations.Count == 0) Monitor.PulseAll(_lock); } return true; } bool WaitForActions() { lock (_lock) { while (_operations.Count == 0 && !_stopping && !_shuttingDown) Monitor.Wait(_lock); if (_stopping) return false; if (_shuttingDown) return _operations.Count > 0; } return true; } IList<Action> RemoveAll() { lock (_lock) { IList<Action> operations = _operations; _operations = new List<Action>(); return operations; } } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace MyFirstCloudHostedAppWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
using System; using System.Runtime.CompilerServices; #if LOCALTEST namespace System_.Text { #else namespace System.Text { #endif public sealed class StringBuilder { private const int defaultMaxCapacity = int.MaxValue; private const int defaultInitialCapacity = 16; private int length; private int capacity; private char[] data; #region Constructors public StringBuilder() : this(defaultInitialCapacity, defaultMaxCapacity) { } public StringBuilder(int initialCapacity) : this(initialCapacity, defaultMaxCapacity) { } public StringBuilder(int initialCapacity, int maxCapacity) { this.capacity = Math.Max(initialCapacity, 2); this.length = 0; this.data = new char[this.capacity]; } public StringBuilder(string value) : this((value != null) ? value.Length : defaultInitialCapacity, defaultMaxCapacity) { if (value != null) { this.Append(value); } } public StringBuilder(string value, int initialCapacity) : this(initialCapacity, defaultMaxCapacity) { if (value != null) { this.Append(value); } } public StringBuilder(string value, int startIndex, int length, int initialCapacity) : this(initialCapacity, defaultMaxCapacity) { if (value == null) { value = string.Empty; } if (startIndex < 0 || length < 0 || startIndex + length > value.Length) { throw new ArgumentOutOfRangeException(); } this.Append(value, startIndex, length); } #endregion public override string ToString() { return new string(this.data, 0, this.length); } public string ToString(int startIndex, int length) { if (startIndex < 0 || length < 0 || startIndex + length > this.length) { Console.WriteLine("Invalid arguments to SB.ToString()"); throw new ArgumentOutOfRangeException(); } return new string(this.data, startIndex, length); } private void EnsureSpace(int space) { if (this.length + space > this.capacity) { do { this.capacity <<= 1; } while (this.capacity < this.length + space); char[] newData = new char[capacity]; Array.Copy(this.data, 0, newData, 0, this.length); this.data = newData; } } public int Length { get { return this.length; } set { if (value < 0) { throw new ArgumentOutOfRangeException(); } if (value > this.length) { this.EnsureSpace(this.length - value); for (int i = this.length; i < value; i++) { this.data[i] = '\x0000'; } } this.length = value; } } public int Capacity { get { return this.capacity; } } [IndexerName("Chars")] public char this[int index] { get { if (index < 0 || index >= this.length) { throw new IndexOutOfRangeException(); } return this.data[index]; } set { if (index < 0 || index >= this.length) { throw new IndexOutOfRangeException(); } this.data[index] = value; } } public void CopyTo(int srcIndex, char[] dst, int dstIndex, int count) { if (dst == null) { throw new ArgumentNullException("destination"); } if (srcIndex < 0 || count < 0 || dstIndex < 0 || srcIndex + count > this.length || dstIndex + count > dst.Length) { throw new ArgumentOutOfRangeException(); } Array.Copy(this.data, srcIndex, dst, dstIndex, count); } public void EnsureCapacity(int capacity) { if (this.capacity < capacity) { // This is not quite right, as it will often over-allocate memory this.EnsureSpace(capacity - this.capacity); } } public StringBuilder Remove(int startIndex, int length) { if (startIndex < 0 || length < 0 || startIndex + length > this.length) { throw new ArgumentOutOfRangeException(); } Array.Copy(this.data, startIndex + length, this.data, startIndex, this.length - length - startIndex); this.length -= length; return this; } #region Append Methods public StringBuilder Append(string value) { int len = value.Length; this.EnsureSpace(len); for (int i = 0; i < len; i++) { this.data[this.length++] = value[i]; } return this; } public StringBuilder Append(string value, int startIndex, int count) { if (value == null) { return this; } if (startIndex < 0 || count < 0 || value.Length < startIndex + count) { throw new ArgumentOutOfRangeException(); } this.EnsureSpace(count); for (int i = 0; i < count; i++) { this.data[this.length++] = value[startIndex + i]; } return this; } public StringBuilder Append(char value) { EnsureSpace(1); data[length++] = value; return this; } public StringBuilder Append(char value, int repeatCount) { if (repeatCount < 0) { throw new ArgumentOutOfRangeException(); } EnsureSpace(repeatCount); for (int i = 0; i < repeatCount; i++) { this.data[this.length++] = value; } return this; } public StringBuilder Append(char[] value) { if (value == null) { return this; } int addLen = value.Length; this.EnsureSpace(addLen); Array.Copy(value, 0, this.data, this.length, addLen); this.length += addLen; return this; } public StringBuilder Append(char[] value, int startIndex, int charCount) { if (value == null) { return this; } if (charCount < 0 || startIndex < 0 || value.Length < (startIndex + charCount)) { throw new ArgumentOutOfRangeException(); } this.EnsureSpace(charCount); Array.Copy(value, startIndex, this.data, this.length, charCount); this.length += charCount; return this; } public StringBuilder Append(object value) { if (value == null) { return this; } return Append(value.ToString()); } public StringBuilder Append(bool value) { return Append(value.ToString()); } public StringBuilder Append(byte value) { return Append(value.ToString()); } public StringBuilder Append(decimal value) { return Append(value.ToString()); } public StringBuilder Append(double value) { return Append(value.ToString()); } public StringBuilder Append(short value) { return Append(value.ToString()); } public StringBuilder Append(int value) { return Append(value.ToString()); } public StringBuilder Append(long value) { return Append(value.ToString()); } public StringBuilder Append(sbyte value) { return Append(value.ToString()); } public StringBuilder Append(float value) { return Append(value.ToString()); } public StringBuilder Append(ushort value) { return Append(value.ToString()); } public StringBuilder Append(uint value) { return Append(value.ToString()); } public StringBuilder Append(ulong value) { return Append(value.ToString()); } #endregion #region AppendFormat Methods public StringBuilder AppendFormat(string format, object obj0) { StringHelper.FormatHelper(this, null, format, obj0); return this; } public StringBuilder AppendFormat(string format, object obj0, object obj1) { StringHelper.FormatHelper(this, null, format, obj0, obj1); return this; } public StringBuilder AppendFormat(string format, object obj0, object obj1, object obj2) { StringHelper.FormatHelper(this, null, format, obj0, obj1, obj2); return this; } public StringBuilder AppendFormat(string format, params object[] objs) { StringHelper.FormatHelper(this, null, format, objs); return this; } public StringBuilder AppendFormat(IFormatProvider provider, string format, params object[] objs) { StringHelper.FormatHelper(this, provider, format, objs); return this; } #endregion #region AppendLine Methods public StringBuilder AppendLine() { return this.Append(Environment.NewLine); } public StringBuilder AppendLine(string value) { return this.Append(value).Append(Environment.NewLine); } #endregion #region Insert Methods public StringBuilder Insert(int index, string value) { if (index < 0 || index > this.length) { throw new ArgumentOutOfRangeException(); } if (string.IsNullOrEmpty(value)) { return this; } int len = value.Length; EnsureSpace(len); Array.Copy(this.data, index, this.data, index + len, this.length - index); for (int i = 0; i < len; i++) { this.data[index + i] = value[i]; } this.length += len; return this; } public StringBuilder Insert(int index, bool value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, byte value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, char value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, char[] value) { return this.Insert(index, new string(value)); } public StringBuilder Insert(int index, decimal value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, double value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, short value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, int value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, long value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, object value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, sbyte value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, float value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, ushort value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, uint value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, ulong value) { return this.Insert(index, value.ToString()); } public StringBuilder Insert(int index, string value, int count) { if (count < 0) { throw new ArgumentOutOfRangeException(); } if (count == 0 || string.IsNullOrEmpty(value)) { return this; } StringBuilder toInsert = new StringBuilder(value.Length * count); for (; count > 0; count--) { toInsert.Append(value); } return this.Insert(index, toInsert.ToString()); } public StringBuilder Insert(int index, char[] value, int startIndex, int charCount) { if (value == null && (startIndex != 0 || charCount != 0)) { throw new ArgumentNullException("value"); } if (startIndex < 0 || charCount < 0 || startIndex + charCount > value.Length) { throw new ArgumentOutOfRangeException(); } return this.Insert(index, new string(value, startIndex, charCount)); } #endregion #region Replace Methods public StringBuilder Replace(char oldChar, char newChar) { return this.Replace(oldChar, newChar, 0, this.length); } public StringBuilder Replace(string oldValue, string newValue) { return this.Replace(oldValue, newValue, 0, this.length); } public StringBuilder Replace(char oldChar, char newChar, int startIndex, int count) { if (startIndex < 0 || count < 0 || startIndex + count > this.length) { throw new ArgumentOutOfRangeException(); } for (int i = 0; i < count; i++) { if (this.data[startIndex + i] == oldChar) { this.data[startIndex + i] = newChar; } } return this; } public StringBuilder Replace(string oldValue, string newValue, int startIndex, int count) { string subStr = this.ToString(startIndex, count); subStr = subStr.Replace(oldValue, newValue); this.Remove(startIndex, count); this.Insert(startIndex, subStr); return this; } #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.Collections.Generic; using System.Diagnostics; using System.Linq; using System.IO; using System.Net.Test.Common; using System.Security.Authentication.ExtendedProtection; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; using System.Net.Sockets; namespace System.Net.Http.Functional.Tests { // Note: Disposing the HttpClient object automatically disposes the handler within. So, it is not necessary // to separately Dispose (or have a 'using' statement) for the handler. public class HttpClientHandlerTest { readonly ITestOutputHelper _output; private const string ExpectedContent = "Test contest"; private const string Username = "testuser"; private const string Password = "password"; private readonly NetworkCredential _credential = new NetworkCredential(Username, Password); public readonly static object[][] EchoServers = HttpTestServers.EchoServers; public readonly static object[][] VerifyUploadServers = HttpTestServers.VerifyUploadServers; public readonly static object[][] CompressedServers = HttpTestServers.CompressedServers; public readonly static object[][] HeaderValueAndUris = { new object[] { "X-CustomHeader", "x-value", HttpTestServers.RemoteEchoServer }, new object[] { "X-Cust-Header-NoValue", "" , HttpTestServers.RemoteEchoServer }, new object[] { "X-CustomHeader", "x-value", HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:HttpTestServers.RemoteEchoServer, hops:1) }, new object[] { "X-Cust-Header-NoValue", "" , HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:HttpTestServers.RemoteEchoServer, hops:1) }, }; public readonly static object[][] Http2Servers = HttpTestServers.Http2Servers; public readonly static object[][] RedirectStatusCodes = { new object[] { 300 }, new object[] { 301 }, new object[] { 302 }, new object[] { 303 }, new object[] { 307 } }; // Standard HTTP methods defined in RFC7231: http://tools.ietf.org/html/rfc7231#section-4.3 // "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE" public readonly static IEnumerable<object[]> HttpMethods = GetMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE", "CUSTOM1"); public readonly static IEnumerable<object[]> HttpMethodsThatAllowContent = GetMethods("GET", "POST", "PUT", "DELETE", "CUSTOM1"); private static IEnumerable<object[]> GetMethods(params string[] methods) { foreach (string method in methods) { foreach (bool secure in new[] { true, false }) { yield return new object[] { method, secure }; } } } public HttpClientHandlerTest(ITestOutputHelper output) { _output = output; } [Fact] public void Ctor_ExpectedDefaultPropertyValues() { using (var handler = new HttpClientHandler()) { // Same as .NET Framework (Desktop). Assert.True(handler.AllowAutoRedirect); Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOptions); CookieContainer cookies = handler.CookieContainer; Assert.NotNull(cookies); Assert.Equal(0, cookies.Count); Assert.Null(handler.Credentials); Assert.Equal(50, handler.MaxAutomaticRedirections); Assert.False(handler.PreAuthenticate); Assert.Equal(null, handler.Proxy); Assert.True(handler.SupportsAutomaticDecompression); Assert.True(handler.SupportsProxy); Assert.True(handler.SupportsRedirectConfiguration); Assert.True(handler.UseCookies); Assert.False(handler.UseDefaultCredentials); Assert.True(handler.UseProxy); // Changes from .NET Framework (Desktop). Assert.Equal(DecompressionMethods.GZip | DecompressionMethods.Deflate, handler.AutomaticDecompression); Assert.Equal(0, handler.MaxRequestContentBufferSize); } } [Fact] public void MaxRequestContentBufferSize_Get_ReturnsZero() { using (var handler = new HttpClientHandler()) { Assert.Equal(0, handler.MaxRequestContentBufferSize); } } [Fact] public void MaxRequestContentBufferSize_Set_ThrowsPlatformNotSupportedException() { using (var handler = new HttpClientHandler()) { Assert.Throws<PlatformNotSupportedException>(() => handler.MaxRequestContentBufferSize = 1024); } } [Theory] [InlineData(false)] [InlineData(true)] public async Task UseDefaultCredentials_SetToFalseAndServerNeedsAuth_StatusCodeUnauthorized(bool useProxy) { var handler = new HttpClientHandler(); handler.UseProxy = useProxy; handler.UseDefaultCredentials = false; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.NegotiateAuthUriForDefaultCreds(secure:false); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } } [Theory, MemberData(nameof(EchoServers))] public async Task SendAsync_SimpleGet_Success(Uri remoteServer) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(remoteServer)) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } [Fact] public async Task SendAsync_MultipleRequestsReusingSameClient_Success() { using (var client = new HttpClient()) { HttpResponseMessage response; for (int i = 0; i < 3; i++) { response = await client.GetAsync(HttpTestServers.RemoteEchoServer); Assert.Equal(HttpStatusCode.OK, response.StatusCode); response.Dispose(); } } } [Fact] public async Task GetAsync_ResponseContentAfterClientAndHandlerDispose_Success() { HttpResponseMessage response = null; using (var handler = new HttpClientHandler()) using (var client = new HttpClient(handler)) { response = await client.GetAsync(HttpTestServers.SecureRemoteEchoServer); } Assert.NotNull(response); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } [Fact] public async Task SendAsync_Cancel_CancellationTokenPropagates() { var cts = new CancellationTokenSource(); cts.Cancel(); using (var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Post, HttpTestServers.RemoteEchoServer); TaskCanceledException ex = await Assert.ThrowsAsync<TaskCanceledException>(() => client.SendAsync(request, cts.Token)); Assert.True(cts.Token.IsCancellationRequested, "cts token IsCancellationRequested"); Assert.True(ex.CancellationToken.IsCancellationRequested, "exception token IsCancellationRequested"); } } [Theory, MemberData(nameof(CompressedServers))] public async Task GetAsync_DefaultAutomaticDecompression_ContentDecompressed(Uri server) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(server)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } [Theory, MemberData(nameof(CompressedServers))] public async Task GetAsync_DefaultAutomaticDecompression_HeadersRemoved(Uri server) { using (var client = new HttpClient()) using (HttpResponseMessage response = await client.GetAsync(server, HttpCompletionOption.ResponseHeadersRead)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.False(response.Content.Headers.Contains("Content-Encoding"), "Content-Encoding unexpectedly found"); Assert.False(response.Content.Headers.Contains("Content-Length"), "Content-Length unexpectedly found"); } } [Fact] public async Task GetAsync_ServerNeedsAuthAndSetCredential_StatusCodeOK() { var handler = new HttpClientHandler(); handler.Credentials = _credential; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Fact] public async Task GetAsync_ServerNeedsAuthAndNoCredential_StatusCodeUnauthorized() { using (var client = new HttpClient()) { Uri uri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } } [Theory, MemberData(nameof(RedirectStatusCodes))] public async Task GetAsync_AllowAutoRedirectFalse_RedirectFromHttpToHttp_StatusCodeRedirect(int statusCode) { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = false; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:statusCode, destinationUri:HttpTestServers.RemoteEchoServer, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(statusCode, (int)response.StatusCode); } } } [Theory, MemberData(nameof(RedirectStatusCodes))] public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttp_StatusCodeOK(int statusCode) { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:statusCode, destinationUri:HttpTestServers.RemoteEchoServer, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttps_StatusCodeOK() { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:HttpTestServers.SecureRemoteEchoServer, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpsToHttp_StatusCodeRedirect() { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:true, statusCode:302, destinationUri:HttpTestServers.RemoteEchoServer, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); } } } [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectToUriWithParams_RequestMsgUriSet() { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; Uri targetUri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password); using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:targetUri, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(targetUri, response.RequestMessage.RequestUri); } } } [Theory] [InlineData(6)] public async Task GetAsync_MaxAutomaticRedirectionsNServerHopsNPlus1_Throw(int hops) { var handler = new HttpClientHandler(); handler.MaxAutomaticRedirections = hops; using (var client = new HttpClient(handler)) { await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:HttpTestServers.RemoteEchoServer, hops:(hops + 1)))); } } [Fact] public async Task GetAsync_CredentialIsNetworkCredentialUriRedirect_StatusCodeUnauthorized() { var handler = new HttpClientHandler(); handler.Credentials = _credential; using (var client = new HttpClient(handler)) { Uri redirectUri = HttpTestServers.RedirectUriForCreds( secure:false, statusCode:302, userName:Username, password:Password); using (HttpResponseMessage unAuthResponse = await client.GetAsync(redirectUri)) { Assert.Equal(HttpStatusCode.Unauthorized, unAuthResponse.StatusCode); } } } [Theory, MemberData(nameof(RedirectStatusCodes))] public async Task GetAsync_CredentialIsCredentialCacheUriRedirect_StatusCodeOK(int statusCode) { Uri uri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password); Uri redirectUri = HttpTestServers.RedirectUriForCreds( secure:false, statusCode:statusCode, userName:Username, password:Password); _output.WriteLine(uri.AbsoluteUri); _output.WriteLine(redirectUri.AbsoluteUri); var credentialCache = new CredentialCache(); credentialCache.Add(uri, "Basic", _credential); var handler = new HttpClientHandler(); handler.Credentials = credentialCache; using (var client = new HttpClient(handler)) { using (HttpResponseMessage response = await client.GetAsync(redirectUri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Fact] public async Task GetAsync_DefaultCoookieContainer_NoCookieSent() { using (HttpClient client = new HttpClient()) { using (HttpResponseMessage httpResponse = await client.GetAsync(HttpTestServers.RemoteEchoServer)) { string responseText = await httpResponse.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.False(TestHelper.JsonMessageContainsKey(responseText, "Cookie")); } } } [Theory] [InlineData("cookieName1", "cookieValue1")] public async Task GetAsync_SetCookieContainer_CookieSent(string cookieName, string cookieValue) { var handler = new HttpClientHandler(); var cookieContainer = new CookieContainer(); cookieContainer.Add(HttpTestServers.RemoteEchoServer, new Cookie(cookieName, cookieValue)); handler.CookieContainer = cookieContainer; using (var client = new HttpClient(handler)) { using (HttpResponseMessage httpResponse = await client.GetAsync(HttpTestServers.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); string responseText = await httpResponse.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, cookieName, cookieValue)); } } } [Theory] [InlineData("cookieName1", "cookieValue1")] public async Task GetAsync_RedirectResponseHasCookie_CookieSentToFinalUri(string cookieName, string cookieValue) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:HttpTestServers.RemoteEchoServer, hops:1); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add( "X-SetCookie", string.Format("{0}={1};Path=/", cookieName, cookieValue)); using (HttpResponseMessage httpResponse = await client.GetAsync(uri)) { string responseText = await httpResponse.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, cookieName, cookieValue)); } } } [Theory, MemberData(nameof(HeaderValueAndUris))] public async Task GetAsync_RequestHeadersAddCustomHeaders_HeaderAndValueSent(string name, string value, Uri uri) { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add(name, value); using (HttpResponseMessage httpResponse = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); string responseText = await httpResponse.Content.ReadAsStringAsync(); Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, name, value)); } } } private static KeyValuePair<string, string> GenerateCookie(string name, char repeat, int overallHeaderValueLength) { string emptyHeaderValue = $"{name}=; Path=/"; Debug.Assert(overallHeaderValueLength > emptyHeaderValue.Length); int valueCount = overallHeaderValueLength - emptyHeaderValue.Length; string value = new string(repeat, valueCount); return new KeyValuePair<string, string>(name, value); } public static object[][] CookieNameValues = { // WinHttpHandler calls WinHttpQueryHeaders to iterate through multiple Set-Cookie header values, // using an initial buffer size of 128 chars. If the buffer is not large enough, WinHttpQueryHeaders // returns an insufficient buffer error, allowing WinHttpHandler to try again with a larger buffer. // Sometimes when WinHttpQueryHeaders fails due to insufficient buffer, it still advances the // iteration index, which would cause header values to be missed if not handled correctly. // // In particular, WinHttpQueryHeader behaves as follows for the following header value lengths: // * 0-127 chars: succeeds, index advances from 0 to 1. // * 128-255 chars: fails due to insufficient buffer, index advances from 0 to 1. // * 256+ chars: fails due to insufficient buffer, index stays at 0. // // The below overall header value lengths were chosen to exercise reading header values at these // edges, to ensure WinHttpHandler does not miss multiple Set-Cookie headers. new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 126) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 127) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 128) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 129) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 254) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 255) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 256) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 257) }, new object[] { new KeyValuePair<string, string>( ".AspNetCore.Antiforgery.Xam7_OeLcN4", "CfDJ8NGNxAt7CbdClq3UJ8_6w_4661wRQZT1aDtUOIUKshbcV4P0NdS8klCL5qGSN-PNBBV7w23G6MYpQ81t0PMmzIN4O04fqhZ0u1YPv66mixtkX3iTi291DgwT3o5kozfQhe08-RAExEmXpoCbueP_QYM") } }; [Theory] [MemberData(nameof(CookieNameValues))] public async Task GetAsync_ResponseWithSetCookieHeaders_AllCookiesRead(KeyValuePair<string, string> cookie1) { var cookie2 = new KeyValuePair<string, string>(".AspNetCore.Session", "RAExEmXpoCbueP_QYM"); var cookie3 = new KeyValuePair<string, string>("name", "value"); string url = string.Format( "http://httpbin.org/cookies/set?{0}={1}&{2}={3}&{4}={5}", cookie1.Key, cookie1.Value, cookie2.Key, cookie2.Value, cookie3.Key, cookie3.Value); var handler = new HttpClientHandler() { AllowAutoRedirect = false }; using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(url)) { Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); CookieCollection cookies = handler.CookieContainer.GetCookies(new Uri(url)); Assert.Equal(3, handler.CookieContainer.Count); Assert.Equal(cookie1.Value, cookies[cookie1.Key].Value); Assert.Equal(cookie2.Value, cookies[cookie2.Key].Value); Assert.Equal(cookie3.Value, cookies[cookie3.Key].Value); } } [Fact] public async Task GetAsync_ResponseHeadersRead_ReadFromEachIterativelyDoesntDeadlock() { using (var client = new HttpClient()) { const int NumGets = 5; Task<HttpResponseMessage>[] responseTasks = (from _ in Enumerable.Range(0, NumGets) select client.GetAsync(HttpTestServers.RemoteEchoServer, HttpCompletionOption.ResponseHeadersRead)).ToArray(); for (int i = responseTasks.Length - 1; i >= 0; i--) // read backwards to increase likelihood that we wait on a different task than has data available { using (HttpResponseMessage response = await responseTasks[i]) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } } [Fact] public async Task SendAsync_HttpRequestMsgResponseHeadersRead_StatusCodeOK() { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, HttpTestServers.SecureRemoteEchoServer); using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } [ActiveIssue(4259, PlatformID.AnyUnix)] [OuterLoop] [Fact] public async Task SendAsync_ReadFromSlowStreamingServer_PartialDataReturned() { // TODO: This is a placeholder until GitHub Issue #2383 gets resolved. const string SlowStreamingServer = "http://httpbin.org/drip?numbytes=8192&duration=15&delay=1&code=200"; int bytesRead; byte[] buffer = new byte[8192]; using (var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Get, SlowStreamingServer); using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)) { Stream stream = await response.Content.ReadAsStreamAsync(); bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length); } _output.WriteLine("Bytes read from stream: {0}", bytesRead); Assert.True(bytesRead < buffer.Length, "bytesRead should be less than buffer.Length"); } } [Fact] public async Task Dispose_DisposingHandlerCancelsActiveOperations() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Task<Socket> accept = socket.AcceptAsync(); IPEndPoint local = (IPEndPoint)socket.LocalEndPoint; var client = new HttpClient(); Task<string> download = client.GetStringAsync($"http://{local.Address}:{local.Port}"); using (Socket acceptedSocket = await accept) { client.Dispose(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => download); } } } #region Post Methods Tests [Theory, MemberData(nameof(VerifyUploadServers))] public async Task PostAsync_CallMethodTwice_StringContent(Uri remoteServer) { using (var client = new HttpClient()) { string data = "Test String"; var content = new StringContent(data, Encoding.UTF8); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data); HttpResponseMessage response; using (response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } // Repeat call. content = new StringContent(data, Encoding.UTF8); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data); using (response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Theory, MemberData(nameof(VerifyUploadServers))] public async Task PostAsync_CallMethod_UnicodeStringContent(Uri remoteServer) { using (var client = new HttpClient()) { string data = "\ub4f1\uffc7\u4e82\u67ab4\uc6d4\ud1a0\uc694\uc77c\uffda3\u3155\uc218\uffdb"; var content = new StringContent(data, Encoding.UTF8); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Theory, MemberData(nameof(VerifyUploadServersStreamsAndExpectedData))] public async Task PostAsync_CallMethod_StreamContent(Uri remoteServer, Stream requestContentStream, byte[] expectedData) { using (var client = new HttpClient()) { HttpContent content = new StreamContent(requestContentStream); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } public static IEnumerable<object[]> VerifyUploadServersStreamsAndExpectedData { get { foreach (object[] serverArr in VerifyUploadServers) { Uri server = (Uri)serverArr[0]; byte[] data = new byte[1234]; new Random(42).NextBytes(data); // A MemoryStream { var memStream = new MemoryStream(data, writable: false); yield return new object[] { server, memStream, data }; } // A stream that provides the data synchronously and has a known length { var wrappedMemStream = new MemoryStream(data, writable: false); var syncKnownLengthStream = new DelegateStream( canReadFunc: () => wrappedMemStream.CanRead, canSeekFunc: () => wrappedMemStream.CanSeek, lengthFunc: () => wrappedMemStream.Length, positionGetFunc: () => wrappedMemStream.Position, readAsyncFunc: (buffer, offset, count, token) => wrappedMemStream.ReadAsync(buffer, offset, count, token)); yield return new object[] { server, syncKnownLengthStream, data }; } // A stream that provides the data synchronously and has an unknown length { int syncUnknownLengthStreamOffset = 0; var syncUnknownLengthStream = new DelegateStream( canReadFunc: () => true, canSeekFunc: () => false, readAsyncFunc: (buffer, offset, count, token) => { int bytesRemaining = data.Length - syncUnknownLengthStreamOffset; int bytesToCopy = Math.Min(bytesRemaining, count); Array.Copy(data, syncUnknownLengthStreamOffset, buffer, offset, bytesToCopy); syncUnknownLengthStreamOffset += bytesToCopy; return Task.FromResult(bytesToCopy); }); yield return new object[] { server, syncUnknownLengthStream, data }; } // A stream that provides the data asynchronously { int asyncStreamOffset = 0, maxDataPerRead = 100; var asyncStream = new DelegateStream( canReadFunc: () => true, canSeekFunc: () => false, readAsyncFunc: async (buffer, offset, count, token) => { await Task.Delay(1).ConfigureAwait(false); int bytesRemaining = data.Length - asyncStreamOffset; int bytesToCopy = Math.Min(bytesRemaining, Math.Min(maxDataPerRead, count)); Array.Copy(data, asyncStreamOffset, buffer, offset, bytesToCopy); asyncStreamOffset += bytesToCopy; return bytesToCopy; }); yield return new object[] { server, asyncStream, data }; } } } } [Theory, MemberData(nameof(EchoServers))] public async Task PostAsync_CallMethod_NullContent(Uri remoteServer) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.PostAsync(remoteServer, null)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, string.Empty); } } } [Theory, MemberData(nameof(EchoServers))] public async Task PostAsync_CallMethod_EmptyContent(Uri remoteServer) { using (var client = new HttpClient()) { var content = new StringContent(string.Empty); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, string.Empty); } } } [Theory] [InlineData(false)] [InlineData(true)] public async Task PostAsync_Redirect_ResultingGetFormattedCorrectly(bool secure) { const string ContentString = "This is the content string."; var content = new StringContent(ContentString); Uri redirectUri = HttpTestServers.RedirectUriForDestinationUri( secure, 302, secure ? HttpTestServers.SecureRemoteEchoServer : HttpTestServers.RemoteEchoServer, 1); using (var client = new HttpClient()) using (HttpResponseMessage response = await client.PostAsync(redirectUri, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); Assert.DoesNotContain(ContentString, responseContent); Assert.DoesNotContain("Content-Length", responseContent); } } [Theory] [InlineData(HttpStatusCode.MethodNotAllowed, "Custom description")] [InlineData(HttpStatusCode.MethodNotAllowed, "")] public async Task GetAsync_CallMethod_ExpectedStatusLine(HttpStatusCode statusCode, string reasonPhrase) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(HttpTestServers.StatusCodeUri( false, (int)statusCode, reasonPhrase))) { Assert.Equal(statusCode, response.StatusCode); Assert.Equal(reasonPhrase, response.ReasonPhrase); } } } [Fact] public async Task PostAsync_Post_ChannelBindingHasExpectedValue() { using (var client = new HttpClient()) { string expectedContent = "Test contest"; var content = new ChannelBindingAwareContent(expectedContent); using (HttpResponseMessage response = await client.PostAsync(HttpTestServers.SecureRemoteEchoServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); ChannelBinding channelBinding = content.ChannelBinding; Assert.NotNull(channelBinding); _output.WriteLine("Channel Binding: {0}", channelBinding); } } } #endregion #region Various HTTP Method Tests [Theory, MemberData(nameof(HttpMethods))] public async Task SendAsync_SendRequestUsingMethodToEchoServerWithNoContent_MethodCorrectlySent( string method, bool secureServer) { using (var client = new HttpClient()) { var request = new HttpRequestMessage( new HttpMethod(method), secureServer ? HttpTestServers.SecureRemoteEchoServer : HttpTestServers.RemoteEchoServer); using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyRequestMethod(response, method); } } } [Theory, MemberData(nameof(HttpMethodsThatAllowContent))] public async Task SendAsync_SendRequestUsingMethodToEchoServerWithContent_Success( string method, bool secureServer) { using (var client = new HttpClient()) { var request = new HttpRequestMessage( new HttpMethod(method), secureServer ? HttpTestServers.SecureRemoteEchoServer : HttpTestServers.RemoteEchoServer); request.Content = new StringContent(ExpectedContent); using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyRequestMethod(response, method); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); Assert.Contains($"\"Content-Length\": \"{request.Content.Headers.ContentLength.Value}\"", responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, ExpectedContent); } } } #endregion #region Version tests // The HTTP RFC 7230 states that servers are NOT required to respond back with the same // minor version if they support a higher minor version. In fact, the RFC states that // servers SHOULD send back the highest minor version they support. So, testing the // response version to see if the client sent a particular request version only works // for some servers. In particular the 'Http2Servers' used in these tests always seem // to echo the minor version of the request. [Theory, MemberData(nameof(Http2Servers))] public async Task SendAsync_RequestVersion10_ServerReceivesVersion10Request(Uri server) { Version responseVersion = await SendRequestAndGetResponseVersionAsync(new Version(1, 0), server); Assert.Equal(new Version(1, 0), responseVersion); } [Theory, MemberData(nameof(Http2Servers))] public async Task SendAsync_RequestVersion11_ServerReceivesVersion11Request(Uri server) { Version responseVersion = await SendRequestAndGetResponseVersionAsync(new Version(1, 1), server); Assert.Equal(new Version(1, 1), responseVersion); } [Theory, MemberData(nameof(Http2Servers))] public async Task SendAsync_RequestVersionNotSpecified_ServerReceivesVersion11Request(Uri server) { Version responseVersion = await SendRequestAndGetResponseVersionAsync(null, server); Assert.Equal(new Version(1, 1), responseVersion); } [Theory, MemberData(nameof(Http2Servers))] public async Task SendAsync_RequestVersion20_ResponseVersion20IfHttp2Supported(Uri server) { // We don't currently have a good way to test whether HTTP/2 is supported without // using the same mechanism we're trying to test, so for now we allow both 2.0 and 1.1 responses. Version responseVersion = await SendRequestAndGetResponseVersionAsync(new Version(2, 0), server); Assert.True( responseVersion == new Version(2, 0) || responseVersion == new Version(1, 1), "Response version " + responseVersion); } private async Task<Version> SendRequestAndGetResponseVersionAsync(Version requestVersion, Uri server) { var request = new HttpRequestMessage(HttpMethod.Get, server); if (requestVersion != null) { request.Version = requestVersion; } else { // The default value for HttpRequestMessage.Version is Version(1,1). // So, we need to set something different to test the "unknown" version. request.Version = new Version(0,0); } using (var client = new HttpClient()) using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); return response.Version; } } #endregion #region SSL Version tests [Theory] [InlineData("SSLv2", HttpTestServers.SSLv2RemoteServer)] [InlineData("SSLv3", HttpTestServers.SSLv3RemoteServer)] public async Task GetAsync_UnsupportedSSLVersion_Throws(string name, string url) { using (HttpClient client = new HttpClient()) { await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url)); } } [Theory] [InlineData("TLSv1.0", HttpTestServers.TLSv10RemoteServer)] [InlineData("TLSv1.1", HttpTestServers.TLSv11RemoteServer)] [InlineData("TLSv1.2", HttpTestServers.TLSv12RemoteServer)] public async Task GetAsync_SupportedSSLVersion_Succeeds(string name, string url) { using (HttpClient client = new HttpClient()) using (await client.GetAsync(url)) { } } #endregion #region Proxy tests [Theory] [MemberData(nameof(CredentialsForProxy))] public void Proxy_BypassFalse_GetRequestGoesThroughCustomProxy(ICredentials creds, bool wrapCredsInCache) { int port; Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync( out port, requireAuth: creds != null && creds != CredentialCache.DefaultCredentials, expectCreds: true); Uri proxyUrl = new Uri($"http://localhost:{port}"); const string BasicAuth = "Basic"; if (wrapCredsInCache) { Assert.IsAssignableFrom<NetworkCredential>(creds); var cache = new CredentialCache(); cache.Add(proxyUrl, BasicAuth, (NetworkCredential)creds); creds = cache; } using (var handler = new HttpClientHandler() { Proxy = new UseSpecifiedUriWebProxy(proxyUrl, creds) }) using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> responseTask = client.GetAsync(HttpTestServers.RemoteEchoServer); Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap(); Task.WaitAll(proxyTask, responseTask, responseStringTask); TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null); Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result); NetworkCredential nc = creds?.GetCredential(proxyUrl, BasicAuth); string expectedAuth = nc == null || nc == CredentialCache.DefaultCredentials ? null : string.IsNullOrEmpty(nc.Domain) ? $"{nc.UserName}:{nc.Password}" : $"{nc.Domain}\\{nc.UserName}:{nc.Password}"; Assert.Equal(expectedAuth, proxyTask.Result.AuthenticationHeaderValue); } } [Theory] [MemberData(nameof(BypassedProxies))] public async Task Proxy_BypassTrue_GetRequestDoesntGoesThroughCustomProxy(IWebProxy proxy) { using (var client = new HttpClient(new HttpClientHandler() { Proxy = proxy })) using (HttpResponseMessage response = await client.GetAsync(HttpTestServers.RemoteEchoServer)) { TestHelper.VerifyResponseBody( await response.Content.ReadAsStringAsync(), response.Content.Headers.ContentMD5, false, null); } } [Fact] public void Proxy_HaveNoCredsAndUseAuthenticatedCustomProxy_ProxyAuthenticationRequiredStatusCode() { int port; Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync( out port, requireAuth: true, expectCreds: false); Uri proxyUrl = new Uri($"http://localhost:{port}"); using (var handler = new HttpClientHandler() { Proxy = new UseSpecifiedUriWebProxy(proxyUrl, null) }) using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> responseTask = client.GetAsync(HttpTestServers.RemoteEchoServer); Task.WaitAll(proxyTask, responseTask); Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, responseTask.Result.StatusCode); } } private static IEnumerable<object[]> BypassedProxies() { yield return new object[] { null }; yield return new object[] { new PlatformNotSupportedWebProxy() }; yield return new object[] { new UseSpecifiedUriWebProxy(new Uri($"http://{Guid.NewGuid().ToString().Substring(0, 15)}:12345"), bypass: true) }; } private static IEnumerable<object[]> CredentialsForProxy() { yield return new object[] { null, false }; foreach (bool wrapCredsInCache in new[] { true, false }) { yield return new object[] { CredentialCache.DefaultCredentials, wrapCredsInCache }; yield return new object[] { new NetworkCredential("user:name", "password"), wrapCredsInCache }; yield return new object[] { new NetworkCredential("username", "password", "dom:\\ain"), wrapCredsInCache }; } } #endregion } }
using System; using SubSonic.Schema; using SubSonic.DataProviders; using System.Data; namespace Solution.DataAccess.DataModel { /// <summary> /// Table: Rules /// Primary Key: rule_id /// </summary> public class RulesStructs: DatabaseTable { public RulesStructs(IDataProvider provider):base("Rules",provider){ ClassName = "Rules"; SchemaName = "dbo"; Columns.Add(new DatabaseColumn("Id", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = false, AutoIncrement = true, IsForeignKey = false, MaxLength = 0, PropertyName = "Id" }); Columns.Add(new DatabaseColumn("rule_id", this) { IsPrimaryKey = true, DataType = DbType.AnsiString, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 8, PropertyName = "rule_id" }); Columns.Add(new DatabaseColumn("rule_name", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 50, PropertyName = "rule_name" }); Columns.Add(new DatabaseColumn("rules", this) { IsPrimaryKey = false, DataType = DbType.String, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 2000, PropertyName = "rules" }); Columns.Add(new DatabaseColumn("daysinmonth", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "daysinmonth" }); Columns.Add(new DatabaseColumn("hoursinday", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "hoursinday" }); Columns.Add(new DatabaseColumn("ot_rate", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "ot_rate" }); Columns.Add(new DatabaseColumn("sun_rate", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "sun_rate" }); Columns.Add(new DatabaseColumn("hd_rate", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "hd_rate" }); Columns.Add(new DatabaseColumn("restdatemethod", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "restdatemethod" }); Columns.Add(new DatabaseColumn("sun", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "sun" }); Columns.Add(new DatabaseColumn("sunbegin", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "sunbegin" }); Columns.Add(new DatabaseColumn("sunend", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "sunend" }); Columns.Add(new DatabaseColumn("sat", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "sat" }); Columns.Add(new DatabaseColumn("satbegin", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "satbegin" }); Columns.Add(new DatabaseColumn("satend", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "satend" }); Columns.Add(new DatabaseColumn("vrestdate", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 100, PropertyName = "vrestdate" }); Columns.Add(new DatabaseColumn("vrestbegtime", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "vrestbegtime" }); Columns.Add(new DatabaseColumn("vrestendtime", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "vrestendtime" }); Columns.Add(new DatabaseColumn("memo", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 50, PropertyName = "memo" }); Columns.Add(new DatabaseColumn("IsAllowances", this) { IsPrimaryKey = false, DataType = DbType.Byte, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "IsAllowances" }); Columns.Add(new DatabaseColumn("SatOutTime", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "SatOutTime" }); Columns.Add(new DatabaseColumn("MonInTime", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "MonInTime" }); Columns.Add(new DatabaseColumn("FriOutTime", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "FriOutTime" }); Columns.Add(new DatabaseColumn("HolInTime", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "HolInTime" }); Columns.Add(new DatabaseColumn("HolOutTime", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "HolOutTime" }); } public IColumn Id{ get{ return this.GetColumn("Id"); } } public IColumn rule_id{ get{ return this.GetColumn("rule_id"); } } public IColumn rule_name{ get{ return this.GetColumn("rule_name"); } } public IColumn rules{ get{ return this.GetColumn("rules"); } } public IColumn daysinmonth{ get{ return this.GetColumn("daysinmonth"); } } public IColumn hoursinday{ get{ return this.GetColumn("hoursinday"); } } public IColumn ot_rate{ get{ return this.GetColumn("ot_rate"); } } public IColumn sun_rate{ get{ return this.GetColumn("sun_rate"); } } public IColumn hd_rate{ get{ return this.GetColumn("hd_rate"); } } public IColumn restdatemethod{ get{ return this.GetColumn("restdatemethod"); } } public IColumn sun{ get{ return this.GetColumn("sun"); } } public IColumn sunbegin{ get{ return this.GetColumn("sunbegin"); } } public IColumn sunend{ get{ return this.GetColumn("sunend"); } } public IColumn sat{ get{ return this.GetColumn("sat"); } } public IColumn satbegin{ get{ return this.GetColumn("satbegin"); } } public IColumn satend{ get{ return this.GetColumn("satend"); } } public IColumn vrestdate{ get{ return this.GetColumn("vrestdate"); } } public IColumn vrestbegtime{ get{ return this.GetColumn("vrestbegtime"); } } public IColumn vrestendtime{ get{ return this.GetColumn("vrestendtime"); } } public IColumn memo{ get{ return this.GetColumn("memo"); } } public IColumn IsAllowances{ get{ return this.GetColumn("IsAllowances"); } } public IColumn SatOutTime{ get{ return this.GetColumn("SatOutTime"); } } public IColumn MonInTime{ get{ return this.GetColumn("MonInTime"); } } public IColumn FriOutTime{ get{ return this.GetColumn("FriOutTime"); } } public IColumn HolInTime{ get{ return this.GetColumn("HolInTime"); } } public IColumn HolOutTime{ get{ return this.GetColumn("HolOutTime"); } } } }
// Copyright 2007-2008 The Apache Software Foundation. // // 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 MassTransit.Tests.Serialization { using System; using MassTransit.Pipeline; using MassTransit.Pipeline.Configuration; using MassTransit.Serialization; using NUnit.Framework; using TestConsumers; public abstract class Deserializing_an_interface<TSerializer> : SerializationSpecificationBase<TSerializer> where TSerializer : IMessageSerializer, new() { [Test] public void Should_create_a_proxy_for_the_interface() { var user = new UserImpl("Chris", "[email protected]"); ComplaintAdded complaint = new ComplaintAddedImpl(user, "No toilet paper", BusinessArea.Appearance) { Body = "There was no toilet paper in the stall, forcing me to use my treasured issue of .NET Developer magazine." }; TestSerialization(complaint); } [Test] public void Should_dispatch_an_interface_via_the_pipeline() { var pipeline = InboundPipelineConfigurator.CreateDefault(null); var consumer = new TestMessageConsumer<ComplaintAdded>(); pipeline.ConnectInstance(consumer); var user = new UserImpl("Chris", "[email protected]"); ComplaintAdded complaint = new ComplaintAddedImpl(user, "No toilet paper", BusinessArea.Appearance) { Body = "There was no toilet paper in the stall, forcing me to use my treasured issue of .NET Developer magazine." }; pipeline.Dispatch(complaint); consumer.ShouldHaveReceivedMessage(complaint); } } [TestFixture] public class WhenUsingCustomXml : Deserializing_an_interface<XmlMessageSerializer> { } [TestFixture][Explicit("the built in binary serializer doesn't support this feature")] public class WhenUsingBinary : Deserializing_an_interface<BinaryMessageSerializer> { } [TestFixture] public class WhenUsingJson : Deserializing_an_interface<JsonMessageSerializer> { } [TestFixture] public class WhenUsingBson : Deserializing_an_interface<BsonMessageSerializer> { } public interface ComplaintAdded { User AddedBy { get; } DateTime AddedAt { get; } string Subject { get; } string Body { get; } BusinessArea Area { get; } } public enum BusinessArea { Unknown = 0, Appearance, Courtesy, } public interface User { string Name { get; } string Email { get; } } public class UserImpl : User { public UserImpl(string name, string email) { Name = name; Email = email; } protected UserImpl() { } public string Name { get; set; } public string Email { get; set; } public bool Equals(User other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Equals(other.Name, Name) && Equals(other.Email, Email); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if(!typeof(User).IsAssignableFrom(obj.GetType())) return false; return Equals((User) obj); } public override int GetHashCode() { unchecked { return ((Name != null ? Name.GetHashCode() : 0)*397) ^ (Email != null ? Email.GetHashCode() : 0); } } } public class ComplaintAddedImpl : ComplaintAdded { public ComplaintAddedImpl(User addedBy, string subject, BusinessArea area) { DateTime dateTime = DateTime.UtcNow; AddedAt = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, DateTimeKind.Utc); AddedBy = addedBy; Subject = subject; Area = area; Body = string.Empty; } protected ComplaintAddedImpl() { } public User AddedBy { get; set; } public DateTime AddedAt { get; set; } public string Subject { get; set; } public string Body { get; set; } public BusinessArea Area { get; set; } public bool Equals(ComplaintAdded other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return AddedBy.Equals(other.AddedBy) && other.AddedAt.Equals(AddedAt) && Equals(other.Subject, Subject) && Equals(other.Body, Body) && Equals(other.Area, Area); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (!typeof(ComplaintAdded).IsAssignableFrom(obj.GetType())) return false; return Equals((ComplaintAdded)obj); } public override int GetHashCode() { unchecked { int result = (AddedBy != null ? AddedBy.GetHashCode() : 0); result = (result*397) ^ AddedAt.GetHashCode(); result = (result*397) ^ (Subject != null ? Subject.GetHashCode() : 0); result = (result*397) ^ (Body != null ? Body.GetHashCode() : 0); result = (result*397) ^ Area.GetHashCode(); return result; } } } }
// // mcs/class/System.Data/System.Data/XmlDiffLoader.cs // // Purpose: Loads XmlDiffGrams to DataSet // // class: XmlDiffLoader // assembly: System.Data.dll // namespace: System.Data // // Author: // Ville Palo <[email protected]> // Lluis Sanchez Gual ([email protected]) // // (c)copyright 2003 Ville Palo // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Data; using System.Xml; using System.Xml.Schema; using System.Xml.XPath; using System.Collections; using System.Globalization; namespace System.Data { internal class XmlDiffLoader { #region Fields private DataSet DSet; private DataTable table; private Hashtable DiffGrRows = new Hashtable (); private Hashtable ErrorRows = new Hashtable (); #endregion // Fields #region ctors public XmlDiffLoader (DataSet DSet) { this.DSet = DSet; } public XmlDiffLoader (DataTable table) { this.table = table; } #endregion //ctors #region Public methods public void Load (XmlReader reader) { bool origEnforceConstraint = false; if (DSet != null) { origEnforceConstraint = DSet.EnforceConstraints; DSet.EnforceConstraints = false; } reader.MoveToContent (); if (reader.IsEmptyElement) { reader.Skip (); return; } reader.ReadStartElement ("diffgram", XmlConstants.DiffgrNamespace); reader.MoveToContent (); while (reader.NodeType != XmlNodeType.EndElement) { if (reader.NodeType == XmlNodeType.Element) { if (reader.LocalName == "before" && reader.NamespaceURI == XmlConstants.DiffgrNamespace) LoadBefore (reader); else if (reader.LocalName == "errors" && reader.NamespaceURI == XmlConstants.DiffgrNamespace) LoadErrors (reader); else LoadCurrent (reader); } else reader.Skip (); } reader.ReadEndElement (); if (DSet != null) DSet.EnforceConstraints = origEnforceConstraint; } #endregion // Public methods #region Private methods private void LoadCurrent (XmlReader reader) { if (reader.IsEmptyElement) { reader.Skip(); return; } reader.ReadStartElement (); // Dataset root reader.MoveToContent (); while (reader.NodeType != XmlNodeType.EndElement) { if (reader.NodeType == XmlNodeType.Element) { DataTable t = GetTable (reader.LocalName); if (t != null) LoadCurrentTable (t, reader); #if true else reader.Skip (); #else else throw new DataException (Locale.GetText ("Cannot load diffGram. Table '" + reader.LocalName + "' is missing in the destination dataset")); #endif } else reader.Skip (); } reader.ReadEndElement (); } private void LoadBefore (XmlReader reader) { if (reader.IsEmptyElement) { reader.Skip (); return; } reader.ReadStartElement (); reader.MoveToContent (); while (reader.NodeType != XmlNodeType.EndElement) { if (reader.NodeType == XmlNodeType.Element) { DataTable t = GetTable (reader.LocalName); if (t != null) LoadBeforeTable(t, reader); else throw new DataException (Locale.GetText ("Cannot load diffGram. Table '" + reader.LocalName + "' is missing in the destination dataset")); } else reader.Skip (); } reader.ReadEndElement (); } private void LoadErrors (XmlReader reader) { if (reader.IsEmptyElement) { reader.Skip (); return; } reader.ReadStartElement (); reader.MoveToContent (); while (reader.NodeType != XmlNodeType.EndElement) { if (reader.NodeType == XmlNodeType.Element) { DataRow Row = null; // find the row in 'current' section string id = reader.GetAttribute ("id", XmlConstants.DiffgrNamespace); if (id != null) Row = (DataRow) ErrorRows [id]; if (reader.IsEmptyElement) continue; reader.ReadStartElement (); while (reader.NodeType != XmlNodeType.EndElement) { if (reader.NodeType == XmlNodeType.Element) { string error = reader.GetAttribute ("Error", XmlConstants.DiffgrNamespace); Row.SetColumnError (reader.LocalName, error); } reader.Read (); } } else reader.Skip (); } reader.ReadEndElement (); } private void LoadColumns (DataTable Table, DataRow Row, XmlReader reader, DataRowVersion loadType) { // attributes LoadColumnAttributes (Table, Row, reader, loadType); LoadColumnChildren (Table, Row, reader, loadType); } private void LoadColumnAttributes (DataTable Table, DataRow Row, XmlReader reader, DataRowVersion loadType) { if (!reader.HasAttributes // this check will be faster || !reader.MoveToFirstAttribute ()) return; do { switch (reader.NamespaceURI) { case XmlConstants.XmlnsNS: case XmlConstants.DiffgrNamespace: case XmlConstants.MsdataNamespace: case XmlConstants.MspropNamespace: case XmlSchema.Namespace: continue; } DataColumn c = Table.Columns [reader.LocalName]; if (c == null || c.ColumnMapping != MappingType.Attribute) continue; if (c.Namespace == null && reader.NamespaceURI == String.Empty || c.Namespace == reader.NamespaceURI) { object data = XmlDataLoader.StringToObject (c.DataType, reader.Value); if (loadType == DataRowVersion.Current) Row [c] = data; else Row.SetOriginalValue (c.ColumnName, data); } // otherwise just ignore as well as unknown elements. } while (reader.MoveToNextAttribute ()); reader.MoveToElement (); } private void LoadColumnChildren (DataTable Table, DataRow Row, XmlReader reader, DataRowVersion loadType) { // children if (reader.IsEmptyElement) { reader.Skip (); return; } reader.ReadStartElement (); reader.MoveToContent (); while (reader.NodeType != XmlNodeType.EndElement) { if (reader.NodeType != XmlNodeType.Element) { reader.Read (); continue; } if (Table.Columns.Contains (reader.LocalName)) { string colName = reader.LocalName; object data = XmlDataLoader.StringToObject (Table.Columns[colName].DataType, reader.ReadString ()); if (loadType == DataRowVersion.Current) Row [colName] = data; else Row.SetOriginalValue (colName, data); reader.Read (); } else { DataTable t = GetTable (reader.LocalName); if (t != null) { if (loadType == DataRowVersion.Original) LoadBeforeTable (t, reader); else if (loadType == DataRowVersion.Current) LoadCurrentTable (t, reader); } } } reader.ReadEndElement (); } private void LoadBeforeTable (DataTable Table, XmlReader reader) { string id = reader.GetAttribute ("id", XmlConstants.DiffgrNamespace); string rowOrder = reader.GetAttribute ("rowOrder", XmlConstants.MsdataNamespace); DataRow Row = (DataRow) DiffGrRows [id]; if (Row == null) { // Deleted row Row = Table.NewRow (); LoadColumns (Table, Row, reader, DataRowVersion.Current); Table.Rows.InsertAt (Row, int.Parse (rowOrder)); Row.AcceptChanges (); Row.Delete (); } else { LoadColumns (Table, Row, reader, DataRowVersion.Original); } } private void LoadCurrentTable (DataTable Table, XmlReader reader) { DataRowState state; DataRow Row = Table.NewRow (); string id = reader.GetAttribute ("id", XmlConstants.DiffgrNamespace); string error = reader.GetAttribute ("hasErrors"); string changes = reader.GetAttribute ("hasChanges", XmlConstants.DiffgrNamespace); if (changes != null) { if (string.Compare (changes, "modified", true) == 0) { DiffGrRows.Add (id, Row); // for later use state = DataRowState.Modified; } else if (string.Compare (changes, "inserted", true) == 0) { state = DataRowState.Added; } else throw new InvalidOperationException ("Invalid row change state"); } else state = DataRowState.Unchanged; // If row had errors add row to hashtable for later use if (error != null && string.Compare (error, "true", true) == 0) ErrorRows.Add (id, Row); LoadColumns (Table, Row, reader, DataRowVersion.Current); Table.Rows.Add (Row); if (state != DataRowState.Added) Row.AcceptChanges (); } DataTable GetTable (string name) { if (DSet != null) return DSet.Tables [name]; else if (name == table.TableName) return table; else return null; } #endregion // Private methods } }
using System; using ChainUtils.BouncyCastle.Crypto.Parameters; namespace ChainUtils.BouncyCastle.Crypto.Engines { /** * A class that provides Twofish encryption operations. * * This Java implementation is based on the Java reference * implementation provided by Bruce Schneier and developed * by Raif S. Naffah. */ public sealed class TwofishEngine : IBlockCipher { private static readonly byte[,] P = { { // p0 (byte) 0xA9, (byte) 0x67, (byte) 0xB3, (byte) 0xE8, (byte) 0x04, (byte) 0xFD, (byte) 0xA3, (byte) 0x76, (byte) 0x9A, (byte) 0x92, (byte) 0x80, (byte) 0x78, (byte) 0xE4, (byte) 0xDD, (byte) 0xD1, (byte) 0x38, (byte) 0x0D, (byte) 0xC6, (byte) 0x35, (byte) 0x98, (byte) 0x18, (byte) 0xF7, (byte) 0xEC, (byte) 0x6C, (byte) 0x43, (byte) 0x75, (byte) 0x37, (byte) 0x26, (byte) 0xFA, (byte) 0x13, (byte) 0x94, (byte) 0x48, (byte) 0xF2, (byte) 0xD0, (byte) 0x8B, (byte) 0x30, (byte) 0x84, (byte) 0x54, (byte) 0xDF, (byte) 0x23, (byte) 0x19, (byte) 0x5B, (byte) 0x3D, (byte) 0x59, (byte) 0xF3, (byte) 0xAE, (byte) 0xA2, (byte) 0x82, (byte) 0x63, (byte) 0x01, (byte) 0x83, (byte) 0x2E, (byte) 0xD9, (byte) 0x51, (byte) 0x9B, (byte) 0x7C, (byte) 0xA6, (byte) 0xEB, (byte) 0xA5, (byte) 0xBE, (byte) 0x16, (byte) 0x0C, (byte) 0xE3, (byte) 0x61, (byte) 0xC0, (byte) 0x8C, (byte) 0x3A, (byte) 0xF5, (byte) 0x73, (byte) 0x2C, (byte) 0x25, (byte) 0x0B, (byte) 0xBB, (byte) 0x4E, (byte) 0x89, (byte) 0x6B, (byte) 0x53, (byte) 0x6A, (byte) 0xB4, (byte) 0xF1, (byte) 0xE1, (byte) 0xE6, (byte) 0xBD, (byte) 0x45, (byte) 0xE2, (byte) 0xF4, (byte) 0xB6, (byte) 0x66, (byte) 0xCC, (byte) 0x95, (byte) 0x03, (byte) 0x56, (byte) 0xD4, (byte) 0x1C, (byte) 0x1E, (byte) 0xD7, (byte) 0xFB, (byte) 0xC3, (byte) 0x8E, (byte) 0xB5, (byte) 0xE9, (byte) 0xCF, (byte) 0xBF, (byte) 0xBA, (byte) 0xEA, (byte) 0x77, (byte) 0x39, (byte) 0xAF, (byte) 0x33, (byte) 0xC9, (byte) 0x62, (byte) 0x71, (byte) 0x81, (byte) 0x79, (byte) 0x09, (byte) 0xAD, (byte) 0x24, (byte) 0xCD, (byte) 0xF9, (byte) 0xD8, (byte) 0xE5, (byte) 0xC5, (byte) 0xB9, (byte) 0x4D, (byte) 0x44, (byte) 0x08, (byte) 0x86, (byte) 0xE7, (byte) 0xA1, (byte) 0x1D, (byte) 0xAA, (byte) 0xED, (byte) 0x06, (byte) 0x70, (byte) 0xB2, (byte) 0xD2, (byte) 0x41, (byte) 0x7B, (byte) 0xA0, (byte) 0x11, (byte) 0x31, (byte) 0xC2, (byte) 0x27, (byte) 0x90, (byte) 0x20, (byte) 0xF6, (byte) 0x60, (byte) 0xFF, (byte) 0x96, (byte) 0x5C, (byte) 0xB1, (byte) 0xAB, (byte) 0x9E, (byte) 0x9C, (byte) 0x52, (byte) 0x1B, (byte) 0x5F, (byte) 0x93, (byte) 0x0A, (byte) 0xEF, (byte) 0x91, (byte) 0x85, (byte) 0x49, (byte) 0xEE, (byte) 0x2D, (byte) 0x4F, (byte) 0x8F, (byte) 0x3B, (byte) 0x47, (byte) 0x87, (byte) 0x6D, (byte) 0x46, (byte) 0xD6, (byte) 0x3E, (byte) 0x69, (byte) 0x64, (byte) 0x2A, (byte) 0xCE, (byte) 0xCB, (byte) 0x2F, (byte) 0xFC, (byte) 0x97, (byte) 0x05, (byte) 0x7A, (byte) 0xAC, (byte) 0x7F, (byte) 0xD5, (byte) 0x1A, (byte) 0x4B, (byte) 0x0E, (byte) 0xA7, (byte) 0x5A, (byte) 0x28, (byte) 0x14, (byte) 0x3F, (byte) 0x29, (byte) 0x88, (byte) 0x3C, (byte) 0x4C, (byte) 0x02, (byte) 0xB8, (byte) 0xDA, (byte) 0xB0, (byte) 0x17, (byte) 0x55, (byte) 0x1F, (byte) 0x8A, (byte) 0x7D, (byte) 0x57, (byte) 0xC7, (byte) 0x8D, (byte) 0x74, (byte) 0xB7, (byte) 0xC4, (byte) 0x9F, (byte) 0x72, (byte) 0x7E, (byte) 0x15, (byte) 0x22, (byte) 0x12, (byte) 0x58, (byte) 0x07, (byte) 0x99, (byte) 0x34, (byte) 0x6E, (byte) 0x50, (byte) 0xDE, (byte) 0x68, (byte) 0x65, (byte) 0xBC, (byte) 0xDB, (byte) 0xF8, (byte) 0xC8, (byte) 0xA8, (byte) 0x2B, (byte) 0x40, (byte) 0xDC, (byte) 0xFE, (byte) 0x32, (byte) 0xA4, (byte) 0xCA, (byte) 0x10, (byte) 0x21, (byte) 0xF0, (byte) 0xD3, (byte) 0x5D, (byte) 0x0F, (byte) 0x00, (byte) 0x6F, (byte) 0x9D, (byte) 0x36, (byte) 0x42, (byte) 0x4A, (byte) 0x5E, (byte) 0xC1, (byte) 0xE0 }, { // p1 (byte) 0x75, (byte) 0xF3, (byte) 0xC6, (byte) 0xF4, (byte) 0xDB, (byte) 0x7B, (byte) 0xFB, (byte) 0xC8, (byte) 0x4A, (byte) 0xD3, (byte) 0xE6, (byte) 0x6B, (byte) 0x45, (byte) 0x7D, (byte) 0xE8, (byte) 0x4B, (byte) 0xD6, (byte) 0x32, (byte) 0xD8, (byte) 0xFD, (byte) 0x37, (byte) 0x71, (byte) 0xF1, (byte) 0xE1, (byte) 0x30, (byte) 0x0F, (byte) 0xF8, (byte) 0x1B, (byte) 0x87, (byte) 0xFA, (byte) 0x06, (byte) 0x3F, (byte) 0x5E, (byte) 0xBA, (byte) 0xAE, (byte) 0x5B, (byte) 0x8A, (byte) 0x00, (byte) 0xBC, (byte) 0x9D, (byte) 0x6D, (byte) 0xC1, (byte) 0xB1, (byte) 0x0E, (byte) 0x80, (byte) 0x5D, (byte) 0xD2, (byte) 0xD5, (byte) 0xA0, (byte) 0x84, (byte) 0x07, (byte) 0x14, (byte) 0xB5, (byte) 0x90, (byte) 0x2C, (byte) 0xA3, (byte) 0xB2, (byte) 0x73, (byte) 0x4C, (byte) 0x54, (byte) 0x92, (byte) 0x74, (byte) 0x36, (byte) 0x51, (byte) 0x38, (byte) 0xB0, (byte) 0xBD, (byte) 0x5A, (byte) 0xFC, (byte) 0x60, (byte) 0x62, (byte) 0x96, (byte) 0x6C, (byte) 0x42, (byte) 0xF7, (byte) 0x10, (byte) 0x7C, (byte) 0x28, (byte) 0x27, (byte) 0x8C, (byte) 0x13, (byte) 0x95, (byte) 0x9C, (byte) 0xC7, (byte) 0x24, (byte) 0x46, (byte) 0x3B, (byte) 0x70, (byte) 0xCA, (byte) 0xE3, (byte) 0x85, (byte) 0xCB, (byte) 0x11, (byte) 0xD0, (byte) 0x93, (byte) 0xB8, (byte) 0xA6, (byte) 0x83, (byte) 0x20, (byte) 0xFF, (byte) 0x9F, (byte) 0x77, (byte) 0xC3, (byte) 0xCC, (byte) 0x03, (byte) 0x6F, (byte) 0x08, (byte) 0xBF, (byte) 0x40, (byte) 0xE7, (byte) 0x2B, (byte) 0xE2, (byte) 0x79, (byte) 0x0C, (byte) 0xAA, (byte) 0x82, (byte) 0x41, (byte) 0x3A, (byte) 0xEA, (byte) 0xB9, (byte) 0xE4, (byte) 0x9A, (byte) 0xA4, (byte) 0x97, (byte) 0x7E, (byte) 0xDA, (byte) 0x7A, (byte) 0x17, (byte) 0x66, (byte) 0x94, (byte) 0xA1, (byte) 0x1D, (byte) 0x3D, (byte) 0xF0, (byte) 0xDE, (byte) 0xB3, (byte) 0x0B, (byte) 0x72, (byte) 0xA7, (byte) 0x1C, (byte) 0xEF, (byte) 0xD1, (byte) 0x53, (byte) 0x3E, (byte) 0x8F, (byte) 0x33, (byte) 0x26, (byte) 0x5F, (byte) 0xEC, (byte) 0x76, (byte) 0x2A, (byte) 0x49, (byte) 0x81, (byte) 0x88, (byte) 0xEE, (byte) 0x21, (byte) 0xC4, (byte) 0x1A, (byte) 0xEB, (byte) 0xD9, (byte) 0xC5, (byte) 0x39, (byte) 0x99, (byte) 0xCD, (byte) 0xAD, (byte) 0x31, (byte) 0x8B, (byte) 0x01, (byte) 0x18, (byte) 0x23, (byte) 0xDD, (byte) 0x1F, (byte) 0x4E, (byte) 0x2D, (byte) 0xF9, (byte) 0x48, (byte) 0x4F, (byte) 0xF2, (byte) 0x65, (byte) 0x8E, (byte) 0x78, (byte) 0x5C, (byte) 0x58, (byte) 0x19, (byte) 0x8D, (byte) 0xE5, (byte) 0x98, (byte) 0x57, (byte) 0x67, (byte) 0x7F, (byte) 0x05, (byte) 0x64, (byte) 0xAF, (byte) 0x63, (byte) 0xB6, (byte) 0xFE, (byte) 0xF5, (byte) 0xB7, (byte) 0x3C, (byte) 0xA5, (byte) 0xCE, (byte) 0xE9, (byte) 0x68, (byte) 0x44, (byte) 0xE0, (byte) 0x4D, (byte) 0x43, (byte) 0x69, (byte) 0x29, (byte) 0x2E, (byte) 0xAC, (byte) 0x15, (byte) 0x59, (byte) 0xA8, (byte) 0x0A, (byte) 0x9E, (byte) 0x6E, (byte) 0x47, (byte) 0xDF, (byte) 0x34, (byte) 0x35, (byte) 0x6A, (byte) 0xCF, (byte) 0xDC, (byte) 0x22, (byte) 0xC9, (byte) 0xC0, (byte) 0x9B, (byte) 0x89, (byte) 0xD4, (byte) 0xED, (byte) 0xAB, (byte) 0x12, (byte) 0xA2, (byte) 0x0D, (byte) 0x52, (byte) 0xBB, (byte) 0x02, (byte) 0x2F, (byte) 0xA9, (byte) 0xD7, (byte) 0x61, (byte) 0x1E, (byte) 0xB4, (byte) 0x50, (byte) 0x04, (byte) 0xF6, (byte) 0xC2, (byte) 0x16, (byte) 0x25, (byte) 0x86, (byte) 0x56, (byte) 0x55, (byte) 0x09, (byte) 0xBE, (byte) 0x91 } }; /** * Define the fixed p0/p1 permutations used in keyed S-box lookup. * By changing the following constant definitions, the S-boxes will * automatically Get changed in the Twofish engine. */ private const int P_00 = 1; private const int P_01 = 0; private const int P_02 = 0; private const int P_03 = P_01 ^ 1; private const int P_04 = 1; private const int P_10 = 0; private const int P_11 = 0; private const int P_12 = 1; private const int P_13 = P_11 ^ 1; private const int P_14 = 0; private const int P_20 = 1; private const int P_21 = 1; private const int P_22 = 0; private const int P_23 = P_21 ^ 1; private const int P_24 = 0; private const int P_30 = 0; private const int P_31 = 1; private const int P_32 = 1; private const int P_33 = P_31 ^ 1; private const int P_34 = 1; /* Primitive polynomial for GF(256) */ private const int GF256_FDBK = 0x169; private const int GF256_FDBK_2 = GF256_FDBK / 2; private const int GF256_FDBK_4 = GF256_FDBK / 4; private const int RS_GF_FDBK = 0x14D; // field generator //==================================== // Useful constants //==================================== private const int ROUNDS = 16; private const int MAX_ROUNDS = 16; // bytes = 128 bits private const int BLOCK_SIZE = 16; // bytes = 128 bits private const int MAX_KEY_BITS = 256; private const int INPUT_WHITEN=0; private const int OUTPUT_WHITEN=INPUT_WHITEN+BLOCK_SIZE/4; // 4 private const int ROUND_SUBKEYS=OUTPUT_WHITEN+BLOCK_SIZE/4;// 8 private const int TOTAL_SUBKEYS=ROUND_SUBKEYS+2*MAX_ROUNDS;// 40 private const int SK_STEP = 0x02020202; private const int SK_BUMP = 0x01010101; private const int SK_ROTL = 9; private bool encrypting; private int[] gMDS0 = new int[MAX_KEY_BITS]; private int[] gMDS1 = new int[MAX_KEY_BITS]; private int[] gMDS2 = new int[MAX_KEY_BITS]; private int[] gMDS3 = new int[MAX_KEY_BITS]; /** * gSubKeys[] and gSBox[] are eventually used in the * encryption and decryption methods. */ private int[] gSubKeys; private int[] gSBox; private int k64Cnt; private byte[] workingKey; public TwofishEngine() { // calculate the MDS matrix var m1 = new int[2]; var mX = new int[2]; var mY = new int[2]; int j; for (var i=0; i< MAX_KEY_BITS ; i++) { j = P[0,i] & 0xff; m1[0] = j; mX[0] = Mx_X(j) & 0xff; mY[0] = Mx_Y(j) & 0xff; j = P[1,i] & 0xff; m1[1] = j; mX[1] = Mx_X(j) & 0xff; mY[1] = Mx_Y(j) & 0xff; gMDS0[i] = m1[P_00] | mX[P_00] << 8 | mY[P_00] << 16 | mY[P_00] << 24; gMDS1[i] = mY[P_10] | mY[P_10] << 8 | mX[P_10] << 16 | m1[P_10] << 24; gMDS2[i] = mX[P_20] | mY[P_20] << 8 | m1[P_20] << 16 | mY[P_20] << 24; gMDS3[i] = mX[P_30] | m1[P_30] << 8 | mY[P_30] << 16 | mX[P_30] << 24; } } /** * initialise a Twofish cipher. * * @param forEncryption whether or not we are for encryption. * @param parameters the parameters required to set up the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public void Init( bool forEncryption, ICipherParameters parameters) { if (!(parameters is KeyParameter)) throw new ArgumentException("invalid parameter passed to Twofish init - " + parameters.GetType().ToString()); encrypting = forEncryption; workingKey = ((KeyParameter)parameters).GetKey(); k64Cnt = (workingKey.Length / 8); // pre-padded ? SetKey(workingKey); } public string AlgorithmName { get { return "Twofish"; } } public bool IsPartialBlockOkay { get { return false; } } public int ProcessBlock( byte[] input, int inOff, byte[] output, int outOff) { if (workingKey == null) throw new InvalidOperationException("Twofish not initialised"); if ((inOff + BLOCK_SIZE) > input.Length) throw new DataLengthException("input buffer too short"); if ((outOff + BLOCK_SIZE) > output.Length) throw new DataLengthException("output buffer too short"); if (encrypting) { EncryptBlock(input, inOff, output, outOff); } else { DecryptBlock(input, inOff, output, outOff); } return BLOCK_SIZE; } public void Reset() { if (workingKey != null) { SetKey(workingKey); } } public int GetBlockSize() { return BLOCK_SIZE; } //================================== // Private Implementation //================================== private void SetKey(byte[] key) { var k32e = new int[MAX_KEY_BITS/64]; // 4 var k32o = new int[MAX_KEY_BITS/64]; // 4 var sBoxKeys = new int[MAX_KEY_BITS/64]; // 4 gSubKeys = new int[TOTAL_SUBKEYS]; if (k64Cnt < 1) { throw new ArgumentException("Key size less than 64 bits"); } if (k64Cnt > 4) { throw new ArgumentException("Key size larger than 256 bits"); } /* * k64Cnt is the number of 8 byte blocks (64 chunks) * that are in the input key. The input key is a * maximum of 32 bytes ( 256 bits ), so the range * for k64Cnt is 1..4 */ for (int i=0,p=0; i<k64Cnt ; i++) { p = i* 8; k32e[i] = BytesTo32Bits(key, p); k32o[i] = BytesTo32Bits(key, p+4); sBoxKeys[k64Cnt-1-i] = RS_MDS_Encode(k32e[i], k32o[i]); } int q,A,B; for (var i=0; i < TOTAL_SUBKEYS / 2 ; i++) { q = i*SK_STEP; A = F32(q, k32e); B = F32(q+SK_BUMP, k32o); B = B << 8 | (int)((uint)B >> 24); A += B; gSubKeys[i*2] = A; A += B; gSubKeys[i*2 + 1] = A << SK_ROTL | (int)((uint)A >> (32-SK_ROTL)); } /* * fully expand the table for speed */ var k0 = sBoxKeys[0]; var k1 = sBoxKeys[1]; var k2 = sBoxKeys[2]; var k3 = sBoxKeys[3]; int b0, b1, b2, b3; gSBox = new int[4*MAX_KEY_BITS]; for (var i=0; i<MAX_KEY_BITS; i++) { b0 = b1 = b2 = b3 = i; switch (k64Cnt & 3) { case 1: gSBox[i*2] = gMDS0[(P[P_01,b0] & 0xff) ^ M_b0(k0)]; gSBox[i*2+1] = gMDS1[(P[P_11,b1] & 0xff) ^ M_b1(k0)]; gSBox[i*2+0x200] = gMDS2[(P[P_21,b2] & 0xff) ^ M_b2(k0)]; gSBox[i*2+0x201] = gMDS3[(P[P_31,b3] & 0xff) ^ M_b3(k0)]; break; case 0: // 256 bits of key b0 = (P[P_04,b0] & 0xff) ^ M_b0(k3); b1 = (P[P_14,b1] & 0xff) ^ M_b1(k3); b2 = (P[P_24,b2] & 0xff) ^ M_b2(k3); b3 = (P[P_34,b3] & 0xff) ^ M_b3(k3); // fall through, having pre-processed b[0]..b[3] with k32[3] goto case 3; case 3: // 192 bits of key b0 = (P[P_03,b0] & 0xff) ^ M_b0(k2); b1 = (P[P_13,b1] & 0xff) ^ M_b1(k2); b2 = (P[P_23,b2] & 0xff) ^ M_b2(k2); b3 = (P[P_33,b3] & 0xff) ^ M_b3(k2); // fall through, having pre-processed b[0]..b[3] with k32[2] goto case 2; case 2: // 128 bits of key gSBox[i * 2] = gMDS0[(P[P_01, (P[P_02, b0] & 0xff) ^ M_b0(k1)] & 0xff) ^ M_b0(k0)]; gSBox[i*2+1] = gMDS1[(P[P_11,(P[P_12,b1] & 0xff) ^ M_b1(k1)] & 0xff) ^ M_b1(k0)]; gSBox[i*2+0x200] = gMDS2[(P[P_21,(P[P_22,b2] & 0xff) ^ M_b2(k1)] & 0xff) ^ M_b2(k0)]; gSBox[i * 2 + 0x201] = gMDS3[(P[P_31, (P[P_32, b3] & 0xff) ^ M_b3(k1)] & 0xff) ^ M_b3(k0)]; break; } } /* * the function exits having setup the gSBox with the * input key material. */ } /** * Encrypt the given input starting at the given offset and place * the result in the provided buffer starting at the given offset. * The input will be an exact multiple of our blocksize. * * encryptBlock uses the pre-calculated gSBox[] and subKey[] * arrays. */ private void EncryptBlock( byte[] src, int srcIndex, byte[] dst, int dstIndex) { var x0 = BytesTo32Bits(src, srcIndex) ^ gSubKeys[INPUT_WHITEN]; var x1 = BytesTo32Bits(src, srcIndex + 4) ^ gSubKeys[INPUT_WHITEN + 1]; var x2 = BytesTo32Bits(src, srcIndex + 8) ^ gSubKeys[INPUT_WHITEN + 2]; var x3 = BytesTo32Bits(src, srcIndex + 12) ^ gSubKeys[INPUT_WHITEN + 3]; var k = ROUND_SUBKEYS; int t0, t1; for (var r = 0; r < ROUNDS; r +=2) { t0 = Fe32_0(x0); t1 = Fe32_3(x1); x2 ^= t0 + t1 + gSubKeys[k++]; x2 = (int)((uint)x2 >>1) | x2 << 31; x3 = (x3 << 1 | (int) ((uint)x3 >> 31)) ^ (t0 + 2*t1 + gSubKeys[k++]); t0 = Fe32_0(x2); t1 = Fe32_3(x3); x0 ^= t0 + t1 + gSubKeys[k++]; x0 = (int) ((uint)x0 >>1) | x0 << 31; x1 = (x1 << 1 | (int)((uint)x1 >> 31)) ^ (t0 + 2*t1 + gSubKeys[k++]); } Bits32ToBytes(x2 ^ gSubKeys[OUTPUT_WHITEN], dst, dstIndex); Bits32ToBytes(x3 ^ gSubKeys[OUTPUT_WHITEN + 1], dst, dstIndex + 4); Bits32ToBytes(x0 ^ gSubKeys[OUTPUT_WHITEN + 2], dst, dstIndex + 8); Bits32ToBytes(x1 ^ gSubKeys[OUTPUT_WHITEN + 3], dst, dstIndex + 12); } /** * Decrypt the given input starting at the given offset and place * the result in the provided buffer starting at the given offset. * The input will be an exact multiple of our blocksize. */ private void DecryptBlock( byte[] src, int srcIndex, byte[] dst, int dstIndex) { var x2 = BytesTo32Bits(src, srcIndex) ^ gSubKeys[OUTPUT_WHITEN]; var x3 = BytesTo32Bits(src, srcIndex+4) ^ gSubKeys[OUTPUT_WHITEN + 1]; var x0 = BytesTo32Bits(src, srcIndex+8) ^ gSubKeys[OUTPUT_WHITEN + 2]; var x1 = BytesTo32Bits(src, srcIndex+12) ^ gSubKeys[OUTPUT_WHITEN + 3]; var k = ROUND_SUBKEYS + 2 * ROUNDS -1 ; int t0, t1; for (var r = 0; r< ROUNDS ; r +=2) { t0 = Fe32_0(x2); t1 = Fe32_3(x3); x1 ^= t0 + 2*t1 + gSubKeys[k--]; x0 = (x0 << 1 | (int)((uint) x0 >> 31)) ^ (t0 + t1 + gSubKeys[k--]); x1 = (int) ((uint)x1 >>1) | x1 << 31; t0 = Fe32_0(x0); t1 = Fe32_3(x1); x3 ^= t0 + 2*t1 + gSubKeys[k--]; x2 = (x2 << 1 | (int)((uint)x2 >> 31)) ^ (t0 + t1 + gSubKeys[k--]); x3 = (int)((uint)x3 >>1) | x3 << 31; } Bits32ToBytes(x0 ^ gSubKeys[INPUT_WHITEN], dst, dstIndex); Bits32ToBytes(x1 ^ gSubKeys[INPUT_WHITEN + 1], dst, dstIndex + 4); Bits32ToBytes(x2 ^ gSubKeys[INPUT_WHITEN + 2], dst, dstIndex + 8); Bits32ToBytes(x3 ^ gSubKeys[INPUT_WHITEN + 3], dst, dstIndex + 12); } /* * TODO: This can be optimised and made cleaner by combining * the functionality in this function and applying it appropriately * to the creation of the subkeys during key setup. */ private int F32(int x, int[] k32) { var b0 = M_b0(x); var b1 = M_b1(x); var b2 = M_b2(x); var b3 = M_b3(x); var k0 = k32[0]; var k1 = k32[1]; var k2 = k32[2]; var k3 = k32[3]; var result = 0; switch (k64Cnt & 3) { case 1: result = gMDS0[(P[P_01,b0] & 0xff) ^ M_b0(k0)] ^ gMDS1[(P[P_11,b1] & 0xff) ^ M_b1(k0)] ^ gMDS2[(P[P_21,b2] & 0xff) ^ M_b2(k0)] ^ gMDS3[(P[P_31,b3] & 0xff) ^ M_b3(k0)]; break; case 0: /* 256 bits of key */ b0 = (P[P_04,b0] & 0xff) ^ M_b0(k3); b1 = (P[P_14,b1] & 0xff) ^ M_b1(k3); b2 = (P[P_24,b2] & 0xff) ^ M_b2(k3); b3 = (P[P_34,b3] & 0xff) ^ M_b3(k3); goto case 3; case 3: b0 = (P[P_03,b0] & 0xff) ^ M_b0(k2); b1 = (P[P_13,b1] & 0xff) ^ M_b1(k2); b2 = (P[P_23,b2] & 0xff) ^ M_b2(k2); b3 = (P[P_33,b3] & 0xff) ^ M_b3(k2); goto case 2; case 2: result = gMDS0[(P[P_01,(P[P_02,b0]&0xff)^M_b0(k1)]&0xff)^M_b0(k0)] ^ gMDS1[(P[P_11,(P[P_12,b1]&0xff)^M_b1(k1)]&0xff)^M_b1(k0)] ^ gMDS2[(P[P_21,(P[P_22,b2]&0xff)^M_b2(k1)]&0xff)^M_b2(k0)] ^ gMDS3[(P[P_31,(P[P_32,b3]&0xff)^M_b3(k1)]&0xff)^M_b3(k0)]; break; } return result; } /** * Use (12, 8) Reed-Solomon code over GF(256) to produce * a key S-box 32-bit entity from 2 key material 32-bit * entities. * * @param k0 first 32-bit entity * @param k1 second 32-bit entity * @return Remainder polynomial Generated using RS code */ private int RS_MDS_Encode(int k0, int k1) { var r = k1; for (var i = 0 ; i < 4 ; i++) // shift 1 byte at a time { r = RS_rem(r); } r ^= k0; for (var i=0 ; i < 4 ; i++) { r = RS_rem(r); } return r; } /** * Reed-Solomon code parameters: (12,8) reversible code: * <p> * <pre> * G(x) = x^4 + (a+1/a)x^3 + ax^2 + (a+1/a)x + 1 * </pre> * where a = primitive root of field generator 0x14D * </p> */ private int RS_rem(int x) { var b = (int) (((uint)x >> 24) & 0xff); var g2 = ((b << 1) ^ ((b & 0x80) != 0 ? RS_GF_FDBK : 0)) & 0xff; var g3 = ( (int)((uint)b >> 1) ^ ((b & 0x01) != 0 ? (int)((uint)RS_GF_FDBK >> 1) : 0)) ^ g2 ; return ((x << 8) ^ (g3 << 24) ^ (g2 << 16) ^ (g3 << 8) ^ b); } private int LFSR1(int x) { return (x >> 1) ^ (((x & 0x01) != 0) ? GF256_FDBK_2 : 0); } private int LFSR2(int x) { return (x >> 2) ^ (((x & 0x02) != 0) ? GF256_FDBK_2 : 0) ^ (((x & 0x01) != 0) ? GF256_FDBK_4 : 0); } private int Mx_X(int x) { return x ^ LFSR2(x); } // 5B private int Mx_Y(int x) { return x ^ LFSR1(x) ^ LFSR2(x); } // EF private int M_b0(int x) { return x & 0xff; } private int M_b1(int x) { return (int)((uint)x >> 8) & 0xff; } private int M_b2(int x) { return (int)((uint)x >> 16) & 0xff; } private int M_b3(int x) { return (int)((uint)x >> 24) & 0xff; } private int Fe32_0(int x) { return gSBox[ 0x000 + 2*(x & 0xff) ] ^ gSBox[ 0x001 + 2*((int)((uint)x >> 8) & 0xff) ] ^ gSBox[ 0x200 + 2*((int)((uint)x >> 16) & 0xff) ] ^ gSBox[ 0x201 + 2*((int)((uint)x >> 24) & 0xff) ]; } private int Fe32_3(int x) { return gSBox[ 0x000 + 2*((int)((uint)x >> 24) & 0xff) ] ^ gSBox[ 0x001 + 2*(x & 0xff) ] ^ gSBox[ 0x200 + 2*((int)((uint)x >> 8) & 0xff) ] ^ gSBox[ 0x201 + 2*((int)((uint)x >> 16) & 0xff) ]; } private int BytesTo32Bits(byte[] b, int p) { return ((b[p] & 0xff) ) | ((b[p+1] & 0xff) << 8) | ((b[p+2] & 0xff) << 16) | ((b[p+3] & 0xff) << 24); } private void Bits32ToBytes(int inData, byte[] b, int offset) { b[offset] = (byte)inData; b[offset + 1] = (byte)(inData >> 8); b[offset + 2] = (byte)(inData >> 16); b[offset + 3] = (byte)(inData >> 24); } } }
namespace System.Web.Mvc.Test { using System; using System.Web.Routing; using System.Web.TestUtil; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; [TestClass] public class UrlHelperTest { [TestMethod] public void RequestContextProperty() { // Arrange RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData()); UrlHelper urlHelper = new UrlHelper(requestContext); // Assert Assert.AreEqual(requestContext, urlHelper.RequestContext); } [TestMethod] public void ConstructorWithNullRequestContextThrows() { // Assert ExceptionHelper.ExpectArgumentNullException( delegate { new UrlHelper(null); }, "requestContext"); } [TestMethod] public void ConstructorWithNullRouteCollectionThrows() { // Assert ExceptionHelper.ExpectArgumentNullException( delegate { new UrlHelper(GetRequestContext(), null); }, "routeCollection"); } [TestMethod] public void Action() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.Action("newaction"); // Assert Assert.AreEqual<string>(HtmlHelperTest.AppPathModifier + "/app/home/newaction", url); } [TestMethod] public void ActionWithControllerName() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.Action("newaction", "home2"); // Assert Assert.AreEqual<string>(HtmlHelperTest.AppPathModifier + "/app/home2/newaction", url); } [TestMethod] public void ActionWithControllerNameAndDictionary() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.Action("newaction", "home2", new RouteValueDictionary(new { id = "someid" })); // Assert Assert.AreEqual<string>(HtmlHelperTest.AppPathModifier + "/app/home2/newaction/someid", url); } [TestMethod] public void ActionWithControllerNameAndObjectProperties() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.Action("newaction", "home2", new { id = "someid" }); // Assert Assert.AreEqual<string>(HtmlHelperTest.AppPathModifier + "/app/home2/newaction/someid", url); } [TestMethod] public void ActionWithDictionary() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.Action("newaction", new RouteValueDictionary(new { Controller = "home2", id = "someid" })); // Assert Assert.AreEqual<string>(HtmlHelperTest.AppPathModifier + "/app/home2/newaction/someid", url); } [TestMethod] public void ActionWithNullActionName() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.Action(null); // Assert Assert.AreEqual(HtmlHelperTest.AppPathModifier + "/app/home/oldaction", url); } [TestMethod] public void ActionWithNullProtocol() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.Action("newaction", "home2", new { id = "someid" }, null /* protocol */); // Assert Assert.AreEqual<string>(HtmlHelperTest.AppPathModifier + "/app/home2/newaction/someid", url); } [TestMethod] public void ActionParameterOverridesObjectProperties() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.Action("newaction", new { Action = "action" }); // Assert Assert.AreEqual<string>(HtmlHelperTest.AppPathModifier + "/app/home/newaction", url); } [TestMethod] public void ActionWithObjectProperties() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.Action("newaction", new { Controller = "home2", id = "someid" }); // Assert Assert.AreEqual<string>(HtmlHelperTest.AppPathModifier + "/app/home2/newaction/someid", url); } [TestMethod] public void ActionWithProtocol() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.Action("newaction", "home2", new { id = "someid" }, "https"); // Assert Assert.AreEqual<string>("https://localhost" + HtmlHelperTest.AppPathModifier + "/app/home2/newaction/someid", url); } [TestMethod] public void ContentWithAbsolutePath() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.Content("/Content/Image.jpg"); // Assert Assert.AreEqual("/Content/Image.jpg", url); } [TestMethod] public void ContentWithAppRelativePath() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.Content("~/Content/Image.jpg"); // Assert Assert.AreEqual(HtmlHelperTest.AppPathModifier + "/app/Content/Image.jpg", url); } [TestMethod] public void ContentWithEmptyPathThrows() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act & Assert ExceptionHelper.ExpectArgumentExceptionNullOrEmpty( delegate() { urlHelper.Content(String.Empty); }, "contentPath"); } [TestMethod] public void ContentWithRelativePath() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.Content("Content/Image.jpg"); // Assert Assert.AreEqual("Content/Image.jpg", url); } [TestMethod] public void ContentWithExternalUrl() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.Content("http://www.asp.net/App_Themes/Standard/i/logo.png"); // Assert Assert.AreEqual("http://www.asp.net/App_Themes/Standard/i/logo.png", url); } [TestMethod] public void Encode() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string encodedUrl = urlHelper.Encode(@"SomeUrl /+\"); // Assert Assert.AreEqual(encodedUrl, "SomeUrl+%2f%2b%5c"); } [TestMethod] public void RouteUrlCanUseNamedRouteWithoutSpecifyingDefaults() { // DevDiv 217072: Non-mvc specific helpers should not give default values for controller and action // Arrange UrlHelper urlHelper = GetUrlHelper(); urlHelper.RouteCollection.MapRoute("MyRouteName", "any/url", new { controller = "Charlie" }); // Act string result = urlHelper.RouteUrl("MyRouteName"); // Assert Assert.AreEqual(HtmlHelperTest.AppPathModifier + "/app/any/url", result); } [TestMethod] public void RouteUrlWithDictionary() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.RouteUrl(new RouteValueDictionary(new { Action = "newaction", Controller = "home2", id = "someid" })); // Assert Assert.AreEqual<string>(HtmlHelperTest.AppPathModifier + "/app/home2/newaction/someid", url); } [TestMethod] public void RouteUrlWithEmptyHostName() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.RouteUrl("namedroute", new RouteValueDictionary(new { Action = "newaction", Controller = "home2", id = "someid" }), "http", String.Empty /* hostName */); // Assert Assert.AreEqual<string>("http://localhost" + HtmlHelperTest.AppPathModifier + "/app/named/home2/newaction/someid", url); } [TestMethod] public void RouteUrlWithEmptyProtocol() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.RouteUrl("namedroute", new RouteValueDictionary(new { Action = "newaction", Controller = "home2", id = "someid" }), String.Empty /* protocol */, "foo.bar.com"); // Assert Assert.AreEqual<string>("http://foo.bar.com" + HtmlHelperTest.AppPathModifier + "/app/named/home2/newaction/someid", url); } [TestMethod] public void RouteUrlWithNullProtocol() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.RouteUrl("namedroute", new RouteValueDictionary(new { Action = "newaction", Controller = "home2", id = "someid" }), null /* protocol */, "foo.bar.com"); // Assert Assert.AreEqual<string>("http://foo.bar.com" + HtmlHelperTest.AppPathModifier + "/app/named/home2/newaction/someid", url); } [TestMethod] public void RouteUrlWithNullProtocolAndNullHostName() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.RouteUrl("namedroute", new RouteValueDictionary(new { Action = "newaction", Controller = "home2", id = "someid" }), null /* protocol */, null /* hostName */); // Assert Assert.AreEqual<string>(HtmlHelperTest.AppPathModifier + "/app/named/home2/newaction/someid", url); } [TestMethod] public void RouteUrlWithObjectProperties() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.RouteUrl(new { Action = "newaction", Controller = "home2", id = "someid" }); // Assert Assert.AreEqual<string>(HtmlHelperTest.AppPathModifier + "/app/home2/newaction/someid", url); } [TestMethod] public void RouteUrlWithProtocol() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.RouteUrl("namedroute", new { Action = "newaction", Controller = "home2", id = "someid" }, "https"); // Assert Assert.AreEqual<string>("https://localhost" + HtmlHelperTest.AppPathModifier + "/app/named/home2/newaction/someid", url); } [TestMethod] public void RouteUrlWithRouteNameAndDefaults() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.RouteUrl("namedroute"); // Assert Assert.AreEqual<string>(HtmlHelperTest.AppPathModifier + "/app/named/home/oldaction", url); } [TestMethod] public void RouteUrlWithRouteNameAndDictionary() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.RouteUrl("namedroute", new RouteValueDictionary(new { Action = "newaction", Controller = "home2", id = "someid" })); // Assert Assert.AreEqual<string>(HtmlHelperTest.AppPathModifier + "/app/named/home2/newaction/someid", url); } [TestMethod] public void RouteUrlWithRouteNameAndObjectProperties() { // Arrange UrlHelper urlHelper = GetUrlHelper(); // Act string url = urlHelper.RouteUrl("namedroute", new { Action = "newaction", Controller = "home2", id = "someid" }); // Assert Assert.AreEqual<string>(HtmlHelperTest.AppPathModifier + "/app/named/home2/newaction/someid", url); } [TestMethod] public void UrlGenerationDoesNotChangeProvidedDictionary() { // Arrange UrlHelper urlHelper = GetUrlHelper(); RouteValueDictionary valuesDictionary = new RouteValueDictionary(); // Act urlHelper.Action("actionName", valuesDictionary); // Assert Assert.AreEqual(0, valuesDictionary.Count); Assert.IsFalse(valuesDictionary.ContainsKey("action")); } private static RequestContext GetRequestContext() { HttpContextBase httpcontext = HtmlHelperTest.GetHttpContext("/app/", null, null); RouteData rd = new RouteData(); return new RequestContext(httpcontext, rd); } private static UrlHelper GetUrlHelper() { HttpContextBase httpcontext = HtmlHelperTest.GetHttpContext("/app/", null, null); RouteCollection rt = new RouteCollection(); rt.Add(new Route("{controller}/{action}/{id}", null) { Defaults = new RouteValueDictionary(new { id = "defaultid" }) }); rt.Add("namedroute", new Route("named/{controller}/{action}/{id}", null) { Defaults = new RouteValueDictionary(new { id = "defaultid" }) }); RouteData rd = new RouteData(); rd.Values.Add("controller", "home"); rd.Values.Add("action", "oldaction"); UrlHelper urlHelper = new UrlHelper(new RequestContext(httpcontext, rd), rt); return urlHelper; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using Validation; namespace System.Collections.Immutable { /// <content> /// Contains the inner Builder class. /// </content> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public sealed partial class ImmutableSortedSet<T> { /// <summary> /// A sorted set that mutates with little or no memory allocations, /// can produce and/or build on immutable sorted set instances very efficiently. /// </summary> /// <remarks> /// <para> /// While <see cref="ImmutableSortedSet&lt;T&gt;.Union"/> and other bulk change methods /// already provide fast bulk change operations on the collection, this class allows /// multiple combinations of changes to be made to a set with equal efficiency. /// </para> /// <para> /// Instance members of this class are <em>not</em> thread-safe. /// </para> /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")] [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableSortedSet<>.Builder.DebuggerProxy))] public sealed class Builder : ISortKeyCollection<T>, IReadOnlyCollection<T>, ISet<T>, ICollection { /// <summary> /// The root of the binary tree that stores the collection. Contents are typically not entirely frozen. /// </summary> private ImmutableSortedSet<T>.Node root = ImmutableSortedSet<T>.Node.EmptyNode; /// <summary> /// The comparer to use for sorting the set. /// </summary> private IComparer<T> comparer = Comparer<T>.Default; /// <summary> /// Caches an immutable instance that represents the current state of the collection. /// </summary> /// <value>Null if no immutable view has been created for the current version.</value> private ImmutableSortedSet<T> immutable; /// <summary> /// A number that increments every time the builder changes its contents. /// </summary> private int version; /// <summary> /// The object callers may use to synchronize access to this collection. /// </summary> private object syncRoot; /// <summary> /// Initializes a new instance of the <see cref="Builder"/> class. /// </summary> /// <param name="set">A set to act as the basis for a new set.</param> internal Builder(ImmutableSortedSet<T> set) { Requires.NotNull(set, "set"); this.root = set.root; this.comparer = set.KeyComparer; this.immutable = set; } #region ISet<T> Properties /// <summary> /// Gets the number of elements in this set. /// </summary> public int Count { get { return this.Root.Count; } } /// <summary> /// Gets a value indicating whether this instance is read-only. /// </summary> /// <value>Always <c>false</c>.</value> bool ICollection<T>.IsReadOnly { get { return false; } } #endregion /// <summary> /// Gets the element of the set at the given index. /// </summary> /// <param name="index">The 0-based index of the element in the set to return.</param> /// <returns>The element at the given position.</returns> /// <remarks> /// No index setter is offered because the element being replaced may not sort /// to the same position in the sorted collection as the replacing element. /// </remarks> public T this[int index] { get { return this.root[index]; } } /// <summary> /// Gets the maximum value in the collection, as defined by the comparer. /// </summary> /// <value>The maximum value in the set.</value> public T Max { get { return this.root.Max; } } /// <summary> /// Gets the minimum value in the collection, as defined by the comparer. /// </summary> /// <value>The minimum value in the set.</value> public T Min { get { return this.root.Min; } } /// <summary> /// Gets or sets the System.Collections.Generic.IComparer&lt;T&gt; object that is used to determine equality for the values in the System.Collections.Generic.SortedSet&lt;T&gt;. /// </summary> /// <value>The comparer that is used to determine equality for the values in the set.</value> /// <remarks> /// When changing the comparer in such a way as would introduce collisions, the conflicting elements are dropped, /// leaving only one of each matching pair in the collection. /// </remarks> public IComparer<T> KeyComparer { get { return this.comparer; } set { Requires.NotNull(value, "value"); if (value != this.comparer) { var newRoot = Node.EmptyNode; foreach (T item in this) { bool mutated; newRoot = newRoot.Add(item, value, out mutated); } this.immutable = null; this.comparer = value; this.Root = newRoot; } } } /// <summary> /// Gets the current version of the contents of this builder. /// </summary> internal int Version { get { return this.version; } } /// <summary> /// Gets or sets the root node that represents the data in this collection. /// </summary> private Node Root { get { return this.root; } set { // We *always* increment the version number because some mutations // may not create a new value of root, although the existing root // instance may have mutated. this.version++; if (this.root != value) { this.root = value; // Clear any cached value for the immutable view since it is now invalidated. this.immutable = null; } } } #region ISet<T> Methods /// <summary> /// Adds an element to the current set and returns a value to indicate if the /// element was successfully added. /// </summary> /// <param name="item">The element to add to the set.</param> /// <returns>true if the element is added to the set; false if the element is already in the set.</returns> public bool Add(T item) { bool mutated; this.Root = this.Root.Add(item, this.comparer, out mutated); return mutated; } /// <summary> /// Removes all elements in the specified collection from the current set. /// </summary> /// <param name="other">The collection of items to remove from the set.</param> public void ExceptWith(IEnumerable<T> other) { Requires.NotNull(other, "other"); foreach (T item in other) { bool mutated; this.Root = this.Root.Remove(item, this.comparer, out mutated); } } /// <summary> /// Modifies the current set so that it contains only elements that are also in a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> public void IntersectWith(IEnumerable<T> other) { Requires.NotNull(other, "other"); var result = ImmutableSortedSet<T>.Node.EmptyNode; foreach (T item in other) { if (this.Contains(item)) { bool mutated; result = result.Add(item, this.comparer, out mutated); } } this.Root = result; } /// <summary> /// Determines whether the current set is a proper (strict) subset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a correct subset of other; otherwise, false.</returns> public bool IsProperSubsetOf(IEnumerable<T> other) { return this.ToImmutable().IsProperSubsetOf(other); } /// <summary> /// Determines whether the current set is a proper (strict) superset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a superset of other; otherwise, false.</returns> public bool IsProperSupersetOf(IEnumerable<T> other) { return this.ToImmutable().IsProperSupersetOf(other); } /// <summary> /// Determines whether the current set is a subset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a subset of other; otherwise, false.</returns> public bool IsSubsetOf(IEnumerable<T> other) { return this.ToImmutable().IsSubsetOf(other); } /// <summary> /// Determines whether the current set is a superset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a superset of other; otherwise, false.</returns> public bool IsSupersetOf(IEnumerable<T> other) { return this.ToImmutable().IsSupersetOf(other); } /// <summary> /// Determines whether the current set overlaps with the specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set and other share at least one common element; otherwise, false.</returns> public bool Overlaps(IEnumerable<T> other) { return this.ToImmutable().Overlaps(other); } /// <summary> /// Determines whether the current set and the specified collection contain the same elements. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is equal to other; otherwise, false.</returns> public bool SetEquals(IEnumerable<T> other) { return this.ToImmutable().SetEquals(other); } /// <summary> /// Modifies the current set so that it contains only elements that are present either in the current set or in the specified collection, but not both. /// </summary> /// <param name="other">The collection to compare to the current set.</param> public void SymmetricExceptWith(IEnumerable<T> other) { this.Root = this.ToImmutable().SymmetricExcept(other).root; } /// <summary> /// Modifies the current set so that it contains all elements that are present in both the current set and in the specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> public void UnionWith(IEnumerable<T> other) { Requires.NotNull(other, "other"); foreach (T item in other) { bool mutated; this.Root = this.Root.Add(item, this.comparer, out mutated); } } /// <summary> /// Adds an element to the current set and returns a value to indicate if the /// element was successfully added. /// </summary> /// <param name="item">The element to add to the set.</param> void ICollection<T>.Add(T item) { this.Add(item); } /// <summary> /// Removes all elements from this set. /// </summary> public void Clear() { this.Root = ImmutableSortedSet<T>.Node.EmptyNode; } /// <summary> /// Determines whether the set contains a specific value. /// </summary> /// <param name="item">The object to locate in the set.</param> /// <returns>true if item is found in the set; false otherwise.</returns> public bool Contains(T item) { return this.Root.Contains(item, this.comparer); } /// <summary> /// See <see cref="ICollection&lt;T&gt;"/> /// </summary> void ICollection<T>.CopyTo(T[] array, int arrayIndex) { this.root.CopyTo(array, arrayIndex); } /// <summary> /// Removes the first occurrence of a specific object from the set. /// </summary> /// <param name="item">The object to remove from the set.</param> /// <returns><c>true</c> if the item was removed from the set; <c>false</c> if the item was not found in the set.</returns> public bool Remove(T item) { bool mutated; this.Root = this.Root.Remove(item, this.comparer, out mutated); return mutated; } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>A enumerator that can be used to iterate through the collection.</returns> public ImmutableSortedSet<T>.Enumerator GetEnumerator() { return this.Root.GetEnumerator(this); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>A enumerator that can be used to iterate through the collection.</returns> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.Root.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>A enumerator that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion /// <summary> /// Returns an System.Collections.Generic.IEnumerable&lt;T&gt; that iterates over this /// collection in reverse order. /// </summary> /// <returns> /// An enumerator that iterates over the System.Collections.Generic.SortedSet&lt;T&gt; /// in reverse order. /// </returns> [Pure] public IEnumerable<T> Reverse() { return new ReverseEnumerable(this.root); } /// <summary> /// Creates an immutable sorted set based on the contents of this instance. /// </summary> /// <returns>An immutable set.</returns> /// <remarks> /// This method is an O(n) operation, and approaches O(1) time as the number of /// actual mutations to the set since the last call to this method approaches 0. /// </remarks> public ImmutableSortedSet<T> ToImmutable() { // Creating an instance of ImmutableSortedSet<T> with our root node automatically freezes our tree, // ensuring that the returned instance is immutable. Any further mutations made to this builder // will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked. if (this.immutable == null) { this.immutable = ImmutableSortedSet<T>.Wrap(this.Root, this.comparer); } return this.immutable; } #region ICollection members /// <summary> /// Copies the elements of the <see cref="T:System.Collections.ICollection" /> to an <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection" />. The <see cref="T:System.Array" /> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array" /> at which copying begins.</param> /// <exception cref="System.NotImplementedException"></exception> void ICollection.CopyTo(Array array, int arrayIndex) { this.Root.CopyTo(array, arrayIndex); } /// <summary> /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection" /> is synchronized (thread safe). /// </summary> /// <returns>true if access to the <see cref="T:System.Collections.ICollection" /> is synchronized (thread safe); otherwise, false.</returns> /// <exception cref="System.NotImplementedException"></exception> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized { get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection" />. /// </summary> /// <returns>An object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection" />.</returns> /// <exception cref="System.NotImplementedException"></exception> [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { if (this.syncRoot == null) { Threading.Interlocked.CompareExchange<Object>(ref this.syncRoot, new Object(), null); } return this.syncRoot; } } #endregion /// <summary> /// A simple view of the immutable collection that the debugger can show to the developer. /// </summary> [ExcludeFromCodeCoverage] private class DebuggerProxy { /// <summary> /// The collection to be enumerated. /// </summary> private readonly ImmutableSortedSet<T>.Node set; /// <summary> /// The simple view of the collection. /// </summary> private T[] contents; /// <summary> /// Initializes a new instance of the <see cref="DebuggerProxy"/> class. /// </summary> /// <param name="builder">The collection to display in the debugger</param> public DebuggerProxy(ImmutableSortedSet<T>.Builder builder) { Requires.NotNull(builder, "builder"); this.set = builder.Root; } /// <summary> /// Gets a simple debugger-viewable collection. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Contents { get { if (this.contents == null) { this.contents = this.set.ToArray(this.set.Count); } return this.contents; } } } } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation.Provider; using System.Management.Automation.Runspaces; using System.Text; using Dbg = System.Management.Automation; #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings #pragma warning disable 56500 namespace System.Management.Automation { /// <summary> /// Holds the state of a PowerShell session /// </summary> internal sealed partial class SessionStateInternal { /// <summary> /// A collection of the providers. Any provider in this collection can /// have drives in any scope in session state. /// </summary> internal Dictionary<string, List<ProviderInfo>> Providers { get { if (this == ExecutionContext.TopLevelSessionState) return _providers; return ExecutionContext.TopLevelSessionState.Providers; } } private Dictionary<string, List<ProviderInfo>> _providers = new Dictionary<string, List<ProviderInfo>>( SessionStateConstants.DefaultDictionaryCapacity, StringComparer.OrdinalIgnoreCase); /// <summary> /// Stores the current working drive for each provider. This /// allows for retrieving the current working directory for each /// individual provider. /// </summary> internal Dictionary<ProviderInfo, PSDriveInfo> ProvidersCurrentWorkingDrive { get { if (this == ExecutionContext.TopLevelSessionState) return _providersCurrentWorkingDrive; return ExecutionContext.TopLevelSessionState.ProvidersCurrentWorkingDrive; } } private Dictionary<ProviderInfo, PSDriveInfo> _providersCurrentWorkingDrive = new Dictionary<ProviderInfo, PSDriveInfo>(); private bool _providersInitialized = false; /// <summary> /// Gets called by the RunspaceConfiguration when a PSSnapin gets added or removed. /// </summary> /// internal void UpdateProviders() { // This should only be called from Update() on a runspace configuration q.e.d. runspace configuration // should never be null when this gets called... if (this.ExecutionContext.RunspaceConfiguration == null) throw PSTraceSource.NewInvalidOperationException(); if (this == ExecutionContext.TopLevelSessionState && !_providersInitialized) { foreach (ProviderConfigurationEntry providerConfig in this.ExecutionContext.RunspaceConfiguration.Providers) { AddProvider(providerConfig); } _providersInitialized = true; return; } foreach (ProviderConfigurationEntry providerConfig in this.ExecutionContext.RunspaceConfiguration.Providers.UpdateList) { switch (providerConfig.Action) { case UpdateAction.Add: AddProvider(providerConfig); break; case UpdateAction.Remove: RemoveProvider(providerConfig); break; default: break; } } } /// <summary> /// Entrypoint used by to add a provider to the current session state /// based on a SessionStateProviderEntry. /// </summary> /// <param name="providerEntry"></param> internal void AddSessionStateEntry(SessionStateProviderEntry providerEntry) { ProviderInfo provider = AddProvider(providerEntry.ImplementingType, providerEntry.Name, providerEntry.HelpFileName, providerEntry.PSSnapIn, providerEntry.Module ); } /// <summary> /// Internal method used by RunspaceConfig for updatting providers. /// </summary> /// <param name="providerConfig"></param> private ProviderInfo AddProvider(ProviderConfigurationEntry providerConfig) { return AddProvider(providerConfig.ImplementingType, providerConfig.Name, providerConfig.HelpFileName, providerConfig.PSSnapIn, null ); } private ProviderInfo AddProvider(Type implementingType, string name, string helpFileName, PSSnapInInfo psSnapIn, PSModuleInfo module) { ProviderInfo provider = null; try { provider = new ProviderInfo( new SessionState(this), implementingType, name, helpFileName, psSnapIn); provider.SetModule(module); NewProvider(provider); // Log the provider start event MshLog.LogProviderLifecycleEvent( this.ExecutionContext, provider.Name, ProviderState.Started); } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { throw; } catch (ActionPreferenceStopException) { throw; } catch (SessionStateException sessionStateException) { if (sessionStateException.GetType() == typeof(SessionStateException)) { throw; } else { // NTRAID#Windows OS Bugs-1009281-2004/02/11-JeffJon this.ExecutionContext.ReportEngineStartupError(sessionStateException); } } catch (Exception e) // Catch-all OK, 3rd party callout { CommandProcessorBase.CheckForSevereException(e); // NTRAID#Windows OS Bugs-1009281-2004/02/11-JeffJon this.ExecutionContext.ReportEngineStartupError(e); } return provider; } /// <summary> /// Determines the appropriate provider for the drive and then calls the NewDrive /// method of that provider. /// </summary> /// /// <param name="drive"> /// The drive to have the provider verify. /// </param> /// /// <param name="context"> /// The command context under which the drive is being added. /// </param> /// /// <param name="resolvePathIfPossible"> /// If true, the drive root will be resolved as an MSH path before verifying with /// the provider. If false, the path is assumed to be a provider-internal path. /// </param> /// /// <returns> /// The instance of the drive to be added as approved by the provider. /// </returns> /// /// <exception cref="NotSupportedException"> /// If the provider is not a DriveCmdletProvider. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// The provider for the <paramref name="drive"/> could not be found. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider throws an exception while validating the drive. /// </exception> /// private PSDriveInfo ValidateDriveWithProvider(PSDriveInfo drive, CmdletProviderContext context, bool resolvePathIfPossible) { Dbg.Diagnostics.Assert( drive != null, "drive should have been validated by the caller"); DriveCmdletProvider namespaceProvider = GetDriveProviderInstance(drive.Provider); return ValidateDriveWithProvider(namespaceProvider, drive, context, resolvePathIfPossible); } private PSDriveInfo ValidateDriveWithProvider( DriveCmdletProvider driveProvider, PSDriveInfo drive, CmdletProviderContext context, bool resolvePathIfPossible) { Dbg.Diagnostics.Assert( drive != null, "drive should have been validated by the caller"); Dbg.Diagnostics.Assert( driveProvider != null, "driveProvider should have been validated by the caller"); // Mark the drive as being created so that the provider can modify the // root if necessary drive.DriveBeingCreated = true; // Only try to resolve the root as an MSH path if there is a current drive. if (CurrentDrive != null && resolvePathIfPossible) { string newRoot = GetProviderRootFromSpecifiedRoot(drive.Root, drive.Provider); if (newRoot != null) { drive.SetRoot(newRoot); } } PSDriveInfo result = null; try { result = driveProvider.NewDrive(drive, context); } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { throw; } catch (ActionPreferenceStopException) { throw; } catch (Exception e) // Catch-all OK, 3rd party callout { CommandProcessorBase.CheckForSevereException(e); ProviderInvocationException pie = NewProviderInvocationException( "NewDriveProviderException", SessionStateStrings.NewDriveProviderException, driveProvider.ProviderInfo, drive.Root, e); context.WriteError( new ErrorRecord( pie.ErrorRecord, pie)); } finally { drive.DriveBeingCreated = false; } return result; } // ValidateDriveWithProvider /// <summary> /// Gets an instance of a provider given the provider ID. /// </summary> /// /// <param name="providerId"> /// The identifier for the provider to return an instance of. /// </param> /// /// <returns> /// An instance of the specified provider. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="providerId"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="providerId"/> refers to a provider that doesn't exist or /// the name passed matched multiple providers. /// </exception> /// internal Provider.CmdletProvider GetProviderInstance(string providerId) { if (providerId == null) { throw PSTraceSource.NewArgumentNullException("providerId"); } ProviderInfo provider = GetSingleProvider(providerId); return GetProviderInstance(provider); } // GetProviderInstance /// <summary> /// Gets an instance of a provider given the provider information. /// </summary> /// /// <param name="provider"> /// The provider to return an instance of. /// </param> /// /// <returns> /// An instance of the specified provider. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="provider"/> is null. /// </exception> /// internal Provider.CmdletProvider GetProviderInstance(ProviderInfo provider) { if (provider == null) { throw PSTraceSource.NewArgumentNullException("provider"); } return provider.CreateInstance(); } // GetProviderInstance /// <summary> /// Creates an exception for the case where the provider name matched multiple providers. /// </summary> /// /// <param name="name"> /// The name of the provider. /// </param> /// /// <param name="matchingProviders"> /// The ProviderInfo of the possible matches. /// </param> /// /// <returns> /// An exception representing the error with a message stating which providers are possible matches. /// </returns> /// internal static ProviderNameAmbiguousException NewAmbiguousProviderName(string name, Collection<ProviderInfo> matchingProviders) { string possibleMatches = GetPossibleMatches(matchingProviders); ProviderNameAmbiguousException e = new ProviderNameAmbiguousException( name, "ProviderNameAmbiguous", SessionStateStrings.ProviderNameAmbiguous, matchingProviders, possibleMatches); return e; } private static string GetPossibleMatches(Collection<ProviderInfo> matchingProviders) { StringBuilder possibleMatches = new StringBuilder(); foreach (ProviderInfo matchingProvider in matchingProviders) { possibleMatches.Append(" "); possibleMatches.Append(matchingProvider.FullName); } return possibleMatches.ToString(); } /// <summary> /// Gets an instance of an DriveCmdletProvider given the provider ID. /// </summary> /// /// <param name="providerId"> /// The provider ID of the provider to get an instance of. /// </param> /// /// <returns> /// An instance of a DriveCmdletProvider for the specified provider ID. /// </returns> /// /// <exception cref="ArgumentNullException"> /// if <paramref name="providerId"/> is null. /// </exception> /// /// <exception cref="NotSupportedException"> /// if the <paramref name="providerId"/> is not for a provider /// that is derived from NavigationCmdletProvider. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="providerId"/> refers to a provider that doesn't exist. /// </exception> /// internal DriveCmdletProvider GetDriveProviderInstance(string providerId) { if (providerId == null) { throw PSTraceSource.NewArgumentNullException("providerId"); } DriveCmdletProvider driveCmdletProvider = GetProviderInstance(providerId) as DriveCmdletProvider; if (driveCmdletProvider == null) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.DriveCmdletProvider_NotSupported); } return driveCmdletProvider; } // GetDriveProviderInstance /// <summary> /// Gets an instance of an DriveCmdletProvider given the provider information. /// </summary> /// /// <param name="provider"> /// The provider to get an instance of. /// </param> /// /// <returns> /// An instance of a DriveCmdletProvider for the specified provider. /// </returns> /// /// <exception cref="ArgumentNullException"> /// if <paramref name="provider"/> is null. /// </exception> /// /// <exception cref="NotSupportedException"> /// if the <paramref name="provider"/> is not for a provider /// that is derived from NavigationCmdletProvider. /// </exception> /// internal DriveCmdletProvider GetDriveProviderInstance(ProviderInfo provider) { if (provider == null) { throw PSTraceSource.NewArgumentNullException("provider"); } DriveCmdletProvider driveCmdletProvider = GetProviderInstance(provider) as DriveCmdletProvider; if (driveCmdletProvider == null) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.DriveCmdletProvider_NotSupported); } return driveCmdletProvider; } // GetDriveProviderInstance /// <summary> /// Gets an instance of an DriveCmdletProvider given the provider ID. /// </summary> /// /// <param name="providerInstance"> /// The instance of the provider to use. /// </param> /// /// <returns> /// An instance of a DriveCmdletProvider for the specified provider ID. /// </returns> /// /// <exception cref="ArgumentNullException"> /// if <paramref name="providerInstance"/> is null. /// </exception> /// /// <exception cref="NotSupportedException"> /// if the <paramref name="providerInstance"/> is not for a provider /// that is derived from DriveCmdletProvider. /// </exception> /// private static DriveCmdletProvider GetDriveProviderInstance(CmdletProvider providerInstance) { if (providerInstance == null) { throw PSTraceSource.NewArgumentNullException("providerInstance"); } DriveCmdletProvider driveCmdletProvider = providerInstance as DriveCmdletProvider; if (driveCmdletProvider == null) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.DriveCmdletProvider_NotSupported); } return driveCmdletProvider; } // GetDriveProviderInstance /// <summary> /// Gets an instance of an ItemCmdletProvider given the provider ID. /// </summary> /// /// <param name="providerId"> /// The provider ID of the provider to get an instance of. /// </param> /// /// <returns> /// An instance of a ItemCmdletProvider for the specified provider ID. /// </returns> /// /// <exception cref="ArgumentNullException"> /// if <paramref name="providerId"/> is null. /// </exception> /// /// <exception cref="NotSupportedException"> /// if the <paramref name="providerId"/> is not for a provider /// that is derived from NavigationCmdletProvider. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="providerId"/> refers to a provider that doesn't exist. /// </exception> /// internal ItemCmdletProvider GetItemProviderInstance(string providerId) { if (providerId == null) { throw PSTraceSource.NewArgumentNullException("providerId"); } ItemCmdletProvider itemCmdletProvider = GetProviderInstance(providerId) as ItemCmdletProvider; if (itemCmdletProvider == null) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.ItemCmdletProvider_NotSupported); } return itemCmdletProvider; } // GetItemProviderInstance /// <summary> /// Gets an instance of an ItemCmdletProvider given the provider. /// </summary> /// /// <param name="provider"> /// The provider to get an instance of. /// </param> /// /// <returns> /// An instance of a ItemCmdletProvider for the specified provider. /// </returns> /// /// <exception cref="ArgumentNullException"> /// if <paramref name="provider"/> is null. /// </exception> /// /// <exception cref="NotSupportedException"> /// if the <paramref name="provider"/> is not for a provider /// that is derived from NavigationCmdletProvider. /// </exception> /// internal ItemCmdletProvider GetItemProviderInstance(ProviderInfo provider) { if (provider == null) { throw PSTraceSource.NewArgumentNullException("provider"); } ItemCmdletProvider itemCmdletProvider = GetProviderInstance(provider) as ItemCmdletProvider; if (itemCmdletProvider == null) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.ItemCmdletProvider_NotSupported); } return itemCmdletProvider; } // GetItemProviderInstance /// <summary> /// Gets an instance of an ItemCmdletProvider given the provider ID. /// </summary> /// /// <param name="providerInstance"> /// The instance of the provider to use. /// </param> /// /// <returns> /// An instance of a ItemCmdletProvider for the specified provider ID. /// </returns> /// /// <exception cref="ArgumentNullException"> /// if <paramref name="providerInstance"/> is null. /// </exception> /// /// <exception cref="NotSupportedException"> /// if the <paramref name="providerInstance"/> is not for a provider /// that is derived from ItemCmdletProvider. /// </exception> /// private static ItemCmdletProvider GetItemProviderInstance(CmdletProvider providerInstance) { if (providerInstance == null) { throw PSTraceSource.NewArgumentNullException("providerInstance"); } ItemCmdletProvider itemCmdletProvider = providerInstance as ItemCmdletProvider; if (itemCmdletProvider == null) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.ItemCmdletProvider_NotSupported); } return itemCmdletProvider; } // GetItemProviderInstance /// <summary> /// Gets an instance of an ContainerCmdletProvider given the provider ID. /// </summary> /// /// <param name="providerId"> /// The provider ID of the provider to get an instance of. /// </param> /// /// <returns> /// An instance of a ContainerCmdletProvider for the specified provider ID. /// </returns> /// /// <exception cref="ArgumentNullException"> /// if <paramref name="providerId"/> is null. /// </exception> /// /// <exception cref="NotSupportedException"> /// if the <paramref name="providerId"/> is not for a provider /// that is derived from NavigationCmdletProvider. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="providerId"/> refers to a provider that doesn't exist. /// </exception> /// internal ContainerCmdletProvider GetContainerProviderInstance(string providerId) { if (providerId == null) { throw PSTraceSource.NewArgumentNullException("providerId"); } ContainerCmdletProvider containerCmdletProvider = GetProviderInstance(providerId) as ContainerCmdletProvider; if (containerCmdletProvider == null) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.ContainerCmdletProvider_NotSupported); } return containerCmdletProvider; } // GetContainerProviderInstance /// <summary> /// Gets an instance of an ContainerCmdletProvider given the provider. /// </summary> /// /// <param name="provider"> /// The provider to get an instance of. /// </param> /// /// <returns> /// An instance of a ContainerCmdletProvider for the specified provider. /// </returns> /// /// <exception cref="ArgumentNullException"> /// if <paramref name="provider"/> is null. /// </exception> /// /// <exception cref="NotSupportedException"> /// if the <paramref name="provider"/> is not for a provider /// that is derived from NavigationCmdletProvider. /// </exception> /// internal ContainerCmdletProvider GetContainerProviderInstance(ProviderInfo provider) { if (provider == null) { throw PSTraceSource.NewArgumentNullException("provider"); } ContainerCmdletProvider containerCmdletProvider = GetProviderInstance(provider) as ContainerCmdletProvider; if (containerCmdletProvider == null) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.ContainerCmdletProvider_NotSupported); } return containerCmdletProvider; } // GetContainerProviderInstance /// <summary> /// Gets an instance of an ContainerCmdletProvider given the provider ID. /// </summary> /// /// <param name="providerInstance"> /// The instance of the provider to use. /// </param> /// /// <returns> /// An instance of a ContainerCmdletProvider for the specified provider ID. /// </returns> /// /// <exception cref="ArgumentNullException"> /// if <paramref name="providerInstance"/> is null. /// </exception> /// /// <exception cref="NotSupportedException"> /// if the <paramref name="providerInstance"/> is not for a provider /// that is derived from ContainerCmdletProvider. /// </exception> /// private static ContainerCmdletProvider GetContainerProviderInstance(CmdletProvider providerInstance) { if (providerInstance == null) { throw PSTraceSource.NewArgumentNullException("providerInstance"); } ContainerCmdletProvider containerCmdletProvider = providerInstance as ContainerCmdletProvider; if (containerCmdletProvider == null) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.ContainerCmdletProvider_NotSupported); } return containerCmdletProvider; } // GetContainerProviderInstance /// <summary> /// Gets an instance of an NavigationCmdletProvider given the provider. /// </summary> /// /// <param name="provider"> /// The provider to get an instance of. /// </param> /// /// <returns> /// An instance of a NavigationCmdletProvider for the specified provider ID. /// </returns> /// /// <exception cref="ArgumentNullException"> /// if <paramref name="provider"/> is null. /// </exception> /// /// <exception cref="NotSupportedException"> /// if the <paramref name="provider"/> is not for a provider /// that is derived from NavigationCmdletProvider. /// </exception> /// internal NavigationCmdletProvider GetNavigationProviderInstance(ProviderInfo provider) { if (provider == null) { throw PSTraceSource.NewArgumentNullException("provider"); } NavigationCmdletProvider navigationCmdletProvider = GetProviderInstance(provider) as NavigationCmdletProvider; if (navigationCmdletProvider == null) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.NavigationCmdletProvider_NotSupported); } return navigationCmdletProvider; } // GetNavigationProviderInstance /// <summary> /// Gets an instance of an NavigationCmdletProvider given the provider ID. /// </summary> /// /// <param name="providerInstance"> /// The instance of the provider to use. /// </param> /// /// <param name="acceptNonContainerProviders"> /// Specify True if the method should just return the Path if the /// provider doesn't support container overloads. /// </param> /// /// <returns> /// An instance of a NavigationCmdletProvider for the specified provider ID. /// </returns> /// /// <exception cref="ArgumentNullException"> /// if <paramref name="providerInstance"/> is null. /// </exception> /// /// <exception cref="NotSupportedException"> /// if the <paramref name="providerInstance"/> is not for a provider /// that is derived from NavigationCmdletProvider. /// </exception> /// private static NavigationCmdletProvider GetNavigationProviderInstance(CmdletProvider providerInstance, bool acceptNonContainerProviders) { if (providerInstance == null) { throw PSTraceSource.NewArgumentNullException("providerInstance"); } NavigationCmdletProvider navigationCmdletProvider = providerInstance as NavigationCmdletProvider; if ((navigationCmdletProvider == null) && (!acceptNonContainerProviders)) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.NavigationCmdletProvider_NotSupported); } return navigationCmdletProvider; } // GetNavigationProviderInstance #region GetProvider /// <summary> /// Determines if the specified CmdletProvider is loaded. /// </summary> /// /// <param name="name"> /// The name of the CmdletProvider. /// </param> /// /// <returns> /// true if the CmdletProvider is loaded, or false otherwise. /// </returns> /// /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// internal bool IsProviderLoaded(string name) { bool result = false; if (String.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } // Get the provider from the providers container try { ProviderInfo providerInfo = GetSingleProvider(name); result = providerInfo != null; } catch (ProviderNotFoundException) { } return result; } // IsProviderLoaded /// <summary> /// Gets the provider of the specified name /// </summary> /// /// <param name="name"> /// The name of the provider to retrieve /// </param> /// /// <returns> /// The provider of the given name /// </returns> /// /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// The provider with the specified <paramref name="name"/> /// could not be found. /// </exception> /// internal Collection<ProviderInfo> GetProvider(string name) { if (String.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } PSSnapinQualifiedName providerName = PSSnapinQualifiedName.GetInstance(name); if (providerName == null) { ProviderNotFoundException e = new ProviderNotFoundException( name, SessionStateCategory.CmdletProvider, "ProviderNotFoundBadFormat", SessionStateStrings.ProviderNotFoundBadFormat); throw e; } return GetProvider(providerName); } /// <summary> /// Gets the provider of the specified name /// </summary> /// /// <param name="name"> /// The name of the provider to retrieve /// </param> /// /// <returns> /// The provider of the given name /// </returns> /// /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// The provider with the specified <paramref name="name"/> /// could not be found or the name was ambiguous. /// If the name is ambiguous then the PSSnapin qualified name must /// be specified. /// </exception> /// internal ProviderInfo GetSingleProvider(string name) { Collection<ProviderInfo> matchingProviders = GetProvider(name); if (matchingProviders.Count != 1) { if (matchingProviders.Count == 0) { ProviderNotFoundException e = new ProviderNotFoundException( name, SessionStateCategory.CmdletProvider, "ProviderNotFound", SessionStateStrings.ProviderNotFound); throw e; } else { throw NewAmbiguousProviderName(name, matchingProviders); } } return matchingProviders[0]; } internal Collection<ProviderInfo> GetProvider(PSSnapinQualifiedName providerName) { Collection<ProviderInfo> result = new Collection<ProviderInfo>(); if (providerName == null) { ProviderNotFoundException e = new ProviderNotFoundException( providerName.ToString(), SessionStateCategory.CmdletProvider, "ProviderNotFound", SessionStateStrings.ProviderNotFound); throw e; } // Get the provider from the providers container List<ProviderInfo> matchingProviders = null; if (!Providers.TryGetValue(providerName.ShortName, out matchingProviders)) { // If the provider was not found, we may need to auto-mount it. SessionStateInternal.MountDefaultDrive(providerName.ShortName, ExecutionContext); if (!Providers.TryGetValue(providerName.ShortName, out matchingProviders)) { ProviderNotFoundException e = new ProviderNotFoundException( providerName.ToString(), SessionStateCategory.CmdletProvider, "ProviderNotFound", SessionStateStrings.ProviderNotFound); throw e; } } if (ExecutionContext.IsSingleShell && !String.IsNullOrEmpty(providerName.PSSnapInName)) { // Be sure the PSSnapin/Module name matches foreach (ProviderInfo provider in matchingProviders) { if (String.Equals( provider.PSSnapInName, providerName.PSSnapInName, StringComparison.OrdinalIgnoreCase) || String.Equals( provider.ModuleName, providerName.PSSnapInName, StringComparison.OrdinalIgnoreCase)) { result.Add(provider); } } } else { foreach (ProviderInfo provider in matchingProviders) { result.Add(provider); } } return result; } // GetProvider /// <summary> /// Gets all the CoreCommandProviders /// </summary> /// internal IEnumerable<ProviderInfo> ProviderList { get { Collection<ProviderInfo> result = new Collection<ProviderInfo>(); foreach (List<ProviderInfo> providerValues in Providers.Values) { foreach (ProviderInfo provider in providerValues) { result.Add(provider); } } return result; } // get } // Providers /// <summary> /// Copy the Providers from another session state instance... /// </summary> /// <param name="ss">the session state instance to copy from...</param> internal void CopyProviders(SessionStateInternal ss) { if (ss == null || ss.Providers == null) return; // private Dictionary<string, List<ProviderInfo>> providers; _providers = new Dictionary<string, List<ProviderInfo>>(); foreach (KeyValuePair<string, List<ProviderInfo>> e in ss._providers) { _providers.Add(e.Key, e.Value); } } #endregion GetProvider #region NewProvider /// <summary> /// Initializes a provider by loading the assembly, creating an instance of the /// provider, calling its start method followed by the InitializeDefaultDrives method. The /// Drives that are returned from the InitializeDefaultDrives method are then mounted. /// </summary> /// /// <param name="providerInstance"> /// An instance of the provider to use for the initialization. /// </param> /// /// <param name="provider"> /// The provider to be initialized. /// </param> /// /// <param name="context"> /// The context under which the initialization is occurring. If this parameter is not /// null, errors will be written to the WriteError method of the context. /// </param> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="provider"/> or <paramref name="context"/> is null. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider is not a DriveCmdletProvider. /// </exception> /// /// <exception cref="SessionStateException"> /// If a drive already exists for the name of one of the drives the /// provider tries to add. /// </exception> /// /// <exception cref="SessionStateOverflowException"> /// If the provider tries to add default drives which exceed the maximum /// limit for the number of drives in the current scope. /// </exception> /// internal void InitializeProvider( Provider.CmdletProvider providerInstance, ProviderInfo provider, CmdletProviderContext context) { if (provider == null) { throw PSTraceSource.NewArgumentNullException("provider"); } if (context == null) { context = new CmdletProviderContext(this.ExecutionContext); } // Initialize the provider so that it can add any drives // that it needs. List<PSDriveInfo> newDrives = new List<PSDriveInfo>(); DriveCmdletProvider driveProvider = GetDriveProviderInstance(providerInstance); if (driveProvider != null) { try { Collection<PSDriveInfo> drives = driveProvider.InitializeDefaultDrives(context); if (drives != null && drives.Count > 0) { newDrives.AddRange(drives); ProvidersCurrentWorkingDrive[provider] = drives[0]; } } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { throw; } catch (ActionPreferenceStopException) { throw; } catch (Exception e) // Catch-all OK, 3rd party callout { CommandProcessorBase.CheckForSevereException(e); ProviderInvocationException providerException = NewProviderInvocationException( "InitializeDefaultDrivesException", SessionStateStrings.InitializeDefaultDrivesException, provider, String.Empty, e); context.WriteError( new ErrorRecord( providerException, "InitializeDefaultDrivesException", ErrorCategory.InvalidOperation, provider)); } } if (newDrives != null && newDrives.Count > 0) { // Add the drives. foreach (PSDriveInfo newDrive in newDrives) { if (newDrive == null) { continue; } // Only mount drives for the current provider if (!provider.NameEquals(newDrive.Provider.FullName)) { continue; } try { PSDriveInfo validatedNewDrive = ValidateDriveWithProvider(driveProvider, newDrive, context, false); if (validatedNewDrive != null) { // Since providers are global then the drives created // through InitializeDefaultDrives should also be global. GlobalScope.NewDrive(validatedNewDrive); } } catch (SessionStateException exception) { context.WriteError(exception.ErrorRecord); } } // foreach (drive in newDrives) } } // InitializeProvider /// <summary> /// Creates and adds a provider to the provider container /// </summary> /// /// <param name="provider"> /// The provider to add. /// </param> /// /// <returns> /// The provider that was added or null if the provider failed to be added. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="provider"/> is null. /// </exception> /// /// <exception cref="SessionStateException"> /// If the provider already exists. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If there was a failure to load the provider or the provider /// threw an exception. /// </exception> /// internal ProviderInfo NewProvider(ProviderInfo provider) { if (provider == null) { throw PSTraceSource.NewArgumentNullException("provider"); } // Check to see if the provider already exists. // We do the check instead of allowing the hashtable to // throw the exception so that we give a better error // message. ProviderInfo existingProvider = ProviderExists(provider); if (existingProvider != null) { // If it's an already loaded provider, don't return an error... if (existingProvider.ImplementingType == provider.ImplementingType) return existingProvider; SessionStateException sessionStateException = new SessionStateException( provider.Name, SessionStateCategory.CmdletProvider, "CmdletProviderAlreadyExists", SessionStateStrings.CmdletProviderAlreadyExists, ErrorCategory.ResourceExists); throw sessionStateException; } // Make sure we are able to create an instance of the provider. // Note, this will also set the friendly name if the user didn't // specify one. Provider.CmdletProvider providerInstance = provider.CreateInstance(); // Now call start to let the provider initialize itself CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); ProviderInfo newProviderInfo = null; try { newProviderInfo = providerInstance.Start(provider, context); // Set the new provider info in the instance in case the provider // derived a new one providerInstance.SetProviderInformation(newProviderInfo); } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { throw; } catch (ActionPreferenceStopException) { throw; } catch (InvalidOperationException) { throw; } catch (Exception e) // Catch-call OK, 3rd party callout { CommandProcessorBase.CheckForSevereException(e); throw NewProviderInvocationException( "ProviderStartException", SessionStateStrings.ProviderStartException, provider, null, e); } context.ThrowFirstErrorOrDoNothing(true); if (newProviderInfo == null) { throw PSTraceSource.NewInvalidOperationException( SessionStateStrings.InvalidProviderInfoNull); } if (newProviderInfo != provider) { // Since the references are not the same, ensure that the provider // name is the same. if (!string.Equals(newProviderInfo.Name, provider.Name, StringComparison.OrdinalIgnoreCase)) { throw PSTraceSource.NewInvalidOperationException( SessionStateStrings.InvalidProviderInfo); } // Use the new provider info instead provider = newProviderInfo; } // Add the newly create provider to the providers container try { NewProviderEntry(provider); } catch (ArgumentException) { SessionStateException sessionStateException = new SessionStateException( provider.Name, SessionStateCategory.CmdletProvider, "CmdletProviderAlreadyExists", SessionStateStrings.CmdletProviderAlreadyExists, ErrorCategory.ResourceExists); throw sessionStateException; } // Add the provider to the provider current working // drive hashtable so that we can associate a current working // drive with it. ProvidersCurrentWorkingDrive.Add(provider, null); bool initializeProviderError = false; try { // Initialize the provider and give it a chance to // mount some drives. InitializeProvider(providerInstance, provider, context); context.ThrowFirstErrorOrDoNothing(true); } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { initializeProviderError = true; throw; } catch (ActionPreferenceStopException) { initializeProviderError = true; throw; } catch (NotSupportedException) { // We can safely ignore NotSupportedExceptions because // it just means that the provider doesn't support // drives. initializeProviderError = false; } catch (SessionStateException) { initializeProviderError = true; throw; } finally { if (initializeProviderError) { // An exception during initialization should remove the provider from // session state. Providers.Remove(provider.Name.ToString()); ProvidersCurrentWorkingDrive.Remove(provider); provider = null; } } #if RELATIONSHIP_SUPPORTED // 2004/11/24-JeffJon - Relationships have been removed from the Exchange release // Make sure the delay-load relationships get updated for the new provider relationships.ProcessDelayLoadRelationships (provider.Name); #endif // Now write out the result return provider; } // NewProvider private ProviderInfo ProviderExists(ProviderInfo provider) { List<ProviderInfo> matchingProviders = null; if (Providers.TryGetValue(provider.Name, out matchingProviders)) { foreach (ProviderInfo possibleMatch in matchingProviders) { if (provider.NameEquals(possibleMatch.FullName)) { return possibleMatch; } } } return null; } /// <summary> /// Creates an entry in the providers hashtable for the new provider. /// </summary> /// /// <param name="provider"> /// The provider being added. /// </param> /// /// <exception cref="SessionStateException"> /// If a provider with the same name and PSSnapIn name already exists. /// </exception> /// private void NewProviderEntry(ProviderInfo provider) { bool isDuplicateProvider = false; // Add the entry to the list of providers with that name if (!Providers.ContainsKey(provider.Name)) { Providers.Add(provider.Name, new List<ProviderInfo>()); } else { // be sure the same provider from the same PSSnapin doesn't already exist List<ProviderInfo> existingProviders = Providers[provider.Name]; foreach (ProviderInfo existingProvider in existingProviders) { //making sure that we are not trying to add the same provider by checking the provider name & type of the new and existing providers. if (string.IsNullOrEmpty(provider.PSSnapInName) && (string.Equals(existingProvider.Name, provider.Name, StringComparison.OrdinalIgnoreCase) && (existingProvider.GetType().Equals(provider.GetType())))) { isDuplicateProvider = true; } //making sure that we are not trying to add the same provider by checking the PSSnapinName of the new and existing providers. else if (string.Equals(existingProvider.PSSnapInName, provider.PSSnapInName, StringComparison.OrdinalIgnoreCase)) { isDuplicateProvider = true; } } } if (!isDuplicateProvider) { Providers[provider.Name].Add(provider); } } #endregion NewProvider #region Remove Provider private void RemoveProvider(ProviderConfigurationEntry entry) { try { CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); string providerName = GetProviderName(entry); RemoveProvider(providerName, true, context); context.ThrowFirstErrorOrDoNothing(); } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { throw; } catch (ActionPreferenceStopException) { throw; } catch (Exception e) // Catch-all OK, 3rd party callout { CommandProcessorBase.CheckForSevereException(e); // NTRAID#Windows OS Bugs-1009281-2004/02/11-JeffJon this.ExecutionContext.ReportEngineStartupError(e); } } private string GetProviderName(ProviderConfigurationEntry entry) { string name = entry.Name; if (entry.PSSnapIn != null) { name = string.Format( System.Globalization.CultureInfo.InvariantCulture, "{0}\\{1}", entry.PSSnapIn.Name, entry.Name); } return name; } /// <summary> /// Removes the provider of the given name. /// </summary> /// /// <param name="providerName"> /// The name of the provider to remove. /// </param> /// /// <param name="force"> /// Determines if the provider should be removed forcefully even if there were /// drives present or errors. /// </param> /// /// <param name="context"> /// The context under which the command is being run. /// </param> /// /// <error cref="ArgumentNullException"> /// If <paramref name="providerName"/> is null. /// </error> /// /// <error cref="SessionStateException"> /// There are still drives associated with this provider, /// and the "force" option was not specified. /// </error> /// /// <error cref="ProviderNotFoundException"> /// A provider with name <paramref name="providerName"/> could not be found. /// </error> /// /// <error> /// If a provider throws an exception it gets written to the <paramref name="context"/>. /// </error> /// /// <exception cref="ArgumentException"> /// If <paramref name="providerName"/> is null or empty. /// </exception> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="context"/> is null. /// </exception> /// /// <remarks> /// All drives associated with the provider must be removed before the provider /// can be removed. Call SessionState.GetDrivesForProvider() to determine if there /// are any drives associated with the provider. A SessionStateException /// will be written to the context if any such drives do exist. /// </remarks> /// internal void RemoveProvider( string providerName, bool force, CmdletProviderContext context) { if (context == null) { throw PSTraceSource.NewArgumentNullException("context"); } if (String.IsNullOrEmpty(providerName)) { throw PSTraceSource.NewArgumentException("providerName"); } bool errors = false; ProviderInfo provider = null; try { provider = GetSingleProvider(providerName); } catch (ProviderNotFoundException) { return; } try { // First get an instance of the provider to make sure it exists Provider.CmdletProvider providerBase = GetProviderInstance(provider); if (providerBase == null) { ProviderNotFoundException e = new ProviderNotFoundException( providerName, SessionStateCategory.CmdletProvider, "ProviderNotFound", SessionStateStrings.ProviderNotFound); context.WriteError(new ErrorRecord(e.ErrorRecord, e)); errors = true; } else { // See if there are any drives present for the provider int driveCount = 0; foreach (PSDriveInfo drive in GetDrivesForProvider(providerName)) { if (drive != null) { ++driveCount; break; } } if (driveCount > 0) { if (force) { // Forcefully remove all the drives foreach (PSDriveInfo drive in GetDrivesForProvider(providerName)) { if (drive != null) { RemoveDrive(drive, true, null); } } } else { errors = true; // Since there are still drives associated with the provider // the provider cannot be removed SessionStateException e = new SessionStateException( providerName, SessionStateCategory.CmdletProvider, "RemoveDrivesBeforeRemovingProvider", SessionStateStrings.RemoveDrivesBeforeRemovingProvider, ErrorCategory.InvalidOperation); context.WriteError(new ErrorRecord(e.ErrorRecord, e)); return; } } // Now tell the provider that they are going to be removed by // calling the Stop method try { providerBase.Stop(context); } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { throw; } catch (ActionPreferenceStopException) { throw; } } } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { throw; } catch (ActionPreferenceStopException) { throw; } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); errors = true; context.WriteError( new ErrorRecord( e, "RemoveProviderUnexpectedException", ErrorCategory.InvalidArgument, providerName)); } finally { if (force || !errors) { // Log the provider stopped event MshLog.LogProviderLifecycleEvent( this.ExecutionContext, providerName, ProviderState.Stopped); RemoveProviderFromCollection(provider); ProvidersCurrentWorkingDrive.Remove(provider); #if RELATIONSHIP_SUPPORTED // 2004/11/24-JeffJon - Relationships have been removed from the Exchange release // Now make sure no relationship reference this provider relationships.ProcessRelationshipsOnCmdletProviderRemoval (providerName); #endif } } } // RemoveProvider /// <summary> /// Removes the provider from the providers dictionary. /// </summary> /// /// <param name="provider"> /// The provider to be removed. /// </param> /// /// <remarks> /// If there are multiple providers with the same name, then only the provider /// from the matching PSSnapin is removed. /// If the last provider of that name is removed the entry is removed from the dictionary. /// </remarks> /// private void RemoveProviderFromCollection(ProviderInfo provider) { List<ProviderInfo> matchingProviders; if (Providers.TryGetValue(provider.Name, out matchingProviders)) { if (matchingProviders.Count == 1 && matchingProviders[0].NameEquals(provider.FullName)) { Providers.Remove(provider.Name); } else { matchingProviders.Remove(provider); } } } #endregion RemoveProvider /// <summary> /// Gets the count of the number of providers that are loaded /// </summary> /// internal int ProviderCount { get { int count = 0; foreach (List<ProviderInfo> matchingProviders in Providers.Values) { count += matchingProviders.Count; } return count; } } // ProviderCount } // SessionStateInternal class } #pragma warning restore 56500
/* * 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.Compute { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Cluster; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Compute.Closure; using Apache.Ignite.Core.Impl.Memory; using Apache.Ignite.Core.Impl.Resource; /// <summary> /// Compute task holder interface used to avoid generics. /// </summary> internal interface IComputeTaskHolder { /// <summary> /// Perform map step. /// </summary> /// <param name="inStream">Stream with IN data (topology info).</param> /// <param name="outStream">Stream for OUT data (map result).</param> /// <returns>Map with produced jobs.</returns> void Map(PlatformMemoryStream inStream, PlatformMemoryStream outStream); /// <summary> /// Process local job result. /// </summary> /// <param name="jobId">Job pointer.</param> /// <returns>Policy.</returns> int JobResultLocal(ComputeJobHolder jobId); /// <summary> /// Process remote job result. /// </summary> /// <param name="jobId">Job pointer.</param> /// <param name="stream">Stream.</param> /// <returns>Policy.</returns> int JobResultRemote(ComputeJobHolder jobId, PlatformMemoryStream stream); /// <summary> /// Perform task reduce. /// </summary> void Reduce(); /// <summary> /// Complete task. /// </summary> /// <param name="taskHandle">Task handle.</param> void Complete(long taskHandle); /// <summary> /// Complete task with error. /// </summary> /// <param name="taskHandle">Task handle.</param> /// <param name="stream">Stream with serialized exception.</param> void CompleteWithError(long taskHandle, PlatformMemoryStream stream); } /// <summary> /// Compute task holder. /// </summary> internal class ComputeTaskHolder<TA, T, TR> : IComputeTaskHolder { /** Empty results. */ private static readonly IList<IComputeJobResult<T>> EmptyRes = new ReadOnlyCollection<IComputeJobResult<T>>(new List<IComputeJobResult<T>>()); /** Compute instance. */ private readonly ComputeImpl _compute; /** Actual task. */ private readonly IComputeTask<TA, T, TR> _task; /** Task argument. */ private readonly TA _arg; /** Results cache flag. */ private readonly bool _resCache; /** Task future. */ private readonly Future<TR> _fut = new Future<TR>(); /** Jobs whose results are cached. */ private ISet<object> _resJobs; /** Cached results. */ private IList<IComputeJobResult<T>> _ress; /** Handles for jobs which are not serialized right away. */ private volatile List<long> _jobHandles; /// <summary> /// Constructor. /// </summary> /// <param name="grid">Grid.</param> /// <param name="compute">Compute.</param> /// <param name="task">Task.</param> /// <param name="arg">Argument.</param> public ComputeTaskHolder(Ignite grid, ComputeImpl compute, IComputeTask<TA, T, TR> task, TA arg) { _compute = compute; _arg = arg; _task = task; ResourceTypeDescriptor resDesc = ResourceProcessor.Descriptor(task.GetType()); IComputeResourceInjector injector = task as IComputeResourceInjector; if (injector != null) injector.Inject(grid); else resDesc.InjectIgnite(task, grid); _resCache = !resDesc.TaskNoResultCache; } /** <inheritDoc /> */ [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "User code can throw any exception")] public void Map(PlatformMemoryStream inStream, PlatformMemoryStream outStream) { IList<IClusterNode> subgrid; ClusterGroupImpl prj = (ClusterGroupImpl)_compute.ClusterGroup; var ignite = (Ignite) prj.Ignite; // 1. Unmarshal topology info if topology changed. var reader = prj.Marshaller.StartUnmarshal(inStream); if (reader.ReadBoolean()) { long topVer = reader.ReadLong(); List<IClusterNode> nodes = new List<IClusterNode>(reader.ReadInt()); int nodesCnt = reader.ReadInt(); subgrid = new List<IClusterNode>(nodesCnt); for (int i = 0; i < nodesCnt; i++) { IClusterNode node = ignite.GetNode(reader.ReadGuid()); nodes.Add(node); if (reader.ReadBoolean()) subgrid.Add(node); } // Update parent projection to help other task callers avoid this overhead. // Note that there is a chance that topology changed even further and this update fails. // It means that some of subgrid nodes could have left the Grid. This is not critical // for us, because Java will handle it gracefully. prj.UpdateTopology(topVer, nodes); } else { IList<IClusterNode> nodes = prj.NodesNoRefresh(); Debug.Assert(nodes != null, "At least one topology update should have occurred."); subgrid = IgniteUtils.Shuffle(nodes); } // 2. Perform map. IDictionary<IComputeJob<T>, IClusterNode> map; Exception err; try { map = _task.Map(subgrid, _arg); err = null; } catch (Exception e) { map = null; err = e; // Java can receive another exception in case of marshalling failure but it is not important. Finish(default(TR), e); } // 3. Write map result to the output stream. BinaryWriter writer = prj.Marshaller.StartMarshal(outStream); try { if (err == null) { writer.WriteBoolean(true); // Success flag. if (map == null) writer.WriteBoolean(false); // Map produced no result. else { writer.WriteBoolean(true); // Map produced result. _jobHandles = WriteJobs(writer, map); } } else { writer.WriteBoolean(false); // Map failed. // Write error as string because it is not important for Java, we need only to print // a message in the log. writer.WriteString("Map step failed [errType=" + err.GetType().Name + ", errMsg=" + err.Message + ']'); } } catch (Exception e) { // Something went wrong during marshaling. Finish(default(TR), e); outStream.Reset(); writer.WriteBoolean(false); // Map failed. writer.WriteString(e.Message); // Write error message. } finally { prj.Marshaller.FinishMarshal(writer); } } /// <summary> /// Writes job map. /// </summary> /// <param name="writer">Writer.</param> /// <param name="map">Map</param> /// <returns>Job handle list.</returns> private static List<long> WriteJobs(BinaryWriter writer, IDictionary<IComputeJob<T>, IClusterNode> map) { Debug.Assert(writer != null && map != null); writer.WriteInt(map.Count); // Amount of mapped jobs. var jobHandles = new List<long>(map.Count); var ignite = writer.Marshaller.Ignite; try { foreach (KeyValuePair<IComputeJob<T>, IClusterNode> mapEntry in map) { var job = new ComputeJobHolder(ignite, mapEntry.Key.ToNonGeneric()); IClusterNode node = mapEntry.Value; var jobHandle = ignite.HandleRegistry.Allocate(job); jobHandles.Add(jobHandle); writer.WriteLong(jobHandle); if (node.IsLocal) writer.WriteBoolean(false); // Job is not serialized. else { writer.WriteBoolean(true); // Job is serialized. writer.WriteObject(job); } writer.WriteGuid(node.Id); } } catch (Exception) { foreach (var handle in jobHandles) ignite.HandleRegistry.Release(handle); throw; } return jobHandles; } /** <inheritDoc /> */ public int JobResultLocal(ComputeJobHolder job) { return (int)JobResult0(job.JobResult); } /** <inheritDoc /> */ [SuppressMessage("ReSharper", "PossibleInvalidOperationException")] public int JobResultRemote(ComputeJobHolder job, PlatformMemoryStream stream) { // 1. Unmarshal result. BinaryReader reader = _compute.Marshaller.StartUnmarshal(stream); var nodeId = reader.ReadGuid(); Debug.Assert(nodeId.HasValue); bool cancelled = reader.ReadBoolean(); try { object err; var data = BinaryUtils.ReadInvocationResult(reader, out err); // 2. Process the result. return (int) JobResult0(new ComputeJobResultImpl(data, (Exception) err, job.Job, nodeId.Value, cancelled)); } catch (Exception e) { Finish(default(TR), e); if (!(e is IgniteException)) throw new IgniteException("Failed to process job result: " + e.Message, e); throw; } } /** <inheritDoc /> */ public void Reduce() { try { TR taskRes = _task.Reduce(_resCache ? _ress : EmptyRes); Finish(taskRes, null); } catch (Exception e) { Finish(default(TR), e); if (!(e is IgniteException)) throw new IgniteException("Failed to reduce task: " + e.Message, e); throw; } } /** <inheritDoc /> */ public void Complete(long taskHandle) { Clean(taskHandle); } /// <summary> /// Complete task with error. /// </summary> /// <param name="taskHandle">Task handle.</param> /// <param name="e">Error.</param> public void CompleteWithError(long taskHandle, Exception e) { Finish(default(TR), e); Clean(taskHandle); } /** <inheritDoc /> */ [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "User object deserialization can throw any exception")] public void CompleteWithError(long taskHandle, PlatformMemoryStream stream) { BinaryReader reader = _compute.Marshaller.StartUnmarshal(stream); Exception err; try { err = reader.ReadBoolean() ? reader.ReadObject<BinaryObject>().Deserialize<Exception>() : ExceptionUtils.GetException(_compute.Marshaller.Ignite, reader.ReadString(), reader.ReadString()); } catch (Exception e) { err = new IgniteException("Task completed with error, but it cannot be unmarshalled: " + e.Message, e); } CompleteWithError(taskHandle, err); } /// <summary> /// Task completion future. /// </summary> internal Future<TR> Future { get { return _fut; } } /// <summary> /// Manually set job handles. Used by closures because they have separate flow for map step. /// </summary> /// <param name="jobHandles">Job handles.</param> internal void JobHandles(List<long> jobHandles) { _jobHandles = jobHandles; } /// <summary> /// Process job result. /// </summary> /// <param name="res">Result.</param> private ComputeJobResultPolicy JobResult0(IComputeJobResult<object> res) { try { IList<IComputeJobResult<T>> ress0; // 1. Prepare old results. if (_resCache) { if (_resJobs == null) { _resJobs = new HashSet<object>(); _ress = new List<IComputeJobResult<T>>(); } ress0 = _ress; } else ress0 = EmptyRes; // 2. Invoke user code. var policy = _task.OnResult(new ComputeJobResultGenericWrapper<T>(res), ress0); // 3. Add result to the list only in case of success. if (_resCache) { var job = res.Job.Unwrap(); if (!_resJobs.Add(job)) { // Duplicate result => find and replace it with the new one. var oldRes = _ress.Single(item => item.Job == job); _ress.Remove(oldRes); } _ress.Add(new ComputeJobResultGenericWrapper<T>(res)); } return policy; } catch (Exception e) { Finish(default(TR), e); if (!(e is IgniteException)) throw new IgniteException("Failed to process job result: " + e.Message, e); throw; } } /// <summary> /// Finish task. /// </summary> /// <param name="res">Result.</param> /// <param name="err">Error.</param> private void Finish(TR res, Exception err) { _fut.OnDone(res, err); } /// <summary> /// Clean-up task resources. /// </summary> /// <param name="taskHandle"></param> private void Clean(long taskHandle) { var handles = _jobHandles; var handleRegistry = _compute.Marshaller.Ignite.HandleRegistry; if (handles != null) foreach (var handle in handles) handleRegistry.Release(handle, true); handleRegistry.Release(taskHandle, true); } } }
using System.Collections; using Signum.Utilities.Reflection; using System.Diagnostics.CodeAnalysis; namespace Signum.Entities.Reflection; public interface IEqualityComparerResolver { IEqualityComparer GetEqualityComparer(Type type, PropertyInfo? pi); } public interface ICompletableComparer { void Complete(IEqualityComparerResolver resolver, PropertyInfo? pi); } public class EntityStructuralEqualityComparer<T> : EqualityComparer<T>, ICompletableComparer where T : ModifiableEntity { public Dictionary<string, PropertyComparer<T>> Properties; public Dictionary<Type, IEqualityComparer>? Mixins; public EntityStructuralEqualityComparer() { this.Properties = null!; } public void Complete(IEqualityComparerResolver resolver, PropertyInfo? pi) { Properties = MemberEntryFactory.GenerateList<T>(MemberOptions.Properties | MemberOptions.Getter) .Where(p => !((PropertyInfo)p.MemberInfo).HasAttribute<HiddenPropertyAttribute>()) .ToDictionary(a => a.Name, a => new PropertyComparer<T>( propertyInfo: (PropertyInfo)a.MemberInfo, a.Getter!, comparer: resolver.GetEqualityComparer(((PropertyInfo)a.MemberInfo).PropertyType, (PropertyInfo)a.MemberInfo))); Mixins = !typeof(Entity).IsAssignableFrom(typeof(T)) ? null : MixinDeclarations.GetMixinDeclarations(typeof(T)).ToDictionary(t => t, t => resolver.GetEqualityComparer(t, null)); } public override bool Equals(T? x, T? y) { if ((x == null) != (y == null)) return false; if (x!.GetType() != y!.GetType()) return false; foreach (var p in Properties.Values) { if (!p.Comparer.Equals(p.Getter(x), p.Getter(y))) return false; } if (Mixins != null) { var ex = (Entity)(ModifiableEntity)x; var ey = (Entity)(ModifiableEntity)y; foreach (var kvp in Mixins) { if (!kvp.Value.Equals(ex.GetMixin(kvp.Key), ey.GetMixin(kvp.Key))) return false; } } return true; } public override int GetHashCode(T obj) { if (obj == null) return 0; int result = obj.GetType().GetHashCode(); foreach (var p in Properties.Values) { result = result * 31 + p.Comparer.GetHashCode(p.Getter(obj)!); } if (Mixins != null) { var e = (Entity)(ModifiableEntity)obj; foreach (var kvp in Mixins) { result = result * 31 + kvp.Value.GetHashCode(e.GetMixin(kvp.Key)); } } return result; } } public class ClassStructuralEqualityComparer<T> : EqualityComparer<T>, ICompletableComparer where T: notnull { public Dictionary<string, PropertyComparer<T>> Properties; public ClassStructuralEqualityComparer() { this.Properties = null!; } public void Complete(IEqualityComparerResolver resolver, PropertyInfo? pi) { Properties = MemberEntryFactory.GenerateList<T>(MemberOptions.Properties | MemberOptions.Getter) .ToDictionary(a => a.Name, a => new PropertyComparer<T>( propertyInfo: (PropertyInfo)a.MemberInfo, getter: a.Getter!, comparer: resolver.GetEqualityComparer(((PropertyInfo)a.MemberInfo).PropertyType, (PropertyInfo)a.MemberInfo))); } public override bool Equals([AllowNull] T x, [AllowNull] T y) { if ((x == null) != (y == null)) return false; if (x!.GetType() != y!.GetType()) return false; foreach (var p in Properties.Values) { if (!p.Comparer.Equals(p.Getter(x), p.Getter(y))) return false; } return true; } public override int GetHashCode(T obj) { if (obj == null) return 0; int result = obj.GetType().GetHashCode(); foreach (var p in Properties.Values) { result = result * 31 + p.Comparer.GetHashCode(p.Getter(obj)!); } return result; } } public class PropertyComparer<T> { public PropertyInfo PropertyInfo { get; set; } public Func<T, object?> Getter { get; set; } public IEqualityComparer Comparer { get; set; } public PropertyComparer(PropertyInfo propertyInfo, Func<T, object?> getter, IEqualityComparer comparer) { this.PropertyInfo = propertyInfo; this.Getter = getter; this.Comparer = comparer; } public override string ToString() => $"{PropertyInfo} -> {Comparer}"; } public class SortedListEqualityComparer<T> : EqualityComparer<IList<T>>, ICompletableComparer { public IEqualityComparer<T> ElementComparer { get; set; } public SortedListEqualityComparer() { this.ElementComparer = null!; } public void Complete(IEqualityComparerResolver resolver, PropertyInfo? pi) { ElementComparer = (IEqualityComparer<T>)resolver.GetEqualityComparer(typeof(T), pi); } public override bool Equals(IList<T>? x, IList<T>? y) { if ((x == null) != (y == null)) return false; if (x!.Count != y!.Count) return false; for (int i = 0; i < x.Count; i++) { if (!ElementComparer.Equals(x[i], y[i])) return false; } return true; } public override int GetHashCode(IList<T> obj) { if (obj == null) return 0; int result = 17; foreach (var p in obj) { result = result * 31 + this.ElementComparer.GetHashCode(p!); } return result; } } public class UnsortedListEqualityComparer<T> : EqualityComparer<IList<T>>, ICompletableComparer { public IEqualityComparer<T> ElementComparer { get; set; } public UnsortedListEqualityComparer() { this.ElementComparer = null!; } public void Complete(IEqualityComparerResolver resolver, PropertyInfo? pi) { ElementComparer = (IEqualityComparer<T>)resolver.GetEqualityComparer(typeof(T), pi); } public override bool Equals(IList<T>? mx, IList<T>? my) { if ((mx == null) != (my == null)) return false; if (mx!.Count != my!.Count) return false; var dic = mx.GroupToDictionary(x => ElementComparer.GetHashCode(x!)); foreach (var y in my) { var list = dic.TryGetC(ElementComparer.GetHashCode(y!)); if (list == null) return false; var element = list.FirstOrDefault(l => ElementComparer.Equals(l, y)); if (element == null) return false; list.Remove(element); } return true; } public override int GetHashCode(IList<T> obj) { if (obj == null) return 0; int result = 0; foreach (var p in obj) { result += this.ElementComparer.GetHashCode(p!); } return result; } } public abstract class EqualityComparerResolverWithCache : IEqualityComparerResolver { readonly Dictionary<(Type, PropertyInfo?), IEqualityComparer> cache = new Dictionary<(Type, PropertyInfo?), IEqualityComparer>(); public virtual IEqualityComparer GetEqualityComparer(Type type, PropertyInfo? pi) { if (cache.TryGetValue((type, pi), out var comparer)) return comparer; else { var comp = GetEqualityComparerInternal(type, pi); cache.Add((type, pi), comp); if (comp is ICompletableComparer cc) cc.Complete(this, pi); return comp; } } protected abstract IEqualityComparer GetEqualityComparerInternal(Type type, PropertyInfo? pi); } public class DefaultEqualityComparerResolver : EqualityComparerResolverWithCache { protected override IEqualityComparer GetEqualityComparerInternal(Type type, PropertyInfo? pi) { if (typeof(ModifiableEntity).IsAssignableFrom(type)) { return (IEqualityComparer)Activator.CreateInstance(typeof(EntityStructuralEqualityComparer<>).MakeGenericType(type))!; } if (typeof(IList).IsAssignableFrom(type)) { if (pi?.HasAttribute<PreserveOrderAttribute>() == true) return (IEqualityComparer)Activator.CreateInstance(typeof(SortedListEqualityComparer<>).MakeGenericType(type.ElementType()!))!; else return (IEqualityComparer)Activator.CreateInstance(typeof(UnsortedListEqualityComparer<>).MakeGenericType(type.ElementType()!))!; } if (type.IsClass && type.GetMethod("Equals", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, new[] { typeof(object) }, null) == null) return (IEqualityComparer)Activator.CreateInstance(typeof(ClassStructuralEqualityComparer<>).MakeGenericType(type))!; return (IEqualityComparer)typeof(EqualityComparer<>).MakeGenericType(type).GetProperty("Default")!.GetValue(null)!; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Xml; using System.Collections.Generic; using OLEDB.Test.ModuleCore; using XmlCoreTest.Common; namespace XmlReaderTest.Common { ///////////////////////////////////////////////////////////////////////// // TestCase ReadOuterXml // ///////////////////////////////////////////////////////////////////////// [InheritRequired()] public abstract partial class TCReadSubtree : TCXMLReaderBaseGeneral { [Variation("ReadSubtree only works on Element Node")] public int ReadSubtreeWorksOnlyOnElementNode() { ReloadSource(); while (DataReader.Read()) { if (DataReader.NodeType != XmlNodeType.Element) { string nodeType = DataReader.NodeType.ToString(); bool flag = true; try { DataReader.ReadSubtree(); } catch (InvalidOperationException) { flag = false; } if (flag) { CError.WriteLine("ReadSubtree doesnt throw InvalidOp Exception on NodeType : " + nodeType); return TEST_FAIL; } //now try next read try { DataReader.Read(); } catch (XmlException) { CError.WriteLine("Cannot Read after an invalid operation exception"); return TEST_FAIL; } } else { if (DataReader.HasAttributes) { bool flag = true; DataReader.MoveToFirstAttribute(); try { DataReader.ReadSubtree(); } catch (InvalidOperationException) { flag = false; } if (flag) { CError.WriteLine("ReadSubtree doesnt throw InvalidOp Exception on Attribute Node Type"); return TEST_FAIL; } //now try next read. try { DataReader.Read(); } catch (XmlException) { CError.WriteLine("Cannot Read after an invalid operation exception"); return TEST_FAIL; } } } }//end while return TEST_PASS; } private string _xml = "<root><elem1><elempi/><?pi target?><elem2 xmlns='xyz'><elem/><!--Comment--><x:elem3 xmlns:x='pqr'><elem4 attr4='4'/></x:elem3></elem2></elem1><elem5/><elem6/></root>"; //[Variation("ReadSubtree Test on Root", Pri = 0, Params = new object[]{"root", "", "ELEMENT", "", "", "NONE" })] //[Variation("ReadSubtree Test depth=1", Pri = 0, Params = new object[] { "elem1", "", "ELEMENT", "elem5", "", "ELEMENT" })] //[Variation("ReadSubtree Test depth=2", Pri = 0, Params = new object[] { "elem2", "", "ELEMENT", "elem1", "", "ENDELEMENT" })] //[Variation("ReadSubtree Test depth=3", Pri = 0, Params = new object[] { "x:elem3", "", "ELEMENT", "elem2", "", "ENDELEMENT" })] //[Variation("ReadSubtree Test depth=4", Pri = 0, Params = new object[] { "elem4", "", "ELEMENT", "x:elem3", "", "ENDELEMENT" })] //[Variation("ReadSubtree Test empty element", Pri = 0, Params = new object[] { "elem5", "", "ELEMENT", "elem6", "", "ELEMENT" })] //[Variation("ReadSubtree Test empty element before root", Pri = 0, Params = new object[] { "elem6", "", "ELEMENT", "root", "", "ENDELEMENT" })] //[Variation("ReadSubtree Test PI after element", Pri = 0, Params = new object[] { "elempi", "", "ELEMENT", "pi", "target", "PROCESSINGINSTRUCTION" })] //[Variation("ReadSubtree Test Comment after element", Pri = 0, Params = new object[] { "elem", "", "ELEMENT", "", "Comment", "COMMENT" })] public int v2() { int count = 0; string name = CurVariation.Params[count++].ToString(); string value = CurVariation.Params[count++].ToString(); string type = CurVariation.Params[count++].ToString(); string oname = CurVariation.Params[count++].ToString(); string ovalue = CurVariation.Params[count++].ToString(); string otype = CurVariation.Params[count++].ToString(); ReloadSource(new StringReader(_xml)); DataReader.PositionOnElement(name); XmlReader r = DataReader.ReadSubtree(); CError.Compare(r.ReadState, ReadState.Initial, "Reader state is not Initial"); CError.Compare(r.Name, String.Empty, "Name is not empty"); CError.Compare(r.NodeType, XmlNodeType.None, "Nodetype is not empty"); CError.Compare(r.Depth, 0, "Depth is not zero"); r.Read(); CError.Compare(r.ReadState, ReadState.Interactive, "Reader state is not Interactive"); CError.Compare(r.Name, name, "Subreader name doesnt match"); CError.Compare(r.Value, value, "Subreader value doesnt match"); CError.Compare(r.NodeType.ToString().ToUpperInvariant(), type, "Subreader nodetype doesnt match"); CError.Compare(r.Depth, 0, "Subreader Depth is not zero"); while (r.Read()) ; r.Dispose(); CError.Compare(r.ReadState, ReadState.Closed, "Reader state is not Initial"); CError.Compare(r.Name, String.Empty, "Name is not empty"); CError.Compare(r.NodeType, XmlNodeType.None, "Nodetype is not empty"); DataReader.Read(); CError.Compare(DataReader.Name, oname, "Main name doesnt match"); CError.Compare(DataReader.Value, ovalue, "Main value doesnt match"); CError.Compare(DataReader.NodeType.ToString().ToUpperInvariant(), otype, "Main nodetype doesnt match"); DataReader.Close(); return TEST_PASS; } [Variation("Read with entities", Pri = 1)] public int v3() { ReloadSource(); DataReader.PositionOnElement("PLAY"); XmlReader r = DataReader.ReadSubtree(); while (r.Read()) { if (r.NodeType == XmlNodeType.EntityReference) { if (r.CanResolveEntity) r.ResolveEntity(); } } DataReader.Close(); return TEST_PASS; } [Variation("Inner XML on Subtree reader", Pri = 1)] public int v4() { string xmlStr = "<elem1><elem2/></elem1>"; ReloadSource(new StringReader(xmlStr)); DataReader.PositionOnElement("elem1"); XmlReader r = DataReader.ReadSubtree(); r.Read(); CError.Compare(r.ReadInnerXml(), "<elem2 />", "Inner Xml Fails"); CError.Compare(r.Read(), false, "Read returns false"); DataReader.Close(); return TEST_PASS; } [Variation("Outer XML on Subtree reader", Pri = 1)] public int v5() { string xmlStr = "<elem1><elem2/></elem1>"; ReloadSource(new StringReader(xmlStr)); DataReader.PositionOnElement("elem1"); XmlReader r = DataReader.ReadSubtree(); r.Read(); CError.Compare(r.ReadOuterXml(), "<elem1><elem2 /></elem1>", "Outer Xml Fails"); CError.Compare(r.Read(), false, "Read returns true"); DataReader.Close(); return TEST_PASS; } //[Variation("Close on inner reader with CloseInput should not close the outer reader", Pri = 1, Params = new object[] { "true" })] //[Variation("Close on inner reader with CloseInput should not close the outer reader", Pri = 1, Params = new object[] { "false" })] public int v7() { if (!(IsFactoryTextReader() || IsBinaryReader() || IsFactoryValidatingReader())) { return TEST_SKIPPED; } string fileName = GetTestFileName(EREADER_TYPE.GENERIC); bool ci = Boolean.Parse(CurVariation.Params[0].ToString()); XmlReaderSettings settings = new XmlReaderSettings(); settings.CloseInput = ci; CError.WriteLine(ci); MyDict<string, object> options = new MyDict<string, object>(); options.Add(ReaderFactory.HT_FILENAME, fileName); options.Add(ReaderFactory.HT_READERSETTINGS, settings); ReloadSource(options); DataReader.PositionOnElement("elem2"); XmlReader r = DataReader.ReadSubtree(); CError.Compare(DataReader.ReadState, ReadState.Interactive, "ReadState not interactive"); DataReader.Close(); return TEST_PASS; } private XmlReader NestRead(XmlReader r) { r.Read(); r.Read(); if (!(r.Name == "elem0" && r.NodeType == XmlNodeType.Element)) { CError.WriteLine(r.Name); NestRead(r.ReadSubtree()); } r.Dispose(); return r; } [Variation("Nested Subtree reader calls", Pri = 2)] public int v8() { string xmlStr = "<elem1><elem2><elem3><elem4><elem5><elem6><elem7><elem8><elem9><elem0></elem0></elem9></elem8></elem7></elem6></elem5></elem4></elem3></elem2></elem1>"; ReloadSource(new StringReader(xmlStr)); XmlReader r = DataReader.Internal; NestRead(r); CError.Compare(r.ReadState, ReadState.Closed, "Reader Read State is not closed"); return TEST_PASS; } [Variation("ReadSubtree for element depth more than 4K chars", Pri = 2)] public int v100() { ManagedNodeWriter mnw = new ManagedNodeWriter(); mnw.PutPattern("X"); do { mnw.OpenElement(); mnw.CloseElement(); } while (mnw.GetNodes().Length < 4096); mnw.Finish(); ReloadSource(new StringReader(mnw.GetNodes())); DataReader.PositionOnElement("ELEMENT_2"); XmlReader r = DataReader.ReadSubtree(); while (r.Read()) ; DataReader.Read(); CError.Compare(DataReader.Name, "ELEMENT_1", "Main name doesnt match"); CError.Compare(DataReader.Value, "", "Main value doesnt match"); CError.Compare(DataReader.NodeType.ToString().ToUpperInvariant(), "ENDELEMENT", "Main nodetype doesnt match"); DataReader.Close(); return TEST_PASS; } [Variation("Multiple Namespaces on Subtree reader", Pri = 1)] public int SubtreeReaderCanDealWithMultipleNamespaces() { string xmlStr = "<root xmlns:p1='a' xmlns:p2='b'><e p1:a='' p2:a=''></e></root>"; ReloadSource(new StringReader(xmlStr)); DataReader.PositionOnElement("e"); XmlReader r = DataReader.ReadSubtree(); while (r.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Subtree Reader caches the NodeType and reports node type of Attribute on subsequent reads.", Pri = 1)] public int SubtreeReaderReadsProperlyNodeTypeOfAttributes() { string xmlStr = "<root xmlns='foo'><b blah='blah'/><b/></root>"; ReloadSource(new StringReader(xmlStr)); DataReader.PositionOnElement("root"); XmlReader xxr = DataReader.ReadSubtree(); xxr.Read(); //Now on root. CError.Compare(xxr.Name, "root", "Root Elem"); CError.Compare(xxr.MoveToNextAttribute(), true, "MTNA 1"); CError.Compare(xxr.NodeType, XmlNodeType.Attribute, "XMLNS NT"); CError.Compare(xxr.Name, "xmlns", "XMLNS Attr"); CError.Compare(xxr.Value, "foo", "XMLNS Value"); CError.Compare(xxr.MoveToNextAttribute(), false, "MTNA 2"); xxr.Read(); //Now on b. CError.Compare(xxr.Name, "b", "b Elem"); CError.Compare(xxr.MoveToNextAttribute(), true, "MTNA 3"); CError.Compare(xxr.NodeType, XmlNodeType.Attribute, "blah NT"); CError.Compare(xxr.Name, "blah", "blah Attr"); CError.Compare(xxr.Value, "blah", "blah Value"); CError.Compare(xxr.MoveToNextAttribute(), false, "MTNA 4"); xxr.Read(); //Now on /b. CError.Compare(xxr.Name, "b", "b EndElem"); CError.Compare(xxr.NodeType, XmlNodeType.Element, "b Elem NT"); CError.Compare(xxr.MoveToNextAttribute(), false, "MTNA 5"); xxr.Read(); //Now on /root. CError.Compare(xxr.Name, "root", "root EndElem"); CError.Compare(xxr.NodeType, XmlNodeType.EndElement, "root EndElem NT"); CError.Compare(xxr.MoveToNextAttribute(), false, "MTNA 6"); DataReader.Close(); return TEST_PASS; } [Variation("XmlSubtreeReader add duplicate namespace declaration")] public int XmlSubtreeReaderDoesntDuplicateLocalNames() { Dictionary<string, object> localNames = new Dictionary<string, object>(); string xml = "<?xml version='1.0' encoding='utf-8'?>" + "<IXmlSerializable z:CLRType='A' z:ClrAssembly='test, " + "Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' " + "xmlns='http://schemas.datacontract.org' xmlns:z='http://schemas.microsoft.com' >" + "<WriteAttributeString p3:attributeName3='attributeValue3' " + "abc:attributeName='attributeValue' attributeName2='attributeValue2' " + "xmlns:abc='myNameSpace' xmlns:p3='myNameSpace3' /></IXmlSerializable>"; ReloadSourceStr(xml); DataReader.MoveToContent(); XmlReader reader = DataReader.ReadSubtree(); reader.ReadToDescendant("WriteAttributeString"); while (reader.MoveToNextAttribute()) { if (localNames.ContainsKey(reader.LocalName)) { CError.WriteLine("Duplicated LocalName: {0}", reader.LocalName); return TEST_FAIL; } localNames.Add(reader.LocalName, null); } return TEST_PASS; } [Variation("XmlSubtreeReader adds duplicate namespace declaration")] public int XmlSubtreeReaderDoesntAddMultipleNamespaceDeclarations() { ReloadSource(new StringReader("<r xmlns:a='X'><a:e/></r>")); DataReader.Read(); DataReader.Read(); if (IsBinaryReader()) DataReader.Read(); XmlReader r1 = DataReader.ReadSubtree(); r1.Read(); XmlReader r2 = r1.ReadSubtree(); r2.Read(); string xml = r2.ReadOuterXml(); CError.Compare(xml, "<a:e xmlns:a=\"X\" />", "Mismatch"); return TEST_PASS; } [Variation("XmlSubtreeReader.Dispose disposes the main reader")] public int XmlReaderDisposeDoesntDisposeMainReader() { ReloadSource(new StringReader("<a><b></b></a>")); DataReader.PositionOnElement("b"); using (XmlReader subtreeReader = DataReader.ReadSubtree()) { } if (DataReader.NodeType.ToString() == "EndElement" && DataReader.Name.ToString() == "b" && DataReader.Read() == true) return TEST_PASS; return TEST_FAIL; } private string[] _s = new string[] { "<root xmlns:p1='a' xmlns:p2='b'><e p1:a='' p2:a=''></e></root>", "<root xmlns:p1='a' xmlns:p2='b'><e p1:a='' p2:a='' xmlns:p2='b' ></e></root>", "<root xmlns:p1='a' xmlns:p2='b'><e xmlns:p2='b' p1:a='' p2:a='' ></e></root>", "<root xmlns:p1='a' ><e p1:a='' p2:a='' xmlns:p2='b' ></e></root>", "<root xmlns:p2='b'><e xmlns:p1='a' p1:a='' p2:a=''></e></root>", "<root xmlns:p1='a' xmlns:p2='b'><e p1:a='' p2:a='' xmlns:p1='a' xmlns:p2='b'></e></root>" }; private string[][] _exp = { new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2"}, new string[] {"p1:a", "p2:a", "xmlns:p2", "xmlns:p1"}, new string[] {"xmlns:p2", "p1:a", "p2:a", "xmlns:p1" }, new string[] {"p1:a", "p2:a", "xmlns:p2", "xmlns:p1"}, new string[] {"xmlns:p1", "p1:a", "p2:a", "xmlns:p2"}, new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2"}, }; private string[][] _expXpath = { new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2"}, new string[] {"xmlns:p2", "p1:a", "p2:a", "xmlns:p1"}, new string[] {"xmlns:p2", "p1:a", "p2:a", "xmlns:p1" }, new string[] {"xmlns:p2", "p1:a", "p2:a", "xmlns:p1"}, new string[] {"xmlns:p1", "p1:a", "p2:a", "xmlns:p2"}, new string[] {"xmlns:p1", "xmlns:p2", "p1:a", "p2:a"}, }; private string[][] _expXslt = { new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2"}, new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2"}, new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2" }, new string[] {"p1:a", "p2:a", "xmlns:p2", "xmlns:p1"}, new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2"}, new string[] {"p1:a", "p2:a", "xmlns:p1", "xmlns:p2"}, }; //[Variation("0. XmlReader.Name inconsistent when reading namespace node attribute", Param = 0)] //[Variation("1. XmlReader.Name inconsistent when reading namespace node attribute", Param = 1)] //[Variation("2. XmlReader.Name inconsistent when reading namespace node attribute", Param = 2)] //[Variation("3. XmlReader.Name inconsistent when reading namespace node attribute", Param = 3)] //[Variation("4. XmlReader.Name inconsistent when reading namespace node attribute", Param = 4)] //[Variation("5. XmlReader.Name inconsistent when reading namespace node attribute", Param = 5)] public int XmlReaderNameIsConsistentWhenReadingNamespaceNodeAttribute() { int param = (int)CurVariation.Param; ReloadSource(new StringReader(_s[param])); DataReader.PositionOnElement("e"); using (XmlReader r = DataReader.ReadSubtree()) { while (r.Read()) { for (int i = 0; i < r.AttributeCount; i++) { r.MoveToAttribute(i); if (IsXPathNavigatorReader()) CError.Compare(r.Name, _expXpath[param][i], "Error"); else if (IsXsltReader()) CError.Compare(r.Name, _expXslt[param][i], "Error"); else CError.Compare(r.Name, _exp[param][i], "Error"); } } } return TEST_PASS; } [Variation("Indexing methods cause infinite recursion & stack overflow")] public int IndexingMethodsWorksProperly() { string xml = "<e1 a='a1' b='b1'> 123 <e2 a='a2' b='b2'> abc</e2><e3 b='b3'/></e1>"; ReloadSourceStr(xml); DataReader.Read(); XmlReader r2 = DataReader.ReadSubtree(); r2.Read(); CError.Compare(r2[0], "a1", "Error 1"); CError.Compare(r2["b"], "b1", "Error 2"); CError.Compare(r2["a", null], "a1", "Error 3"); return TEST_PASS; } //[Variation("1. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 1)] //[Variation("2. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 2)] //[Variation("3. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 3)] //[Variation("4. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 4)] //[Variation("5. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 5)] //[Variation("6. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 6)] //[Variation("7. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 7)] //[Variation("8. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 8)] //[Variation("9. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 9)] //[Variation("10. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 10)] //[Variation("11. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 11)] //[Variation("12. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 12)] //[Variation("13. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 13)] //[Variation("14. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 14)] //[Variation("15. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 15)] //[Variation("16. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 16)] //[Variation("17. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 17)] //[Variation("18. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 18)] //[Variation("19. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 19)] //[Variation("20. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 20)] //[Variation("21. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 21)] //[Variation("22. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 22)] //[Variation("23. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 23)] //[Variation("24. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 24)] public int DisposingSubtreeReaderThatIsInErrorStateWorksProperly() { int param = (int)CurVariation.Param; byte[] b = new byte[4]; string xml = "<Report><Account><Balance>-4,095,783.00" + "</Balance><LastActivity>2006/01/05</LastActivity>" + "</Account></Report>"; ReloadSourceStr(xml); while (DataReader.Name != "Account") DataReader.Read(); XmlReader sub = DataReader.ReadSubtree(); while (sub.Read()) { if (sub.Name == "Balance") { try { switch (param) { case 1: decimal num1 = sub.ReadElementContentAsDecimal(); break; case 2: object num2 = sub.ReadElementContentAs(typeof(float), null); break; case 3: bool num3 = sub.ReadElementContentAsBoolean(); break; case 5: float num5 = sub.ReadElementContentAsFloat(); break; case 6: double num6 = sub.ReadElementContentAsDouble(); break; case 7: int num7 = sub.ReadElementContentAsInt(); break; case 8: long num8 = sub.ReadElementContentAsLong(); break; case 9: object num9 = sub.ReadElementContentAs(typeof(double), null); break; case 10: object num10 = sub.ReadElementContentAs(typeof(decimal), null); break; case 11: sub.Read(); decimal num11 = sub.ReadContentAsDecimal(); break; case 12: sub.Read(); object num12 = sub.ReadContentAs(typeof(float), null); break; case 13: sub.Read(); bool num13 = sub.ReadContentAsBoolean(); break; case 15: sub.Read(); float num15 = sub.ReadContentAsFloat(); break; case 16: sub.Read(); double num16 = sub.ReadContentAsDouble(); break; case 17: sub.Read(); int num17 = sub.ReadContentAsInt(); break; case 18: sub.Read(); long num18 = sub.ReadContentAsLong(); break; case 19: sub.Read(); object num19 = sub.ReadContentAs(typeof(double), null); break; case 20: sub.Read(); object num20 = sub.ReadContentAs(typeof(decimal), null); break; case 21: object num21 = sub.ReadElementContentAsBase64(b, 0, 2); break; case 22: object num22 = sub.ReadElementContentAsBinHex(b, 0, 2); break; case 23: sub.Read(); object num23 = sub.ReadContentAsBase64(b, 0, 2); break; case 24: sub.Read(); object num24 = sub.ReadContentAsBinHex(b, 0, 2); break; } } catch (XmlException) { try { switch (param) { case 1: decimal num1 = sub.ReadElementContentAsDecimal(); break; case 2: object num2 = sub.ReadElementContentAs(typeof(float), null); break; case 3: bool num3 = sub.ReadElementContentAsBoolean(); break; case 5: float num5 = sub.ReadElementContentAsFloat(); break; case 6: double num6 = sub.ReadElementContentAsDouble(); break; case 7: int num7 = sub.ReadElementContentAsInt(); break; case 8: long num8 = sub.ReadElementContentAsLong(); break; case 9: object num9 = sub.ReadElementContentAs(typeof(double), null); break; case 10: object num10 = sub.ReadElementContentAs(typeof(decimal), null); break; case 11: sub.Read(); decimal num11 = sub.ReadContentAsDecimal(); break; case 12: sub.Read(); object num12 = sub.ReadContentAs(typeof(float), null); break; case 13: sub.Read(); bool num13 = sub.ReadContentAsBoolean(); break; case 15: sub.Read(); float num15 = sub.ReadContentAsFloat(); break; case 16: sub.Read(); double num16 = sub.ReadContentAsDouble(); break; case 17: sub.Read(); int num17 = sub.ReadContentAsInt(); break; case 18: sub.Read(); long num18 = sub.ReadContentAsLong(); break; case 19: sub.Read(); object num19 = sub.ReadContentAs(typeof(double), null); break; case 20: sub.Read(); object num20 = sub.ReadContentAs(typeof(decimal), null); break; case 21: object num21 = sub.ReadElementContentAsBase64(b, 0, 2); break; case 22: object num22 = sub.ReadElementContentAsBinHex(b, 0, 2); break; case 23: sub.Read(); object num23 = sub.ReadContentAsBase64(b, 0, 2); break; case 24: sub.Read(); object num24 = sub.ReadContentAsBinHex(b, 0, 2); break; } } catch (InvalidOperationException) { return TEST_PASS; } catch (XmlException) { return TEST_PASS; } if (param == 24 || param == 23) return TEST_PASS; } catch (NotSupportedException) { return TEST_PASS; } } } return TEST_FAIL; } [Variation("SubtreeReader has empty namespace")] public int v101() { string xml = @"<a xmlns:f='urn:foobar' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" + "<b><c xsi:type='f:mytype'>some content</c></b></a>"; ReloadSourceStr(xml); DataReader.Read(); CError.Compare(DataReader.Name, "a", "a"); DataReader.Read(); CError.Compare(DataReader.Name, "b", "b"); using (XmlReader subtree = DataReader.ReadSubtree()) { subtree.Read(); CError.Compare(subtree.Name, "b", "b2"); subtree.Read(); CError.Compare(subtree.Name, "c", "c"); subtree.MoveToAttribute("type", "http://www.w3.org/2001/XMLSchema-instance"); CError.Compare(subtree.Value, "f:mytype", "value"); string ns = subtree.LookupNamespace("f"); if (ns == null) { return TEST_PASS; } } return TEST_FAIL; } [Variation("ReadValueChunk on an xmlns attribute that has been added by the subtree reader")] public int v102() { char[] c = new char[10]; string xml = @"<a xmlns:f='urn:foobar' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" + "<b><c xsi:type='f:mytype'>some content</c></b></a>"; ReloadSourceStr(xml); DataReader.Read(); using (XmlReader subtree = DataReader.ReadSubtree()) { subtree.Read(); CError.Compare(subtree.Name, "a", "a"); string s = subtree[0]; CError.Compare(s, "urn:foobar", "urn:foobar"); CError.Compare(subtree.LookupNamespace("xmlns"), "http://www.w3.org/2000/xmlns/", "xmlns"); CError.Compare(subtree.MoveToFirstAttribute(), "True"); try { CError.Compare(subtree.ReadValueChunk(c, 0, 10), 10, "ReadValueChunk"); CError.Compare(c[0].ToString(), "u", "u"); CError.Compare(c[9].ToString(), "r", "r"); } catch (NotSupportedException) { if (IsCustomReader() || IsCharCheckingReader()) return TEST_PASS; } } return TEST_PASS; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** <OWNER>[....]</OWNER> ** ** Class: File ** ** ** Purpose: A collection of methods for manipulating Files. ** ** April 09,2000 (some design refactorization) ** ===========================================================*/ using System; #if FEATURE_MACL using System.Security.AccessControl; #endif using System.Security.Permissions; using PermissionSet = System.Security.PermissionSet; using Win32Native = Microsoft.Win32.Win32Native; using System.Runtime.InteropServices; using System.Text; using System.Runtime.Serialization; using System.Globalization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System.IO { // Class for creating FileStream objects, and some basic file management // routines such as Delete, etc. [Serializable] [ComVisible(true)] public sealed class FileInfo: FileSystemInfo { private String _name; #if FEATURE_CORECLR // Migrating InheritanceDemands requires this default ctor, so we can annotate it. #if FEATURE_CORESYSTEM [System.Security.SecurityCritical] #else [System.Security.SecuritySafeCritical] #endif //FEATURE_CORESYSTEM private FileInfo(){} [System.Security.SecurityCritical] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public static FileInfo UnsafeCreateFileInfo(String fileName) { if (fileName == null) throw new ArgumentNullException("fileName"); Contract.EndContractBlock(); FileInfo fi = new FileInfo(); fi.Init(fileName, false); return fi; } #endif [System.Security.SecuritySafeCritical] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public FileInfo(String fileName) { if (fileName == null) throw new ArgumentNullException("fileName"); Contract.EndContractBlock(); #if FEATURE_LEGACYNETCF if(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { System.Reflection.Assembly callingAssembly = System.Reflection.Assembly.GetCallingAssembly(); if(callingAssembly != null && !callingAssembly.IsProfileAssembly) { string caller = new System.Diagnostics.StackFrame(1).GetMethod().FullName; string callee = System.Reflection.MethodBase.GetCurrentMethod().FullName; throw new MethodAccessException(String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Arg_MethodAccessException_WithCaller"), caller, callee)); } } #endif // FEATURE_LEGACYNETCF Init(fileName, true); } [System.Security.SecurityCritical] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] private void Init(String fileName, bool checkHost) { OriginalPath = fileName; // Must fully qualify the path for the security check String fullPath = Path.GetFullPathInternal(fileName); #if !MONO #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, fileName, fullPath); state.EnsureState(); } #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false); #endif #endif _name = Path.GetFileName(fileName); FullPath = fullPath; DisplayPath = GetDisplayPath(fileName); } private String GetDisplayPath(String originalPath) { #if FEATURE_CORECLR return Path.GetFileName(originalPath); #else return originalPath; #endif } [System.Security.SecurityCritical] // auto-generated private FileInfo(SerializationInfo info, StreamingContext context) : base(info, context) { #if !DISABLE_CAS_USE #if !FEATURE_CORECLR new FileIOPermission(FileIOPermissionAccess.Read, new String[] { FullPath }, false, false).Demand(); #endif #endif _name = Path.GetFileName(OriginalPath); DisplayPath = GetDisplayPath(OriginalPath); } #if FEATURE_CORESYSTEM [System.Security.SecuritySafeCritical] #endif //FEATURE_CORESYSTEM internal FileInfo(String fullPath, bool ignoreThis) { #if !MONO Contract.Assert(Path.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!"); #endif _name = Path.GetFileName(fullPath); OriginalPath = _name; FullPath = fullPath; DisplayPath = _name; } public override String Name { get { return _name; } } public long Length { [System.Security.SecuritySafeCritical] // auto-generated get { if (_dataInitialised == -1) Refresh(); if (_dataInitialised != 0) // Refresh was unable to initialise the data __Error.WinIOError(_dataInitialised, DisplayPath); if ((_data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) != 0) __Error.WinIOError(Win32Native.ERROR_FILE_NOT_FOUND, DisplayPath); #if MONO return _data.Length; #else return ((long)_data.fileSizeHigh) << 32 | ((long)_data.fileSizeLow & 0xFFFFFFFFL); #endif } } /* Returns the name of the directory that the file is in */ public String DirectoryName { [System.Security.SecuritySafeCritical] get { String directoryName = Path.GetDirectoryName(FullPath); if (directoryName != null) { #if !DISABLE_CAS_USE #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, DisplayPath, FullPath); state.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { directoryName }, false, false).Demand(); #endif #endif } return directoryName; } } /* Creates an instance of the the parent directory */ public DirectoryInfo Directory { [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] get { String dirName = DirectoryName; if (dirName == null) return null; return new DirectoryInfo(dirName); } } public bool IsReadOnly { get { return (Attributes & FileAttributes.ReadOnly) != 0; } set { if (value) Attributes |= FileAttributes.ReadOnly; else Attributes &= ~FileAttributes.ReadOnly; } } #if FEATURE_MACL [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] public FileSecurity GetAccessControl() { return File.GetAccessControl(FullPath, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); } [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] public FileSecurity GetAccessControl(AccessControlSections includeSections) { return File.GetAccessControl(FullPath, includeSections); } [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] public void SetAccessControl(FileSecurity fileSecurity) { File.SetAccessControl(FullPath, fileSecurity); } #endif [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public StreamReader OpenText() { return new StreamReader(FullPath, Encoding.UTF8, true, StreamReader.DefaultBufferSize, false); } [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public StreamWriter CreateText() { return new StreamWriter(FullPath,false); } [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public StreamWriter AppendText() { return new StreamWriter(FullPath,true); } // Copies an existing file to a new file. An exception is raised if the // destination file already exists. Use the // Copy(String, String, boolean) method to allow // overwriting an existing file. // // The caller must have certain FileIOPermissions. The caller must have // Read permission to sourceFileName // and Write permissions to destFileName. // [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public FileInfo CopyTo(String destFileName) { if (destFileName == null) throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName")); if (destFileName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName"); Contract.EndContractBlock(); destFileName = File.InternalCopy(FullPath, destFileName, false, true); return new FileInfo(destFileName, false); } // Copies an existing file to a new file. If overwrite is // false, then an IOException is thrown if the destination file // already exists. If overwrite is true, the file is // overwritten. // // The caller must have certain FileIOPermissions. The caller must have // Read permission to sourceFileName and Create // and Write permissions to destFileName. // [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public FileInfo CopyTo(String destFileName, bool overwrite) { if (destFileName == null) throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName")); if (destFileName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName"); Contract.EndContractBlock(); destFileName = File.InternalCopy(FullPath, destFileName, overwrite, true); return new FileInfo(destFileName, false); } [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] public FileStream Create() { return File.Create(FullPath); } // Deletes a file. The file specified by the designated path is deleted. // If the file does not exist, Delete succeeds without throwing // an exception. // // On NT, Delete will fail for a file that is open for normal I/O // or a file that is memory mapped. On Win95, the file will be // deleted irregardless of whether the file is being used. // // Your application must have Delete permission to the target file. // [System.Security.SecuritySafeCritical] [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] public override void Delete() { #if !DISABLE_CAS_USE #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, DisplayPath, FullPath); state.EnsureState(); #else // For security check, path should be resolved to an absolute path. new FileIOPermission(FileIOPermissionAccess.Write, new String[] { FullPath }, false, false).Demand(); #endif #endif #if MONO MonoIOError error; if (MonoIO.ExistsDirectory (FullPath, out error)) __Error.WinIOError (Win32Native.ERROR_ACCESS_DENIED, DisplayPath); if (!MonoIO.DeleteFile (FullPath, out error)) { int hr = (int) error; #else bool r = Win32Native.DeleteFile(FullPath); if (!r) { int hr = Marshal.GetLastWin32Error(); #endif if (hr==Win32Native.ERROR_FILE_NOT_FOUND) return; else __Error.WinIOError(hr, DisplayPath); } } [ComVisible(false)] [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] public void Decrypt() { File.Decrypt(FullPath); } [ComVisible(false)] [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] public void Encrypt() { File.Encrypt(FullPath); } // Tests if the given file exists. The result is true if the file // given by the specified path exists; otherwise, the result is // false. // // Your application must have Read permission for the target directory. public override bool Exists { [System.Security.SecuritySafeCritical] // auto-generated get { try { if (_dataInitialised == -1) Refresh(); if (_dataInitialised != 0) { // Refresh was unable to initialise the data. // We should normally be throwing an exception here, // but Exists is supposed to return true or false. return false; } return (_data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) == 0; } catch { return false; } } } // User must explicitly specify opening a new file or appending to one. [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public FileStream Open(FileMode mode) { return Open(mode, FileAccess.ReadWrite, FileShare.None); } [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public FileStream Open(FileMode mode, FileAccess access) { return Open(mode, access, FileShare.None); } [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public FileStream Open(FileMode mode, FileAccess access, FileShare share) { return new FileStream(FullPath, mode, access, share); } #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] // auto-generated #endif [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public FileStream OpenRead() { return new FileStream(FullPath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, false); } [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public FileStream OpenWrite() { return new FileStream(FullPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); } // Moves a given file to a new location and potentially a new file name. // This method does work across volumes. // // The caller must have certain FileIOPermissions. The caller must // have Read and Write permission to // sourceFileName and Write // permissions to destFileName. // [System.Security.SecuritySafeCritical] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public void MoveTo(String destFileName) { if (destFileName==null) throw new ArgumentNullException("destFileName"); if (destFileName.Length==0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName"); Contract.EndContractBlock(); String fullDestFileName = Path.GetFullPathInternal(destFileName); #if !MONO #if FEATURE_CORECLR FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, DisplayPath, FullPath); FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName); sourceState.EnsureState(); destState.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, new String[] { FullPath }, false, false).Demand(); FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false); #endif #endif #if MONO MonoIOError error; if (!MonoIO.MoveFile (FullPath, fullDestFileName, out error)) __Error.WinIOError ((int) error, String.Empty); #else if (!Win32Native.MoveFile(FullPath, fullDestFileName)) __Error.WinIOError(); #endif FullPath = fullDestFileName; OriginalPath = destFileName; _name = Path.GetFileName(fullDestFileName); DisplayPath = GetDisplayPath(destFileName); // Flush any cached information about the file. _dataInitialised = -1; } [ComVisible(false)] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public FileInfo Replace(String destinationFileName, String destinationBackupFileName) { return Replace(destinationFileName, destinationBackupFileName, false); } [ComVisible(false)] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public FileInfo Replace(String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors) { File.Replace(FullPath, destinationFileName, destinationBackupFileName, ignoreMetadataErrors); return new FileInfo(destinationFileName); } // Returns the display path public override String ToString() { return DisplayPath; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization.Infrastructure; namespace Microsoft.AspNetCore.Authorization { /// <summary> /// Used for building policies. /// </summary> public class AuthorizationPolicyBuilder { /// <summary> /// Creates a new instance of <see cref="AuthorizationPolicyBuilder"/> /// </summary> /// <param name="authenticationSchemes">An array of authentication schemes the policy should be evaluated against.</param> public AuthorizationPolicyBuilder(params string[] authenticationSchemes) { AddAuthenticationSchemes(authenticationSchemes); } /// <summary> /// Creates a new instance of <see cref="AuthorizationPolicyBuilder"/>. /// </summary> /// <param name="policy">The <see cref="AuthorizationPolicy"/> to copy.</param> public AuthorizationPolicyBuilder(AuthorizationPolicy policy) { Combine(policy); } /// <summary> /// Gets or sets a list of <see cref="IAuthorizationRequirement"/>s which must succeed for /// this policy to be successful. /// </summary> public IList<IAuthorizationRequirement> Requirements { get; set; } = new List<IAuthorizationRequirement>(); /// <summary> /// Gets or sets a list authentication schemes the <see cref="AuthorizationPolicyBuilder.Requirements"/> /// are evaluated against. /// <para> /// When not specified, the requirements are evaluated against default schemes. /// </para> /// </summary> public IList<string> AuthenticationSchemes { get; set; } = new List<string>(); /// <summary> /// Adds the specified authentication <paramref name="schemes"/> to the /// <see cref="AuthorizationPolicyBuilder.AuthenticationSchemes"/> for this instance. /// </summary> /// <param name="schemes">The schemes to add.</param> /// <returns>A reference to this instance after the operation has completed.</returns> public AuthorizationPolicyBuilder AddAuthenticationSchemes(params string[] schemes) { foreach (var authType in schemes) { AuthenticationSchemes.Add(authType); } return this; } /// <summary> /// Adds the specified <paramref name="requirements"/> to the /// <see cref="AuthorizationPolicyBuilder.Requirements"/> for this instance. /// </summary> /// <param name="requirements">The authorization requirements to add.</param> /// <returns>A reference to this instance after the operation has completed.</returns> public AuthorizationPolicyBuilder AddRequirements(params IAuthorizationRequirement[] requirements) { foreach (var req in requirements) { Requirements.Add(req); } return this; } /// <summary> /// Combines the specified <paramref name="policy"/> into the current instance. /// </summary> /// <param name="policy">The <see cref="AuthorizationPolicy"/> to combine.</param> /// <returns>A reference to this instance after the operation has completed.</returns> public AuthorizationPolicyBuilder Combine(AuthorizationPolicy policy) { if (policy == null) { throw new ArgumentNullException(nameof(policy)); } AddAuthenticationSchemes(policy.AuthenticationSchemes.ToArray()); AddRequirements(policy.Requirements.ToArray()); return this; } /// <summary> /// Adds a <see cref="ClaimsAuthorizationRequirement"/> to the current instance which requires /// that the current user has the specified claim and that the claim value must be one of the allowed values. /// </summary> /// <param name="claimType">The claim type required.</param> /// <param name="allowedValues">Values the claim must process one or more of for evaluation to succeed.</param> /// <returns>A reference to this instance after the operation has completed.</returns> public AuthorizationPolicyBuilder RequireClaim(string claimType, params string[] allowedValues) { if (claimType == null) { throw new ArgumentNullException(nameof(claimType)); } return RequireClaim(claimType, (IEnumerable<string>)allowedValues); } /// <summary> /// Adds a <see cref="ClaimsAuthorizationRequirement"/> to the current instance which requires /// that the current user has the specified claim and that the claim value must be one of the allowed values. /// </summary> /// <param name="claimType">The claim type required.</param> /// <param name="allowedValues">Values the claim must process one or more of for evaluation to succeed.</param> /// <returns>A reference to this instance after the operation has completed.</returns> public AuthorizationPolicyBuilder RequireClaim(string claimType, IEnumerable<string> allowedValues) { if (claimType == null) { throw new ArgumentNullException(nameof(claimType)); } Requirements.Add(new ClaimsAuthorizationRequirement(claimType, allowedValues)); return this; } /// <summary> /// Adds a <see cref="ClaimsAuthorizationRequirement"/> to the current instance which requires /// that the current user has the specified claim. /// </summary> /// <param name="claimType">The claim type required, with no restrictions on claim value.</param> /// <returns>A reference to this instance after the operation has completed.</returns> public AuthorizationPolicyBuilder RequireClaim(string claimType) { if (claimType == null) { throw new ArgumentNullException(nameof(claimType)); } Requirements.Add(new ClaimsAuthorizationRequirement(claimType, allowedValues: null)); return this; } /// <summary> /// Adds a <see cref="RolesAuthorizationRequirement"/> to the current instance which enforces that the current user /// must have at least one of the specified roles. /// </summary> /// <param name="roles">The allowed roles.</param> /// <returns>A reference to this instance after the operation has completed.</returns> public AuthorizationPolicyBuilder RequireRole(params string[] roles) { if (roles == null) { throw new ArgumentNullException(nameof(roles)); } return RequireRole((IEnumerable<string>)roles); } /// <summary> /// Adds a <see cref="RolesAuthorizationRequirement"/> to the current instance which enforces that the current user /// must have at least one of the specified roles. /// </summary> /// <param name="roles">The allowed roles.</param> /// <returns>A reference to this instance after the operation has completed.</returns> public AuthorizationPolicyBuilder RequireRole(IEnumerable<string> roles) { if (roles == null) { throw new ArgumentNullException(nameof(roles)); } Requirements.Add(new RolesAuthorizationRequirement(roles)); return this; } /// <summary> /// Adds a <see cref="NameAuthorizationRequirement"/> to the current instance which enforces that the current user matches the specified name. /// </summary> /// <param name="userName">The user name the current user must possess.</param> /// <returns>A reference to this instance after the operation has completed.</returns> public AuthorizationPolicyBuilder RequireUserName(string userName) { if (userName == null) { throw new ArgumentNullException(nameof(userName)); } Requirements.Add(new NameAuthorizationRequirement(userName)); return this; } /// <summary> /// Adds <see cref="DenyAnonymousAuthorizationRequirement"/> to the current instance which enforces that the current user is authenticated. /// </summary> /// <returns>A reference to this instance after the operation has completed.</returns> public AuthorizationPolicyBuilder RequireAuthenticatedUser() { Requirements.Add(new DenyAnonymousAuthorizationRequirement()); return this; } /// <summary> /// Adds an <see cref="AssertionRequirement"/> to the current instance. /// </summary> /// <param name="handler">The handler to evaluate during authorization.</param> /// <returns>A reference to this instance after the operation has completed.</returns> public AuthorizationPolicyBuilder RequireAssertion(Func<AuthorizationHandlerContext, bool> handler) { if (handler == null) { throw new ArgumentNullException(nameof(handler)); } Requirements.Add(new AssertionRequirement(handler)); return this; } /// <summary> /// Adds an <see cref="AssertionRequirement"/> to the current instance. /// </summary> /// <param name="handler">The handler to evaluate during authorization.</param> /// <returns>A reference to this instance after the operation has completed.</returns> public AuthorizationPolicyBuilder RequireAssertion(Func<AuthorizationHandlerContext, Task<bool>> handler) { if (handler == null) { throw new ArgumentNullException(nameof(handler)); } Requirements.Add(new AssertionRequirement(handler)); return this; } /// <summary> /// Builds a new <see cref="AuthorizationPolicy"/> from the requirements /// in this instance. /// </summary> /// <returns> /// A new <see cref="AuthorizationPolicy"/> built from the requirements in this instance. /// </returns> public AuthorizationPolicy Build() { return new AuthorizationPolicy(Requirements, AuthenticationSchemes.Distinct()); } } }
#region Using directives #define USE_TRACING using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Reflection; using System.Text; using System.Xml; #endregion namespace Google.GData.Client { /// <summary>String utilities /// </summary> public sealed class Utilities { /// <summary> /// xsd version of bool:true /// </summary> public const string XSDTrue = "true"; /// <summary> /// xsd version of bool:false /// </summary> public const string XSDFalse = "false"; /// <summary> /// default user string /// </summary> public const string DefaultUser = "default"; /// <summary>private constructor to prevent the compiler from generating a default one</summary> private Utilities() { } /// <summary>returns a blank emptyDate. That's the default for an empty string date</summary> public static DateTime EmptyDate { get { // that's the blank value you get when setting a DateTime to an empty string inthe property browswer return new DateTime(1, 1, 1); } } /// <summary>Little helper that checks if a string is XML persistable</summary> public static bool IsPersistable(string toPersist) { if (!string.IsNullOrEmpty(toPersist) && toPersist.Trim().Length != 0) { return true; } return false; } /// <summary>Little helper that checks if a string is XML persistable</summary> public static bool IsPersistable(AtomUri uriString) { return uriString == null ? false : IsPersistable(uriString.ToString()); } /// <summary>Little helper that checks if an int is XML persistable</summary> public static bool IsPersistable(int number) { return number == 0 ? false : true; } /// <summary>Little helper that checks if a datevalue is XML persistable</summary> public static bool IsPersistable(DateTime testDate) { return testDate == EmptyDate ? false : true; } /// <summary> /// .NET treats bool as True/False as the default /// string representation. XSD requires true/false /// this method encapsulates this /// </summary> /// <param name="flag">the boolean to convert</param> /// <returns>"true" or "false"</returns> public static string ConvertBooleanToXSDString(bool flag) { return flag ? XSDTrue : XSDFalse; } /// <summary> /// .NET treats bool as True/False as the default /// string representation. XSD requires true/false /// this method encapsulates this /// </summary> /// <param name="obj">the object to convert</param> /// <returns>the string representation</returns> public static string ConvertToXSDString(object obj) { if (obj is bool) { return ConvertBooleanToXSDString((bool) obj); } return Convert.ToString(obj, CultureInfo.InvariantCulture); } /// <summary>helper to read in a string and encode it</summary> /// <param name="content">the xmlreader string</param> /// <returns>UTF8 encoded string</returns> public static string EncodeString(string content) { // get the encoding Encoding utf8Encoder = Encoding.UTF8; byte[] utf8Bytes = EncodeStringToUtf8(content); char[] utf8Chars = new char[utf8Encoder.GetCharCount(utf8Bytes, 0, utf8Bytes.Length)]; utf8Encoder.GetChars(utf8Bytes, 0, utf8Bytes.Length, utf8Chars, 0); string utf8String = new string(utf8Chars); return utf8String; } /// <summary> /// returns you a bytearray of UTF8 bytes from the string passed in /// the passed in string is assumed to be UTF16 /// </summary> /// <param name="content">UTF16 string</param> /// <returns>utf 8 byte array</returns> public static byte[] EncodeStringToUtf8(string content) { // get the encoding Encoding utf8Encoder = Encoding.UTF8; Encoding utf16Encoder = Encoding.Unicode; byte[] bytes = utf16Encoder.GetBytes(content); byte[] utf8Bytes = Encoding.Convert(utf16Encoder, utf8Encoder, bytes); return utf8Bytes; } /// <summary>helper to read in a string and Encode it according to /// RFC 5023 rules for slugheaders</summary> /// <param name="slug">the Unicode string for the slug header</param> /// <returns>ASCII encoded string</returns> public static string EncodeSlugHeader(string slug) { if (slug == null) { return ""; } byte[] bytes = EncodeStringToUtf8(slug); if (bytes == null) { return ""; } StringBuilder returnString = new StringBuilder(256); foreach (byte b in bytes) { if ((b < 0x20) || (b == 0x25) || (b > 0x7E)) { returnString.AppendFormat(CultureInfo.InvariantCulture, "%{0:X}", b); } else { returnString.Append((char) b); } } return returnString.ToString(); } /// <summary> /// used as a cover method to hide the actual decoding implementation /// decodes an html decoded string /// </summary> /// <param name="value">the string to decode</param> public static string DecodedValue(string value) { return HttpUtility.HtmlDecode(value); } /// <summary> /// used as a cover method to hide the actual decoding implementation /// decodes an URL decoded string /// </summary> /// <param name="value">the string to decode</param> public static string UrlDecodedValue(string value) { return HttpUtility.UrlDecode(value); } /// <summary>helper to read in a string and replace the reserved URI /// characters with hex encoding</summary> /// <param name="content">the parameter string</param> /// <returns>hex encoded string</returns> public static string UriEncodeReserved(string content) { if (content == null) { return null; } StringBuilder returnString = new StringBuilder(256); foreach (char ch in content) { if (ch == ';' || ch == '/' || ch == '?' || ch == ':' || ch == '@' || ch == '&' || ch == '=' || ch == '+' || ch == '$' || ch == ',' || ch == '#' || ch == '%') { returnString.Append(Uri.HexEscape(ch)); } else { returnString.Append(ch); } } return returnString.ToString(); } /// <summary> /// tests an etag for weakness. returns TRUE for weak etags and for null strings /// </summary> /// <param name="eTag"></param> /// <returns></returns> public static bool IsWeakETag(string eTag) { if (eTag == null) { return true; } return eTag.StartsWith("W/"); } /// <summary> /// tests an etag for weakness. returns TRUE for weak etags and for null strings /// </summary> /// <param name="ise">the element that supports an etag</param> /// <returns></returns> public static bool IsWeakETag(ISupportsEtag ise) { string eTag = null; if (ise != null) { eTag = ise.Etag; } return IsWeakETag(eTag); } /// <summary>helper to read in a string and replace the reserved URI /// characters with hex encoding</summary> /// <param name="content">the parameter string</param> /// <returns>hex encoded string</returns> public static string UriEncodeUnsafe(string content) { if (content == null) { return null; } StringBuilder returnString = new StringBuilder(256); foreach (char ch in content) { if (ch == ';' || ch == '/' || ch == '?' || ch == ':' || ch == '@' || ch == '&' || ch == '=' || ch == '+' || ch == '$' || ch == ',' || ch == ' ' || ch == '\'' || ch == '"' || ch == '>' || ch == '<' || ch == '#' || ch == '%') { returnString.Append(Uri.HexEscape(ch)); } else { returnString.Append(ch); } } return returnString.ToString(); } /// <summary>Method to output just the date portion as string</summary> /// <param name="dateTime">the DateTime object to output as a string</param> /// <returns>an rfc-3339 string</returns> public static string LocalDateInUTC(DateTime dateTime) { // Add "full-date T partial-time" return dateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); } /// <summary>Method to output DateTime as string</summary> /// <param name="dateTime">the DateTime object to output as a string</param> /// <returns>an rfc-3339 string</returns> public static string LocalDateTimeInUTC(DateTime dateTime) { TimeSpan diffFromUtc = TimeZone.CurrentTimeZone.GetUtcOffset(dateTime); // Add "full-date T partial-time" string strOutput = dateTime.ToString("s", CultureInfo.InvariantCulture); // Add "time-offset" return strOutput + FormatTimeOffset(diffFromUtc); } /// <summary> /// returns the next child element of the xml reader, based on the /// depth passed in. /// </summary> /// <param name="reader">the xml reader to use</param> /// <param name="depth">the depth to start with</param> /// <returns></returns> public static bool NextChildElement(XmlReader reader, ref int depth) { Tracing.Assert(reader != null, "reader should not be null"); if (reader == null) { throw new ArgumentNullException("reader"); } if (reader.Depth == depth) { // assume we gone around circle, a child read and moved to the next element of the same KIND return false; } if (reader.NodeType == XmlNodeType.Element && depth >= 0 && reader.Depth > depth) { // assume we gone around circle, a child read and moved to the next element of the same KIND // but now we are in the parent/containing element, hence we return TRUE without reading further return true; } if (depth == -1) { depth = reader.Depth; } while (reader.Read()) { if (reader.NodeType == XmlNodeType.EndElement && reader.Depth <= depth) { return false; } if (reader.NodeType == XmlNodeType.Element && reader.Depth > depth) { return true; } if (reader.NodeType == XmlNodeType.Element && reader.Depth == depth) { // assume that we had no children. We read once and we are at the // next element, same level as the previous one. return false; } } return !reader.EOF; } /// <summary>Helper method to format a TimeSpan as a string compliant with the "time-offset" format defined in RFC-3339</summary> /// <param name="spanFromUtc">the TimeSpan to format</param> /// <returns></returns> public static string FormatTimeOffset(TimeSpan spanFromUtc) { // Simply return "Z" if there is no offset if (spanFromUtc == TimeSpan.Zero) return "Z"; // Return the numeric offset TimeSpan absoluteSpan = spanFromUtc.Duration(); if (spanFromUtc > TimeSpan.Zero) { return "+" + FormatNumOffset(absoluteSpan); } return "-" + FormatNumOffset(absoluteSpan); } /// <summary>Helper method to format a TimeSpan to {HH}:{MM}</summary> /// <param name="timeSpan">the TimeSpan to format</param> /// <returns>a string in "hh:mm" format.</returns> internal static string FormatNumOffset(TimeSpan timeSpan) { return string.Format(CultureInfo.InvariantCulture, "{0:00}:{1:00}", timeSpan.Hours, timeSpan.Minutes); } /// <summary>public static string CalculateUri(string base, string inheritedBase, string local)</summary> /// <param name="localBase">the baseUri from xml:base </param> /// <param name="inheritedBase">the pushed down baseUri from an outer element</param> /// <param name="localUri">the Uri value</param> /// <returns>the absolute Uri to use... </returns> internal static string CalculateUri(AtomUri localBase, AtomUri inheritedBase, string localUri) { try { Uri uriBase = null; Uri uriSuperBase = null; Uri uriComplete = null; if (inheritedBase != null && inheritedBase.ToString() != null) { uriSuperBase = new Uri(inheritedBase.ToString()); } if (localBase != null && localBase.ToString() != null) { if (uriSuperBase != null) { uriBase = new Uri(uriSuperBase, localBase.ToString()); } else { uriBase = new Uri(localBase.ToString()); } } else { // if no local xml:base, take the passed down one uriBase = uriSuperBase; } if (localUri != null) { if (uriBase != null) { uriComplete = new Uri(uriBase, localUri); } else { uriComplete = new Uri(localUri); } } else { uriComplete = uriBase; } return uriComplete != null ? uriComplete.AbsoluteUri : null; } catch (UriFormatException) { return "Unsupported URI format"; } } /// <summary>Sets the Atom namespace, if it's not already set. /// </summary> /// <param name="writer"> the xmlwriter to use</param> /// <returns> the namespace prefix</returns> public static string EnsureAtomNamespace(XmlWriter writer) { Tracing.Assert(writer != null, "writer should not be null"); if (writer == null) { throw new ArgumentNullException("writer"); } string strPrefix = writer.LookupPrefix(BaseNameTable.NSAtom); if (strPrefix == null) { writer.WriteAttributeString("xmlns", null, BaseNameTable.NSAtom); } return strPrefix; } /// <summary>Sets the gData namespace, if it's not already set. /// </summary> /// <param name="writer"> the xmlwriter to use</param> /// <returns> the namespace prefix</returns> public static string EnsureGDataNamespace(XmlWriter writer) { Tracing.Assert(writer != null, "writer should not be null"); if (writer == null) { throw new ArgumentNullException("writer"); } string strPrefix = writer.LookupPrefix(BaseNameTable.gNamespace); if (strPrefix == null) { writer.WriteAttributeString("xmlns", BaseNameTable.gDataPrefix, null, BaseNameTable.gNamespace); } return strPrefix; } /// <summary>Sets the gDataBatch namespace, if it's not already set. /// </summary> /// <param name="writer"> the xmlwriter to use</param> /// <returns> the namespace prefix</returns> public static string EnsureGDataBatchNamespace(XmlWriter writer) { Tracing.Assert(writer != null, "writer should not be null"); if (writer == null) { throw new ArgumentNullException("writer"); } string strPrefix = writer.LookupPrefix(BaseNameTable.gBatchNamespace); if (strPrefix == null) { writer.WriteAttributeString("xmlns", BaseNameTable.gBatchPrefix, null, BaseNameTable.gBatchNamespace); } return strPrefix; } /// <summary>searches tokenCollection for a specific NEXT value. /// The collection is assume to be a key/value pair list, so if A,B,C,D is the list /// A and C are keys, B and D are values /// </summary> /// <param name="tokens">the TokenCollection to search</param> /// <param name="key">the key to search for</param> /// <returns> the value string</returns> public static string FindToken(TokenCollection tokens, string key) { if (tokens == null) { throw new ArgumentNullException("tokens"); } string returnValue = null; bool fNextOne = false; foreach (string token in tokens) { if (fNextOne) { returnValue = token; break; } if (key == token) { // next one is it fNextOne = true; } } return returnValue; } /// <summary>converts a form response stream to a TokenCollection, /// by parsing the contents of the stream for newlines and equal signs /// the input stream is assumed to be an ascii encoded form resonse /// </summary> /// <param name="inputStream">the stream to read and parse</param> /// <returns> the resulting TokenCollection </returns> public static TokenCollection ParseStreamInTokenCollection(Stream inputStream) { // get the body and parse it ASCIIEncoding encoder = new ASCIIEncoding(); StreamReader readStream = new StreamReader(inputStream, encoder); string body = readStream.ReadToEnd(); readStream.Close(); Tracing.TraceMsg("got the following body back: " + body); // all we are interested is the token, so we break the string in parts TokenCollection tokens = new TokenCollection(body, '=', true, 2); return tokens; } /// <summary>parses a form response stream in token form for a specific value /// </summary> /// <param name="inputStream">the stream to read and parse</param> /// <param name="key">the key to search for</param> /// <returns> the string in the tokenized stream </returns> public static string ParseValueFormStream(Stream inputStream, string key) { TokenCollection tokens = ParseStreamInTokenCollection(inputStream); return FindToken(tokens, key); } /// <summary> /// Finds a specific ExtensionElement based on it's local name /// and it's namespace. If namespace is NULL, the first one where /// the localname matches is found. If there are extensionelements that do /// not implment ExtensionElementFactory, they will not be taken into account /// Primary use of this is to find XML nodes /// </summary> /// <param name="arrList">the array to search through</param> /// <param name="localName">the xml local name of the element to find</param> /// <param name="ns">the namespace of the elementToPersist</param> /// <returns>Object</returns> public static IExtensionElementFactory FindExtension(ExtensionList arrList, string localName, string ns) { if (arrList == null) { return null; } foreach (IExtensionElementFactory ele in arrList) { if (compareXmlNess(ele.XmlName, localName, ele.XmlNameSpace, ns)) { return ele; } } return null; } /// <summary> /// Finds all ExtensionElement based on it's local name /// and it's namespace. If namespace is NULL, allwhere /// the localname matches is found. If there are extensionelements that do /// not implment ExtensionElementFactory, they will not be taken into account /// Primary use of this is to find XML nodes /// </summary> /// <param name="arrList">the array to search through</param> /// <param name="localName">the xml local name of the element to find</param> /// <param name="ns">the namespace of the elementToPersist</param> /// <param name="arr">the array to fill</param> /// <returns>none</returns> public static ExtensionList FindExtensions(ExtensionList arrList, string localName, string ns, ExtensionList arr) { if (arrList == null) { throw new ArgumentNullException("arrList"); } if (arr == null) { throw new ArgumentNullException("arr"); } foreach (IExtensionElementFactory ob in arrList) { XmlNode node = ob as XmlNode; if (node != null) { if (compareXmlNess(node.LocalName, localName, node.NamespaceURI, ns)) { arr.Add(ob); } } else { // only if the elements do implement the ExtensionElementFactory // do we know if it's xml name/namespace IExtensionElementFactory ele = ob; if (ele != null) { if (compareXmlNess(ele.XmlName, localName, ele.XmlNameSpace, ns)) { arr.Add(ob); } } } } return arr; } /// <summary> /// Finds all ExtensionElement based on it's local name /// and it's namespace. If namespace is NULL, allwhere /// the localname matches is found. If there are extensionelements that do /// not implment ExtensionElementFactory, they will not be taken into account /// Primary use of this is to find XML nodes /// </summary> /// <param name="arrList">the array to search through</param> /// <param name="localName">the xml local name of the element to find</param> /// <param name="ns">the namespace of the elementToPersist</param> /// <returns>none</returns> public static List<T> FindExtensions<T>(ExtensionList arrList, string localName, string ns) where T : IExtensionElementFactory { List<T> list = new List<T>(); if (arrList == null) { throw new ArgumentNullException("arrList"); } foreach (IExtensionElementFactory obj in arrList) { if (obj is T) { T ele = (T) obj; // only if the elements do implement the ExtensionElementFactory // do we know if it's xml name/namespace if (ele != null) { if (compareXmlNess(ele.XmlName, localName, ele.XmlNameSpace, ns)) { list.Add(ele); } } } } return list; } /// <summary> /// save method to get an attribute value from an xmlnode /// </summary> /// <param name="attributeName"></param> /// <param name="xmlNode"></param> /// <returns></returns> public static string GetAttributeValue(string attributeName, XmlNode xmlNode) { if (xmlNode != null && attributeName != null && xmlNode.Attributes != null && xmlNode.Attributes[attributeName] != null) { return xmlNode.Attributes[attributeName].Value; } return null; } /// <summary> /// returns the current assembly version using split() instead of the version /// attribute to avoid security issues /// </summary> /// <returns>the current assembly version as a string</returns> public static string GetAssemblyVersion() { Assembly asm = Assembly.GetExecutingAssembly(); if (asm != null) { string[] parts = asm.FullName.Split(','); if (parts != null && parts.Length > 1) return parts[1].Trim(); } return "1.0.0"; } /// <summary> /// returns the useragent string, including a version number /// </summary> /// <returns>the constructed userAgend in a standard form</returns> public static string ConstructUserAgent(string applicationName, string serviceName) { return "G-" + applicationName + "/" + serviceName + "-CS-" + GetAssemblyVersion(); } private static bool compareXmlNess(string l1, string l2, string ns1, string ns2) { if (string.Compare(l1, l2) == 0) { if (ns1 == null) { return true; } if (string.Compare(ns1, ns2) == 0) { return true; } } return false; } /// <summary>goes to the Google auth service, and gets a new auth token</summary> /// <returns>the auth token, or NULL if none received</returns> public static string QueryClientLoginToken(GDataCredentials gc, string serviceName, string applicationName, bool fUseKeepAlive, Uri clientLoginHandler) { return QueryClientLoginToken(gc, serviceName, applicationName, fUseKeepAlive, null, clientLoginHandler); } /// <summary>goes to the Google auth service, and gets a new auth token</summary> /// <returns>the auth token, or NULL if none received</returns> public static string QueryClientLoginToken(GDataCredentials gc, string serviceName, string applicationName, bool fUseKeepAlive, IWebProxy proxyServer, Uri clientLoginHandler) { Tracing.Assert(gc != null, "Do not call QueryAuthToken with no network credentials"); if (gc == null) { throw new ArgumentNullException("nc", "No credentials supplied"); } HttpWebRequest authRequest = WebRequest.Create(clientLoginHandler) as HttpWebRequest; authRequest.KeepAlive = fUseKeepAlive; if (proxyServer != null) { authRequest.Proxy = proxyServer; } string accountType = GoogleAuthentication.AccountType; if (!string.IsNullOrEmpty(gc.AccountType)) { accountType += gc.AccountType; } else { accountType += GoogleAuthentication.AccountTypeDefault; } WebResponse authResponse = null; HttpWebResponse response = null; string authToken = null; try { authRequest.ContentType = HttpFormPost.Encoding; authRequest.Method = HttpMethods.Post; ASCIIEncoding encoder = new ASCIIEncoding(); string user = gc.Username == null ? "" : gc.Username; string pwd = gc.getPassword() == null ? "" : gc.getPassword(); // now enter the data in the stream string postData = GoogleAuthentication.Email + "=" + UriEncodeUnsafe(user) + "&"; postData += GoogleAuthentication.Password + "=" + UriEncodeUnsafe(pwd) + "&"; postData += GoogleAuthentication.Source + "=" + UriEncodeUnsafe(applicationName) + "&"; postData += GoogleAuthentication.Service + "=" + UriEncodeUnsafe(serviceName) + "&"; if (gc.CaptchaAnswer != null) { postData += GoogleAuthentication.CaptchaAnswer + "=" + UriEncodeUnsafe(gc.CaptchaAnswer) + "&"; } if (gc.CaptchaToken != null) { postData += GoogleAuthentication.CaptchaToken + "=" + UriEncodeUnsafe(gc.CaptchaToken) + "&"; } postData += accountType; byte[] encodedData = encoder.GetBytes(postData); authRequest.ContentLength = encodedData.Length; Stream requestStream = authRequest.GetRequestStream(); requestStream.Write(encodedData, 0, encodedData.Length); requestStream.Close(); authResponse = authRequest.GetResponse(); response = authResponse as HttpWebResponse; } catch (WebException e) { response = e.Response as HttpWebResponse; if (response == null) { Tracing.TraceMsg("QueryAuthtoken failed " + e.Status + " " + e.Message); throw; } } if (response != null) { // check the content type, it must be text if (!response.ContentType.StartsWith(HttpFormPost.ReturnContentType)) { throw new GDataRequestException( "Execution of authentication request returned unexpected content type: " + response.ContentType, response); } TokenCollection tokens = ParseStreamInTokenCollection(response.GetResponseStream()); authToken = FindToken(tokens, GoogleAuthentication.AuthToken); if (authToken == null) { throw getAuthException(tokens, response); } // failsafe. if getAuthException did not catch an error... int code = (int) response.StatusCode; if (code != 200) { throw new GDataRequestException( "Execution of authentication request returned unexpected result: " + code, response); } } Tracing.Assert(authToken != null, "did not find an auth token in QueryAuthToken"); if (authResponse != null) { authResponse.Close(); } return authToken; } /// <summary> /// Returns the respective GDataAuthenticationException given the return /// values from the login URI handler. /// </summary> /// <param name="tokens">The tokencollection of the parsed return form</param> /// <param name="response">the webresponse</param> /// <returns>AuthenticationException</returns> private static LoggedException getAuthException(TokenCollection tokens, HttpWebResponse response) { string errorName = FindToken(tokens, "Error"); int code = (int) response.StatusCode; if (errorName == null || errorName.Length == 0) { // no error given by Gaia, return a standard GDataRequestException throw new GDataRequestException( "Execution of authentication request returned unexpected result: " + code, response); } if ("BadAuthentication".Equals(errorName)) { return new InvalidCredentialsException("Invalid credentials"); } if ("AccountDeleted".Equals(errorName)) { return new AccountDeletedException("Account deleted"); } if ("AccountDisabled".Equals(errorName)) { return new AccountDisabledException("Account disabled"); } if ("NotVerified".Equals(errorName)) { return new NotVerifiedException("Not verified"); } if ("TermsNotAgreed".Equals(errorName)) { return new TermsNotAgreedException("Terms not agreed"); } if ("ServiceUnavailable".Equals(errorName)) { return new ServiceUnavailableException("Service unavailable"); } if ("CaptchaRequired".Equals(errorName)) { string captchaPath = FindToken(tokens, "CaptchaUrl"); string captchaToken = FindToken(tokens, "CaptchaToken"); StringBuilder captchaUrl = new StringBuilder(); captchaUrl.Append(GoogleAuthentication.DefaultProtocol).Append("://"); captchaUrl.Append(GoogleAuthentication.DefaultDomain); captchaUrl.Append(GoogleAuthentication.AccountPrefix); captchaUrl.Append('/').Append(captchaPath); return new CaptchaRequiredException("Captcha required", captchaUrl.ToString(), captchaToken); } return new AuthenticationException("Error authenticating (check service name): " + errorName); } } /// <summary> /// standard string tokenizer class. Pretty much cut/copy/paste out of MSDN. /// </summary> public class TokenCollection : IEnumerable { private readonly string[] elements; /// <summary>Constructor, takes a string and a delimiter set</summary> public TokenCollection(string source, char[] delimiters) { if (source != null) { elements = source.Split(delimiters); } } /// <summary>Constructor, takes a string and a delimiter set</summary> public TokenCollection(string source, char delimiter, bool separateLines, int resultsPerLine) { if (source != null) { if (separateLines) { // first split the source into a line array string[] lines = source.Split('\n'); int size = lines.Length*resultsPerLine; elements = new string[size]; size = 0; foreach (string s in lines) { // do not use Split(char,int) as that one // does not exist on .NET CF string[] temp = s.Split(delimiter); int counter = temp.Length < resultsPerLine ? temp.Length : resultsPerLine; for (int i = 0; i < counter; i++) { elements[size++] = temp[i]; } for (int i = resultsPerLine; i < temp.Length; i++) { elements[size - 1] += delimiter + temp[i]; } } } else { string[] temp = source.Split(delimiter); resultsPerLine = temp.Length < resultsPerLine ? temp.Length : resultsPerLine; elements = new string[resultsPerLine]; for (int i = 0; i < resultsPerLine; i++) { elements[i] = temp[i]; } for (int i = resultsPerLine; i < temp.Length; i++) { elements[resultsPerLine - 1] += delimiter + temp[i]; } } } } /// <summary>IEnumerable Interface Implementation</summary> IEnumerator IEnumerable.GetEnumerator() { return new TokenEnumerator(this); } /// <summary> /// creates a dictionary of tokens based on this tokencollection /// </summary> /// <returns></returns> public Dictionary<string, string> CreateDictionary() { Dictionary<string, string> dict = new Dictionary<string, string>(); for (int i = 0; i < elements.Length; i += 2) { string key = elements[i]; string val = elements[i + 1]; dict.Add(key, val); } return dict; } /// <summary>IEnumerable Interface Implementation, for the noninterface</summary> public TokenEnumerator GetEnumerator() // non-IEnumerable version { return new TokenEnumerator(this); } /// <summary>Inner class implements IEnumerator interface</summary> public class TokenEnumerator : IEnumerator { private int position = -1; private readonly TokenCollection tokens; /// <summary>Standard constructor</summary> public TokenEnumerator(TokenCollection tokens) { this.tokens = tokens; } /// <summary>Current implementation, non interface, type-safe</summary> public string Current { get { return tokens.elements != null ? tokens.elements[position] : null; } } /// <summary>IEnumerable::MoveNext implementation</summary> public bool MoveNext() { if (tokens.elements != null && position < tokens.elements.Length - 1) { position++; return true; } return false; } /// <summary>IEnumerable::Reset implementation</summary> public void Reset() { position = -1; } /// <summary>Current implementation, interface, not type-safe</summary> object IEnumerator.Current { get { return tokens.elements != null ? tokens.elements[position] : null; } } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.XWPF.UserModel { using System; using System.Text; using NPOI.OpenXmlFormats.Wordprocessing; using System.Collections.Generic; /** * Sketch of XWPFTable class. Only table's text is being hold. * <p/> * Specifies the contents of a table present in the document. A table is a Set * of paragraphs (and other block-level content) arranged in rows and columns. * * @author Yury Batrakov (batrakov at gmail.com) * @author Gregg Morris (gregg dot morris at gmail dot com) - added * setStyleID() * getRowBandSize(), setRowBandSize() * getColBandSize(), setColBandSize() * getInsideHBorderType(), getInsideHBorderSize(), getInsideHBorderSpace(), getInsideHBorderColor() * getInsideVBorderType(), getInsideVBorderSize(), getInsideVBorderSpace(), getInsideVBorderColor() * setInsideHBorder(), setInsideVBorder() * getCellMarginTop(), getCellMarginLeft(), getCellMarginBottom(), getCellMarginRight() * setCellMargins() */ public class XWPFTable : IBodyElement { protected StringBuilder text = new StringBuilder(); private CT_Tbl ctTbl; protected List<XWPFTableRow> tableRows; protected List<String> styleIDs; // Create a map from this XWPF-level enum to the STBorder.Enum values public enum XWPFBorderType { NIL, NONE, SINGLE, THICK, DOUBLE, DOTTED, DASHED, DOT_DASH }; internal static Dictionary<XWPFBorderType, ST_Border> xwpfBorderTypeMap; // Create a map from the STBorder.Enum values to the XWPF-level enums internal static Dictionary<ST_Border, XWPFBorderType> stBorderTypeMap; protected IBody part; static XWPFTable() { // populate enum maps xwpfBorderTypeMap = new Dictionary<XWPFBorderType, ST_Border>(); xwpfBorderTypeMap.Add(XWPFBorderType.NIL, ST_Border.nil); xwpfBorderTypeMap.Add(XWPFBorderType.NONE, ST_Border.none); xwpfBorderTypeMap.Add(XWPFBorderType.SINGLE, ST_Border.single); xwpfBorderTypeMap.Add(XWPFBorderType.THICK, ST_Border.thick); xwpfBorderTypeMap.Add(XWPFBorderType.DOUBLE, ST_Border.@double); xwpfBorderTypeMap.Add(XWPFBorderType.DOTTED, ST_Border.dotted); xwpfBorderTypeMap.Add(XWPFBorderType.DASHED, ST_Border.dashed); xwpfBorderTypeMap.Add(XWPFBorderType.DOT_DASH, ST_Border.dotDash); stBorderTypeMap = new Dictionary<ST_Border, XWPFBorderType>(); stBorderTypeMap.Add(ST_Border.nil, XWPFBorderType.NIL); stBorderTypeMap.Add(ST_Border.none, XWPFBorderType.NONE); stBorderTypeMap.Add(ST_Border.single, XWPFBorderType.SINGLE); stBorderTypeMap.Add(ST_Border.thick, XWPFBorderType.THICK); stBorderTypeMap.Add(ST_Border.@double, XWPFBorderType.DOUBLE); stBorderTypeMap.Add(ST_Border.dotted, XWPFBorderType.DOTTED); stBorderTypeMap.Add(ST_Border.dashed, XWPFBorderType.DASHED); stBorderTypeMap.Add(ST_Border.dotDash, XWPFBorderType.DOT_DASH); } public XWPFTable(CT_Tbl table, IBody part, int row, int col) : this(table, part) { CT_TblGrid ctTblGrid = table.AddNewTblGrid(); for (int j = 0; j < col; j++) { CT_TblGridCol ctGridCol= ctTblGrid.AddNewGridCol(); ctGridCol.w = 300; } for (int i = 0; i < row; i++) { XWPFTableRow tabRow = (GetRow(i) == null) ? CreateRow() : GetRow(i); for (int k = 0; k < col; k++) { if (tabRow.GetCell(k) == null) { tabRow.CreateCell(); } } } } public void SetColumnWidth(int columnIndex, ulong width) { if (this.ctTbl.tblGrid == null) return; if (columnIndex > this.ctTbl.tblGrid.gridCol.Count) { throw new ArgumentOutOfRangeException(string.Format("Column index {0} doesn't exist.", columnIndex)); } this.ctTbl.tblGrid.gridCol[columnIndex].w = width; } public XWPFTable(CT_Tbl table, IBody part) { this.part = part; this.ctTbl = table; tableRows = new List<XWPFTableRow>(); // is an empty table: I add one row and one column as default if (table.SizeOfTrArray() == 0) CreateEmptyTable(table); foreach (CT_Row row in table.GetTrList()) { StringBuilder rowText = new StringBuilder(); row.Table = table; XWPFTableRow tabRow = new XWPFTableRow(row, this); tableRows.Add(tabRow); foreach (CT_Tc cell in row.GetTcList()) { foreach (CT_P ctp in cell.GetPList()) { XWPFParagraph p = new XWPFParagraph(ctp, part); if (rowText.Length > 0) { rowText.Append('\t'); } rowText.Append(p.Text); } } if (rowText.Length > 0) { this.text.Append(rowText); this.text.Append('\n'); } } } private void CreateEmptyTable(CT_Tbl table) { // MINIMUM ELEMENTS FOR A TABLE table.AddNewTr().AddNewTc().AddNewP(); CT_TblPr tblpro = table.AddNewTblPr(); if (!tblpro.IsSetTblW()) tblpro.AddNewTblW().w = "0"; tblpro.tblW.type=(ST_TblWidth.auto); // layout tblpro.AddNewTblLayout().type = ST_TblLayoutType.autofit; // borders CT_TblBorders borders = tblpro.AddNewTblBorders(); borders.AddNewBottom().val=ST_Border.single; borders.AddNewInsideH().val = ST_Border.single; borders.AddNewInsideV().val = ST_Border.single; borders.AddNewLeft().val = ST_Border.single; borders.AddNewRight().val = ST_Border.single; borders.AddNewTop().val = ST_Border.single; CT_TblGrid tblgrid=table.AddNewTblGrid(); tblgrid.AddNewGridCol().w= (ulong)2000; } /** * @return ctTbl object */ internal CT_Tbl GetCTTbl() { return ctTbl; } /** * @return text */ public String Text { get { return text.ToString(); } } public void AddNewRowBetween(int start, int end) { throw new NotImplementedException(); } /** * add a new column for each row in this table */ public void AddNewCol() { if (ctTbl.SizeOfTrArray() == 0) { CreateRow(); } for (int i = 0; i < ctTbl.SizeOfTrArray(); i++) { XWPFTableRow tabRow = new XWPFTableRow(ctTbl.GetTrArray(i), this); tabRow.CreateCell(); } } /** * create a new XWPFTableRow object with as many cells as the number of columns defined in that moment * * @return tableRow */ public XWPFTableRow CreateRow() { int sizeCol = ctTbl.SizeOfTrArray() > 0 ? ctTbl.GetTrArray(0) .SizeOfTcArray() : 0; XWPFTableRow tabRow = new XWPFTableRow(ctTbl.AddNewTr(), this); AddColumn(tabRow, sizeCol); tableRows.Add(tabRow); return tabRow; } /** * @param pos - index of the row * @return the row at the position specified or null if no rows is defined or if the position is greather than the max size of rows array */ public XWPFTableRow GetRow(int pos) { if (pos >= 0 && pos < ctTbl.SizeOfTrArray()) { //return new XWPFTableRow(ctTbl.GetTrArray(pos)); return Rows[(pos)]; } return null; } /** * @return width value */ public int Width { get { CT_TblPr tblPr = GetTrPr(); return tblPr.IsSetTblW() ? int.Parse(tblPr.tblW.w) : -1; } set { CT_TblPr tblPr = GetTrPr(); CT_TblWidth tblWidth = tblPr.IsSetTblW() ? tblPr.tblW : tblPr .AddNewTblW(); tblWidth.w = value.ToString(); tblWidth.type = ST_TblWidth.pct; } } /** * @return number of rows in table */ public int NumberOfRows { get { return ctTbl.SizeOfTrArray(); } } private CT_TblPr GetTrPr() { return (ctTbl.tblPr != null) ? ctTbl.tblPr : ctTbl .AddNewTblPr(); } private void AddColumn(XWPFTableRow tabRow, int sizeCol) { if (sizeCol > 0) { for (int i = 0; i < sizeCol; i++) { tabRow.CreateCell(); } } } /** * Get the StyleID of the table * @return style-ID of the table */ public String StyleID { get { String styleId = null; CT_TblPr tblPr = ctTbl.tblPr; if (tblPr != null) { CT_String styleStr = tblPr.tblStyle; if (styleStr != null) { styleId = styleStr.val; } } return styleId; } set { CT_TblPr tblPr = GetTrPr(); CT_String styleStr = tblPr.tblStyle; if (styleStr == null) { styleStr = tblPr.AddNewTblStyle(); } styleStr.val = value; } } public XWPFBorderType InsideHBorderType { get { XWPFBorderType bt = XWPFBorderType.NONE; CT_TblPr tblPr = GetTrPr(); if (tblPr.IsSetTblBorders()) { CT_TblBorders ctb = tblPr.tblBorders; if (ctb.IsSetInsideH()) { CT_Border border = ctb.insideH; bt = stBorderTypeMap[border.val]; } } return bt; } } public int InsideHBorderSize { get { int size = -1; CT_TblPr tblPr = GetTrPr(); if (tblPr.IsSetTblBorders()) { CT_TblBorders ctb = tblPr.tblBorders; if (ctb.IsSetInsideH()) { CT_Border border = ctb.insideH; size = (int)border.sz; } } return size; } } public int InsideHBorderSpace { get { int space = -1; CT_TblPr tblPr = GetTrPr(); if (tblPr.IsSetTblBorders()) { CT_TblBorders ctb = tblPr.tblBorders; if (ctb.IsSetInsideH()) { CT_Border border = ctb.insideH; space = (int)border.space; } } return space; } } public String InsideHBorderColor { get { String color = null; CT_TblPr tblPr = GetTrPr(); if (tblPr.IsSetTblBorders()) { CT_TblBorders ctb = tblPr.tblBorders; if (ctb.IsSetInsideH()) { CT_Border border = ctb.insideH; color = border.color; } } return color; } } public XWPFBorderType InsideVBorderType { get { XWPFBorderType bt = XWPFBorderType.NONE; CT_TblPr tblPr = GetTrPr(); if (tblPr.IsSetTblBorders()) { CT_TblBorders ctb = tblPr.tblBorders; if (ctb.IsSetInsideV()) { CT_Border border = ctb.insideV; bt = stBorderTypeMap[border.val]; } } return bt; } } public int InsideVBorderSize { get { int size = -1; CT_TblPr tblPr = GetTrPr(); if (tblPr.IsSetTblBorders()) { CT_TblBorders ctb = tblPr.tblBorders; if (ctb.IsSetInsideV()) { CT_Border border = ctb.insideV; size = (int)border.sz; } } return size; } } public int InsideVBorderSpace { get { int space = -1; CT_TblPr tblPr = GetTrPr(); if (tblPr.IsSetTblBorders()) { CT_TblBorders ctb = tblPr.tblBorders; if (ctb.IsSetInsideV()) { CT_Border border = ctb.insideV; space = (int)border.space; } } return space; } } public String InsideVBorderColor { get { String color = null; CT_TblPr tblPr = GetTrPr(); if (tblPr.IsSetTblBorders()) { CT_TblBorders ctb = tblPr.tblBorders; if (ctb.IsSetInsideV()) { CT_Border border = ctb.insideV; color = border.color; } } return color; } } public int RowBandSize { get { int size = 0; CT_TblPr tblPr = GetTrPr(); if (tblPr.IsSetTblStyleRowBandSize()) { CT_DecimalNumber rowSize = tblPr.tblStyleRowBandSize; int.TryParse(rowSize.val, out size); } return size; } set { CT_TblPr tblPr = GetTrPr(); CT_DecimalNumber rowSize = tblPr.IsSetTblStyleRowBandSize() ? tblPr.tblStyleRowBandSize : tblPr.AddNewTblStyleRowBandSize(); rowSize.val = value.ToString(); } } public int ColBandSize { get { int size = 0; CT_TblPr tblPr = GetTrPr(); if (tblPr.IsSetTblStyleColBandSize()) { CT_DecimalNumber colSize = tblPr.tblStyleColBandSize; int.TryParse(colSize.val, out size); } return size; } set { CT_TblPr tblPr = GetTrPr(); CT_DecimalNumber colSize = tblPr.IsSetTblStyleColBandSize() ? tblPr.tblStyleColBandSize : tblPr.AddNewTblStyleColBandSize(); colSize.val = value.ToString(); } } public void SetTopBorder(XWPFBorderType type, int size, int space, String rgbColor) { CT_TblPr tblPr = GetTrPr(); CT_TblBorders ctb = tblPr.IsSetTblBorders() ? tblPr.tblBorders : tblPr.AddNewTblBorders(); CT_Border b = ctb.top!=null ? ctb.top : ctb.AddNewTop(); b.val = xwpfBorderTypeMap[type]; b.sz = (ulong)size; b.space = (ulong)space; b.color = (rgbColor); } public void SetBottomBorder(XWPFBorderType type, int size, int space, String rgbColor) { CT_TblPr tblPr = GetTrPr(); CT_TblBorders ctb = tblPr.IsSetTblBorders() ? tblPr.tblBorders : tblPr.AddNewTblBorders(); CT_Border b = ctb.bottom != null ? ctb.bottom : ctb.AddNewBottom(); b.val = xwpfBorderTypeMap[type]; b.sz = (ulong)size; b.space = (ulong)space; b.color = (rgbColor); } public void SetLeftBorder(XWPFBorderType type, int size, int space, String rgbColor) { CT_TblPr tblPr = GetTrPr(); CT_TblBorders ctb = tblPr.IsSetTblBorders() ? tblPr.tblBorders : tblPr.AddNewTblBorders(); CT_Border b = ctb.left != null ? ctb.left : ctb.AddNewLeft(); b.val = xwpfBorderTypeMap[type]; b.sz = (ulong)size; b.space = (ulong)space; b.color = (rgbColor); } public void SetRightBorder(XWPFBorderType type, int size, int space, String rgbColor) { CT_TblPr tblPr = GetTrPr(); CT_TblBorders ctb = tblPr.IsSetTblBorders() ? tblPr.tblBorders : tblPr.AddNewTblBorders(); CT_Border b = ctb.right != null ? ctb.right : ctb.AddNewRight(); b.val = xwpfBorderTypeMap[type]; b.sz = (ulong)size; b.space = (ulong)space; b.color = (rgbColor); } public void SetInsideHBorder(XWPFBorderType type, int size, int space, String rgbColor) { CT_TblPr tblPr = GetTrPr(); CT_TblBorders ctb = tblPr.IsSetTblBorders() ? tblPr.tblBorders : tblPr.AddNewTblBorders(); CT_Border b = ctb.IsSetInsideH() ? ctb.insideH : ctb.AddNewInsideH(); b.val = (xwpfBorderTypeMap[(type)]); b.sz = (ulong)size; b.space = (ulong)space; b.color = (rgbColor); } public void SetInsideVBorder(XWPFBorderType type, int size, int space, String rgbColor) { CT_TblPr tblPr = GetTrPr(); CT_TblBorders ctb = tblPr.IsSetTblBorders() ? tblPr.tblBorders : tblPr.AddNewTblBorders(); CT_Border b = ctb.IsSetInsideV() ? ctb.insideV : ctb.AddNewInsideV(); b.val = (xwpfBorderTypeMap[type]); b.sz = (ulong)size; b.space = (ulong)space; b.color = (rgbColor); } public int CellMarginTop { get { int margin = 0; CT_TblPr tblPr = GetTrPr(); CT_TblCellMar tcm = tblPr.tblCellMar; if (tcm != null) { CT_TblWidth tw = tcm.top; if (tw != null) { int.TryParse(tw.w, out margin); } } return margin; } } public int CellMarginLeft { get { int margin = 0; CT_TblPr tblPr = GetTrPr(); CT_TblCellMar tcm = tblPr.tblCellMar; if (tcm != null) { CT_TblWidth tw = tcm.left; if (tw != null) { int.TryParse(tw.w, out margin); } } return margin; } } public int CellMarginBottom { get { int margin = 0; CT_TblPr tblPr = GetTrPr(); CT_TblCellMar tcm = tblPr.tblCellMar; if (tcm != null) { CT_TblWidth tw = tcm.bottom; if (tw != null) { int.TryParse(tw.w, out margin); } } return margin; } } public int CellMarginRight { get { int margin = 0; CT_TblPr tblPr = GetTrPr(); CT_TblCellMar tcm = tblPr.tblCellMar; if (tcm != null) { CT_TblWidth tw = tcm.right; if (tw != null) { int.TryParse(tw.w, out margin); } } return margin; } } public void SetCellMargins(int top, int left, int bottom, int right) { CT_TblPr tblPr = GetTrPr(); CT_TblCellMar tcm = tblPr.IsSetTblCellMar() ? tblPr.tblCellMar : tblPr.AddNewTblCellMar(); CT_TblWidth tw = tcm.IsSetLeft() ? tcm.left : tcm.AddNewLeft(); tw.type = (ST_TblWidth.dxa); tw.w = left.ToString(); tw = tcm.IsSetTop() ? tcm.top : tcm.AddNewTop(); tw.type = (ST_TblWidth.dxa); tw.w = top.ToString(); tw = tcm.IsSetBottom() ? tcm.bottom : tcm.AddNewBottom(); tw.type = (ST_TblWidth.dxa); tw.w = bottom.ToString(); tw = tcm.IsSetRight() ? tcm.right : tcm.AddNewRight(); tw.type = (ST_TblWidth.dxa); tw.w = right.ToString(); } /** * add a new Row to the table * * @param row the row which should be Added */ public void AddRow(XWPFTableRow row) { ctTbl.AddNewTr(); ctTbl.SetTrArray(this.NumberOfRows-1, row.GetCTRow()); tableRows.Add(row); } /** * add a new Row to the table * at position pos * @param row the row which should be Added */ public bool AddRow(XWPFTableRow row, int pos) { if (pos >= 0 && pos <= tableRows.Count) { ctTbl.InsertNewTr(pos); ctTbl.SetTrArray(pos, row.GetCTRow()); tableRows.Insert(pos, row); return true; } return false; } /** * inserts a new tablerow * @param pos * @return the inserted row */ public XWPFTableRow InsertNewTableRow(int pos) { if(pos >= 0 && pos <= tableRows.Count){ CT_Row row = ctTbl.InsertNewTr(pos); XWPFTableRow tableRow = new XWPFTableRow(row, this); tableRows.Insert(pos, tableRow); return tableRow; } return null; } /** * Remove a row at position pos from the table * @param pos position the Row in the Table */ public bool RemoveRow(int pos) { if (pos >= 0 && pos < tableRows.Count) { if (ctTbl.SizeOfTrArray() > 0) { ctTbl.RemoveTr(pos); } tableRows.RemoveAt(pos); return true; } return false; } public List<XWPFTableRow> Rows { get { return tableRows; } } /** * returns the type of the BodyElement Table * @see NPOI.XWPF.UserModel.IBodyElement#getElementType() */ public BodyElementType ElementType { get { return BodyElementType.TABLE; } } public IBody Body { get { return part; } } /** * returns the part of the bodyElement * @see NPOI.XWPF.UserModel.IBody#getPart() */ public POIXMLDocumentPart GetPart() { if (part != null) { return part.GetPart(); } return null; } /** * returns the partType of the bodyPart which owns the bodyElement * @see NPOI.XWPF.UserModel.IBody#getPartType() */ public BodyType PartType { get { return part.PartType; } } /** * returns the XWPFRow which belongs to the CTRow row * if this row is not existing in the table null will be returned */ public XWPFTableRow GetRow(CT_Row row) { for(int i=0; i<Rows.Count; i++){ if(Rows[(i)].GetCTRow() == row) return GetRow(i); } return null; } }// end class }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Conn.Scheme.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. #pragma warning disable 1717 namespace Org.Apache.Http.Conn.Scheme { /// <java-name> /// org/apache/http/conn/scheme/HostNameResolver /// </java-name> [Dot42.DexImport("org/apache/http/conn/scheme/HostNameResolver", AccessFlags = 1537)] public partial interface IHostNameResolver /* scope: __dot42__ */ { /// <java-name> /// resolve /// </java-name> [Dot42.DexImport("resolve", "(Ljava/lang/String;)Ljava/net/InetAddress;", AccessFlags = 1025)] global::Java.Net.InetAddress Resolve(string hostname) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Encapsulates specifics of a protocol scheme such as "http" or "https". Schemes are identified by lowercase names. Supported schemes are typically collected in a SchemeRegistry.</para><para>For example, to configure support for "https://" URLs, you could write code like the following: </para><para><pre> /// Scheme https = new Scheme("https", new MySecureSocketFactory(), 443); /// SchemeRegistry.DEFAULT.register(https); /// </pre></para><para><para> </para><simplesectsep></simplesectsep><para>Michael Becke </para><simplesectsep></simplesectsep><para>Jeff Dever </para><simplesectsep></simplesectsep><para> </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/scheme/Scheme /// </java-name> [Dot42.DexImport("org/apache/http/conn/scheme/Scheme", AccessFlags = 49)] public sealed partial class Scheme /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new scheme. Whether the created scheme allows for layered connections depends on the class of <code>factory</code>.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Lorg/apache/http/conn/scheme/SocketFactory;I)V", AccessFlags = 1)] public Scheme(string name, global::Org.Apache.Http.Conn.Scheme.ISocketFactory factory, int port) /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the default port.</para><para></para> /// </summary> /// <returns> /// <para>the default port for this scheme </para> /// </returns> /// <java-name> /// getDefaultPort /// </java-name> [Dot42.DexImport("getDefaultPort", "()I", AccessFlags = 17)] public int GetDefaultPort() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Obtains the socket factory. If this scheme is layered, the factory implements LayeredSocketFactory.</para><para></para> /// </summary> /// <returns> /// <para>the socket factory for this scheme </para> /// </returns> /// <java-name> /// getSocketFactory /// </java-name> [Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/scheme/SocketFactory;", AccessFlags = 17)] public global::Org.Apache.Http.Conn.Scheme.ISocketFactory GetSocketFactory() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Scheme.ISocketFactory); } /// <summary> /// <para>Obtains the scheme name.</para><para></para> /// </summary> /// <returns> /// <para>the name of this scheme, in lowercase </para> /// </returns> /// <java-name> /// getName /// </java-name> [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 17)] public string GetName() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Indicates whether this scheme allows for layered connections.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if layered connections are possible, <code>false</code> otherwise </para> /// </returns> /// <java-name> /// isLayered /// </java-name> [Dot42.DexImport("isLayered", "()Z", AccessFlags = 17)] public bool IsLayered() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Resolves the correct port for this scheme. Returns the given port if it is valid, the default port otherwise.</para><para></para> /// </summary> /// <returns> /// <para>the given port or the defaultPort </para> /// </returns> /// <java-name> /// resolvePort /// </java-name> [Dot42.DexImport("resolvePort", "(I)I", AccessFlags = 17)] public int ResolvePort(int port) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Return a string representation of this object.</para><para></para> /// </summary> /// <returns> /// <para>a human-readable string description of this scheme </para> /// </returns> /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 17)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Compares this scheme to an object.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> iff the argument is equal to this scheme </para> /// </returns> /// <java-name> /// equals /// </java-name> [Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 17)] public override bool Equals(object obj) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Obtains a hash code for this scheme.</para><para></para> /// </summary> /// <returns> /// <para>the hash code </para> /// </returns> /// <java-name> /// hashCode /// </java-name> [Dot42.DexImport("hashCode", "()I", AccessFlags = 1)] public override int GetHashCode() /* MethodBuilder.Create */ { return default(int); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal Scheme() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Obtains the default port.</para><para></para> /// </summary> /// <returns> /// <para>the default port for this scheme </para> /// </returns> /// <java-name> /// getDefaultPort /// </java-name> public int DefaultPort { [Dot42.DexImport("getDefaultPort", "()I", AccessFlags = 17)] get{ return GetDefaultPort(); } } /// <summary> /// <para>Obtains the socket factory. If this scheme is layered, the factory implements LayeredSocketFactory.</para><para></para> /// </summary> /// <returns> /// <para>the socket factory for this scheme </para> /// </returns> /// <java-name> /// getSocketFactory /// </java-name> public global::Org.Apache.Http.Conn.Scheme.ISocketFactory SocketFactory { [Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/scheme/SocketFactory;", AccessFlags = 17)] get{ return GetSocketFactory(); } } /// <summary> /// <para>Obtains the scheme name.</para><para></para> /// </summary> /// <returns> /// <para>the name of this scheme, in lowercase </para> /// </returns> /// <java-name> /// getName /// </java-name> public string Name { [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 17)] get{ return GetName(); } } } /// <summary> /// <para>A SocketFactory for layered sockets (SSL/TLS). See there for things to consider when implementing a socket factory.</para><para><para>Michael Becke </para><simplesectsep></simplesectsep><para> </para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/scheme/LayeredSocketFactory /// </java-name> [Dot42.DexImport("org/apache/http/conn/scheme/LayeredSocketFactory", AccessFlags = 1537)] public partial interface ILayeredSocketFactory : global::Org.Apache.Http.Conn.Scheme.ISocketFactory /* scope: __dot42__ */ { /// <summary> /// <para>Returns a socket connected to the given host that is layered over an existing socket. Used primarily for creating secure sockets through proxies.</para><para></para> /// </summary> /// <returns> /// <para>Socket a new socket</para> /// </returns> /// <java-name> /// createSocket /// </java-name> [Dot42.DexImport("createSocket", "(Ljava/net/Socket;Ljava/lang/String;IZ)Ljava/net/Socket;", AccessFlags = 1025)] global::Java.Net.Socket CreateSocket(global::Java.Net.Socket socket, string host, int port, bool autoClose) /* MethodBuilder.Create */ ; } /// <summary> /// <para>A set of supported protocol schemes. Schemes are identified by lowercase names.</para><para><para></para><para></para><title>Revision:</title><para>648356 </para><title>Date:</title><para>2008-04-15 10:57:53 -0700 (Tue, 15 Apr 2008) </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/scheme/SchemeRegistry /// </java-name> [Dot42.DexImport("org/apache/http/conn/scheme/SchemeRegistry", AccessFlags = 49)] public sealed partial class SchemeRegistry /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new, empty scheme registry. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public SchemeRegistry() /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the scheme for a host. Convenience method for <code>getScheme(host.getSchemeName())</code></para><para><code> </code></para> /// </summary> /// <returns> /// <para>the scheme for the given host, never <code>null</code></para> /// </returns> /// <java-name> /// getScheme /// </java-name> [Dot42.DexImport("getScheme", "(Ljava/lang/String;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)] public global::Org.Apache.Http.Conn.Scheme.Scheme GetScheme(string host) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Scheme.Scheme); } /// <summary> /// <para>Obtains the scheme for a host. Convenience method for <code>getScheme(host.getSchemeName())</code></para><para><code> </code></para> /// </summary> /// <returns> /// <para>the scheme for the given host, never <code>null</code></para> /// </returns> /// <java-name> /// getScheme /// </java-name> [Dot42.DexImport("getScheme", "(Lorg/apache/http/HttpHost;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)] public global::Org.Apache.Http.Conn.Scheme.Scheme GetScheme(global::Org.Apache.Http.HttpHost host) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Scheme.Scheme); } /// <summary> /// <para>Obtains a scheme by name, if registered.</para><para></para> /// </summary> /// <returns> /// <para>the scheme, or <code>null</code> if there is none by this name </para> /// </returns> /// <java-name> /// get /// </java-name> [Dot42.DexImport("get", "(Ljava/lang/String;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)] public global::Org.Apache.Http.Conn.Scheme.Scheme Get(string name) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Scheme.Scheme); } /// <summary> /// <para>Registers a scheme. The scheme can later be retrieved by its name using getScheme or get.</para><para></para> /// </summary> /// <returns> /// <para>the scheme previously registered with that name, or <code>null</code> if none was registered </para> /// </returns> /// <java-name> /// register /// </java-name> [Dot42.DexImport("register", "(Lorg/apache/http/conn/scheme/Scheme;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)] public global::Org.Apache.Http.Conn.Scheme.Scheme Register(global::Org.Apache.Http.Conn.Scheme.Scheme sch) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Scheme.Scheme); } /// <summary> /// <para>Unregisters a scheme.</para><para></para> /// </summary> /// <returns> /// <para>the unregistered scheme, or <code>null</code> if there was none </para> /// </returns> /// <java-name> /// unregister /// </java-name> [Dot42.DexImport("unregister", "(Ljava/lang/String;)Lorg/apache/http/conn/scheme/Scheme;", AccessFlags = 49)] public global::Org.Apache.Http.Conn.Scheme.Scheme Unregister(string name) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Scheme.Scheme); } /// <summary> /// <para>Obtains the names of the registered schemes in their default order.</para><para></para> /// </summary> /// <returns> /// <para>List containing registered scheme names. </para> /// </returns> /// <java-name> /// getSchemeNames /// </java-name> [Dot42.DexImport("getSchemeNames", "()Ljava/util/List;", AccessFlags = 49, Signature = "()Ljava/util/List<Ljava/lang/String;>;")] public global::Java.Util.IList<string> GetSchemeNames() /* MethodBuilder.Create */ { return default(global::Java.Util.IList<string>); } /// <summary> /// <para>Populates the internal collection of registered protocol schemes with the content of the map passed as a parameter.</para><para></para> /// </summary> /// <java-name> /// setItems /// </java-name> [Dot42.DexImport("setItems", "(Ljava/util/Map;)V", AccessFlags = 33, Signature = "(Ljava/util/Map<Ljava/lang/String;Lorg/apache/http/conn/scheme/Scheme;>;)V")] public void SetItems(global::Java.Util.IMap<string, global::Org.Apache.Http.Conn.Scheme.Scheme> map) /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the names of the registered schemes in their default order.</para><para></para> /// </summary> /// <returns> /// <para>List containing registered scheme names. </para> /// </returns> /// <java-name> /// getSchemeNames /// </java-name> public global::Java.Util.IList<string> SchemeNames { [Dot42.DexImport("getSchemeNames", "()Ljava/util/List;", AccessFlags = 49, Signature = "()Ljava/util/List<Ljava/lang/String;>;")] get{ return GetSchemeNames(); } } } /// <summary> /// <para>The default class for creating sockets.</para><para><para> </para><simplesectsep></simplesectsep><para>Michael Becke </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/scheme/PlainSocketFactory /// </java-name> [Dot42.DexImport("org/apache/http/conn/scheme/PlainSocketFactory", AccessFlags = 49)] public sealed partial class PlainSocketFactory : global::Org.Apache.Http.Conn.Scheme.ISocketFactory /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/conn/scheme/HostNameResolver;)V", AccessFlags = 1)] public PlainSocketFactory(global::Org.Apache.Http.Conn.Scheme.IHostNameResolver nameResolver) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public PlainSocketFactory() /* MethodBuilder.Create */ { } /// <summary> /// <para>Gets the singleton instance of this class. </para> /// </summary> /// <returns> /// <para>the one and only plain socket factory </para> /// </returns> /// <java-name> /// getSocketFactory /// </java-name> [Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/scheme/PlainSocketFactory;", AccessFlags = 9)] public static global::Org.Apache.Http.Conn.Scheme.PlainSocketFactory GetSocketFactory() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Scheme.PlainSocketFactory); } /// <summary> /// <para>Creates a new, unconnected socket. The socket should subsequently be passed to connectSocket.</para><para></para> /// </summary> /// <returns> /// <para>a new socket</para> /// </returns> /// <java-name> /// createSocket /// </java-name> [Dot42.DexImport("createSocket", "()Ljava/net/Socket;", AccessFlags = 1)] public global::Java.Net.Socket CreateSocket() /* MethodBuilder.Create */ { return default(global::Java.Net.Socket); } /// <summary> /// <para>Connects a socket to the given host.</para><para></para> /// </summary> /// <returns> /// <para>the connected socket. The returned object may be different from the <code>sock</code> argument if this factory supports a layered protocol.</para> /// </returns> /// <java-name> /// connectSocket /// </java-name> [Dot42.DexImport("connectSocket", "(Ljava/net/Socket;Ljava/lang/String;ILjava/net/InetAddress;ILorg/apache/http/para" + "ms/HttpParams;)Ljava/net/Socket;", AccessFlags = 1)] public global::Java.Net.Socket ConnectSocket(global::Java.Net.Socket sock, string host, int port, global::Java.Net.InetAddress localAddress, int localPort, global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Java.Net.Socket); } /// <summary> /// <para>Checks whether a socket connection is secure. This factory creates plain socket connections which are not considered secure.</para><para></para> /// </summary> /// <returns> /// <para><code>false</code></para> /// </returns> /// <java-name> /// isSecure /// </java-name> [Dot42.DexImport("isSecure", "(Ljava/net/Socket;)Z", AccessFlags = 17)] public bool IsSecure(global::Java.Net.Socket sock) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Compares this factory with an object. There is only one instance of this class.</para><para></para> /// </summary> /// <returns> /// <para>iff the argument is this object </para> /// </returns> /// <java-name> /// equals /// </java-name> [Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)] public override bool Equals(object obj) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Obtains a hash code for this object. All instances of this class have the same hash code. There is only one instance of this class. </para> /// </summary> /// <java-name> /// hashCode /// </java-name> [Dot42.DexImport("hashCode", "()I", AccessFlags = 1)] public override int GetHashCode() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Gets the singleton instance of this class. </para> /// </summary> /// <returns> /// <para>the one and only plain socket factory </para> /// </returns> /// <java-name> /// getSocketFactory /// </java-name> public static global::Org.Apache.Http.Conn.Scheme.PlainSocketFactory SocketFactory { [Dot42.DexImport("getSocketFactory", "()Lorg/apache/http/conn/scheme/PlainSocketFactory;", AccessFlags = 9)] get{ return GetSocketFactory(); } } } /// <summary> /// <para>A factory for creating and connecting sockets. The factory encapsulates the logic for establishing a socket connection. <br></br> Both Object.equals() and Object.hashCode() must be overridden for the correct operation of some connection managers.</para><para><para> </para><simplesectsep></simplesectsep><para>Michael Becke </para><simplesectsep></simplesectsep><para> </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/scheme/SocketFactory /// </java-name> [Dot42.DexImport("org/apache/http/conn/scheme/SocketFactory", AccessFlags = 1537)] public partial interface ISocketFactory /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new, unconnected socket. The socket should subsequently be passed to connectSocket.</para><para></para> /// </summary> /// <returns> /// <para>a new socket</para> /// </returns> /// <java-name> /// createSocket /// </java-name> [Dot42.DexImport("createSocket", "()Ljava/net/Socket;", AccessFlags = 1025)] global::Java.Net.Socket CreateSocket() /* MethodBuilder.Create */ ; /// <summary> /// <para>Connects a socket to the given host.</para><para></para> /// </summary> /// <returns> /// <para>the connected socket. The returned object may be different from the <code>sock</code> argument if this factory supports a layered protocol.</para> /// </returns> /// <java-name> /// connectSocket /// </java-name> [Dot42.DexImport("connectSocket", "(Ljava/net/Socket;Ljava/lang/String;ILjava/net/InetAddress;ILorg/apache/http/para" + "ms/HttpParams;)Ljava/net/Socket;", AccessFlags = 1025)] global::Java.Net.Socket ConnectSocket(global::Java.Net.Socket sock, string host, int port, global::Java.Net.InetAddress localAddress, int localPort, global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ ; /// <summary> /// <para>Checks whether a socket provides a secure connection. The socket must be connected by this factory. The factory will <b>not</b> perform I/O operations in this method. <br></br> As a rule of thumb, plain sockets are not secure and TLS/SSL sockets are secure. However, there may be application specific deviations. For example, a plain socket to a host in the same intranet ("trusted zone") could be considered secure. On the other hand, a TLS/SSL socket could be considered insecure based on the cypher suite chosen for the connection.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the connection of the socket should be considered secure, or <code>false</code> if it should not</para> /// </returns> /// <java-name> /// isSecure /// </java-name> [Dot42.DexImport("isSecure", "(Ljava/net/Socket;)Z", AccessFlags = 1025)] bool IsSecure(global::Java.Net.Socket sock) /* MethodBuilder.Create */ ; } }
//------------------------------------------------------------------------------ // <license file="NativeRegExpCtor.cs"> // // The use and distribution terms for this software are contained in the file // named 'LICENSE', which can be found in the resources directory of this // distribution. // // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // </license> //------------------------------------------------------------------------------ using System; using EcmaScript.NET; namespace EcmaScript.NET.Types.RegExp { /// <summary> This class implements the RegExp constructor native object. /// /// Revision History: /// Implementation in C by Brendan Eich /// Initial port to Java by Norris Boyd from jsregexp.c version 1.36 /// Merged up to version 1.38, which included Unicode support. /// Merged bug fixes in version 1.39. /// Merged JSFUN13_BRANCH changes up to 1.32.2.11 /// /// </summary> class BuiltinRegExpCtor : BaseFunction { override public string FunctionName { get { return "RegExp"; } } private static RegExpImpl Impl { get { Context cx = Context.CurrentContext; return (RegExpImpl)cx.RegExpProxy; } } override protected internal int MaxInstanceId { get { return base.MaxInstanceId + MAX_INSTANCE_ID; } } internal BuiltinRegExpCtor () { } public override object Call (Context cx, IScriptable scope, IScriptable thisObj, object [] args) { if (args.Length > 0 && args [0] is BuiltinRegExp && (args.Length == 1 || args [1] == Undefined.Value)) { return args [0]; } return Construct (cx, scope, args); } public override IScriptable Construct (Context cx, IScriptable scope, object [] args) { BuiltinRegExp re = new BuiltinRegExp (); re.compile (cx, scope, args); ScriptRuntime.setObjectProtoAndParent (re, scope); return re; } #region InstanceIds private const int Id_multiline = 1; private const int Id_STAR = 2; private const int Id_input = 3; private const int Id_UNDERSCORE = 4; private const int Id_lastMatch = 5; private const int Id_AMPERSAND = 6; private const int Id_lastParen = 7; private const int Id_PLUS = 8; private const int Id_leftContext = 9; private const int Id_BACK_QUOTE = 10; private const int Id_rightContext = 11; private const int Id_QUOTE = 12; private const int DOLLAR_ID_BASE = 12; private const int Id_DOLLAR_1 = 13; private const int Id_DOLLAR_2 = 14; private const int Id_DOLLAR_3 = 15; private const int Id_DOLLAR_4 = 16; private const int Id_DOLLAR_5 = 17; private const int Id_DOLLAR_6 = 18; private const int Id_DOLLAR_7 = 19; private const int Id_DOLLAR_8 = 20; private const int Id_DOLLAR_9 = 21; private const int MAX_INSTANCE_ID = 21; #endregion protected internal override int FindInstanceIdInfo (string s) { int id; #region Generated InstanceId Switch L0: { id = 0; string X = null; int c; L: switch (s.Length) { case 2: switch (s[1]) { case '&': if (s[0]=='$') {id=Id_AMPERSAND; goto EL0;} break; case '\'': if (s[0]=='$') {id=Id_QUOTE; goto EL0;} break; case '*': if (s[0]=='$') {id=Id_STAR; goto EL0;} break; case '+': if (s[0]=='$') {id=Id_PLUS; goto EL0;} break; case '1': if (s[0]=='$') {id=Id_DOLLAR_1; goto EL0;} break; case '2': if (s[0]=='$') {id=Id_DOLLAR_2; goto EL0;} break; case '3': if (s[0]=='$') {id=Id_DOLLAR_3; goto EL0;} break; case '4': if (s[0]=='$') {id=Id_DOLLAR_4; goto EL0;} break; case '5': if (s[0]=='$') {id=Id_DOLLAR_5; goto EL0;} break; case '6': if (s[0]=='$') {id=Id_DOLLAR_6; goto EL0;} break; case '7': if (s[0]=='$') {id=Id_DOLLAR_7; goto EL0;} break; case '8': if (s[0]=='$') {id=Id_DOLLAR_8; goto EL0;} break; case '9': if (s[0]=='$') {id=Id_DOLLAR_9; goto EL0;} break; case '_': if (s[0]=='$') {id=Id_UNDERSCORE; goto EL0;} break; } break; case 5: X="input";id=Id_input; break; case 9: c=s[4]; if (c=='M') { X="lastMatch";id=Id_lastMatch; } else if (c=='P') { X="lastParen";id=Id_lastParen; } else if (c=='i') { X="multiline";id=Id_multiline; } break; case 10: X="BACK_QUOTE";id=Id_BACK_QUOTE; break; case 11: X="leftContext";id=Id_leftContext; break; case 12: X="rightContext";id=Id_rightContext; break; } if (X!=null && X!=s && !X.Equals(s)) id = 0; } EL0: #endregion if (id == 0) return base.FindInstanceIdInfo (s); int attr; switch (id) { case Id_multiline: case Id_STAR: case Id_input: case Id_UNDERSCORE: attr = PERMANENT; break; default: attr = PERMANENT | READONLY; break; } return InstanceIdInfo (attr, base.MaxInstanceId + id); } // #/string_id_map# protected internal override string GetInstanceIdName (int id) { int shifted = id - base.MaxInstanceId; if (1 <= shifted && shifted <= MAX_INSTANCE_ID) { switch (shifted) { case Id_multiline: return "multiline"; case Id_STAR: return "$*"; case Id_input: return "input"; case Id_UNDERSCORE: return "$_"; case Id_lastMatch: return "lastMatch"; case Id_AMPERSAND: return "$&"; case Id_lastParen: return "lastParen"; case Id_PLUS: return "$+"; case Id_leftContext: return "leftContext"; case Id_BACK_QUOTE: return "$`"; case Id_rightContext: return "rightContext"; case Id_QUOTE: return "$'"; } // Must be one of $1..$9, convert to 0..8 int substring_number = shifted - DOLLAR_ID_BASE - 1; char [] buf = new char [] { '$', (char)('1' + substring_number) }; return new string (buf); } return base.GetInstanceIdName (id); } protected internal override object GetInstanceIdValue (int id) { int shifted = id - base.MaxInstanceId; if (1 <= shifted && shifted <= MAX_INSTANCE_ID) { RegExpImpl impl = Impl; object stringResult; switch (shifted) { case Id_multiline: case Id_STAR: return impl.multiline; case Id_input: case Id_UNDERSCORE: stringResult = impl.input; break; case Id_lastMatch: case Id_AMPERSAND: stringResult = impl.lastMatch; break; case Id_lastParen: case Id_PLUS: stringResult = impl.lastParen; break; case Id_leftContext: case Id_BACK_QUOTE: stringResult = impl.leftContext; break; case Id_rightContext: case Id_QUOTE: stringResult = impl.rightContext; break; default: { // Must be one of $1..$9, convert to 0..8 int substring_number = shifted - DOLLAR_ID_BASE - 1; stringResult = impl.getParenSubString (substring_number); break; } } return (stringResult == null) ? "" : stringResult.ToString (); } return base.GetInstanceIdValue (id); } protected internal override void SetInstanceIdValue (int id, object value) { int shifted = id - base.MaxInstanceId; switch (shifted) { case Id_multiline: case Id_STAR: Impl.multiline = ScriptConvert.ToBoolean (value); return; case Id_input: case Id_UNDERSCORE: Impl.input = ScriptConvert.ToString (value); return; } base.SetInstanceIdValue (id, value); } } }
using System.Collections.Generic; using System.Threading.Tasks; using Abp.Application.Features; using Abp.Application.Navigation; using Abp.Authorization; using Abp.Configuration; using Abp.Configuration.Startup; using Abp.Localization; using Abp.Runtime.Session; using Abp.Timing; using Abp.Timing.Timezone; using Abp.Web.Models.AbpUserConfiguration; using Abp.Web.Security.AntiForgery; using System.Linq; using Abp.Dependency; using Abp.Extensions; using System.Globalization; namespace Abp.Web.Configuration { public class AbpUserConfigurationBuilder : ITransientDependency { private readonly IAbpStartupConfiguration _startupConfiguration; protected IMultiTenancyConfig MultiTenancyConfig { get; } protected ILanguageManager LanguageManager { get; } protected ILocalizationManager LocalizationManager { get; } protected IFeatureManager FeatureManager { get; } protected IFeatureChecker FeatureChecker { get; } protected IPermissionManager PermissionManager { get; } protected IUserNavigationManager UserNavigationManager { get; } protected ISettingDefinitionManager SettingDefinitionManager { get; } protected ISettingManager SettingManager { get; } protected IAbpAntiForgeryConfiguration AbpAntiForgeryConfiguration { get; } protected IAbpSession AbpSession { get; } protected IPermissionChecker PermissionChecker { get; } protected Dictionary<string, object> CustomDataConfig { get; } private readonly IIocResolver _iocResolver; public AbpUserConfigurationBuilder( IMultiTenancyConfig multiTenancyConfig, ILanguageManager languageManager, ILocalizationManager localizationManager, IFeatureManager featureManager, IFeatureChecker featureChecker, IPermissionManager permissionManager, IUserNavigationManager userNavigationManager, ISettingDefinitionManager settingDefinitionManager, ISettingManager settingManager, IAbpAntiForgeryConfiguration abpAntiForgeryConfiguration, IAbpSession abpSession, IPermissionChecker permissionChecker, IIocResolver iocResolver, IAbpStartupConfiguration startupConfiguration) { MultiTenancyConfig = multiTenancyConfig; LanguageManager = languageManager; LocalizationManager = localizationManager; FeatureManager = featureManager; FeatureChecker = featureChecker; PermissionManager = permissionManager; UserNavigationManager = userNavigationManager; SettingDefinitionManager = settingDefinitionManager; SettingManager = settingManager; AbpAntiForgeryConfiguration = abpAntiForgeryConfiguration; AbpSession = abpSession; PermissionChecker = permissionChecker; _iocResolver = iocResolver; _startupConfiguration = startupConfiguration; CustomDataConfig = new Dictionary<string, object>(); } public virtual async Task<AbpUserConfigurationDto> GetAll() { return new AbpUserConfigurationDto { MultiTenancy = GetUserMultiTenancyConfig(), Session = GetUserSessionConfig(), Localization = GetUserLocalizationConfig(), Features = await GetUserFeaturesConfig(), Auth = await GetUserAuthConfig(), Nav = await GetUserNavConfig(), Setting = await GetUserSettingConfig(), Clock = GetUserClockConfig(), Timing = await GetUserTimingConfig(), Security = GetUserSecurityConfig(), Custom = _startupConfiguration.GetCustomConfig() }; } protected virtual AbpMultiTenancyConfigDto GetUserMultiTenancyConfig() { return new AbpMultiTenancyConfigDto { IsEnabled = MultiTenancyConfig.IsEnabled, IgnoreFeatureCheckForHostUsers = MultiTenancyConfig.IgnoreFeatureCheckForHostUsers }; } protected virtual AbpUserSessionConfigDto GetUserSessionConfig() { return new AbpUserSessionConfigDto { UserId = AbpSession.UserId, TenantId = AbpSession.TenantId, ImpersonatorUserId = AbpSession.ImpersonatorUserId, ImpersonatorTenantId = AbpSession.ImpersonatorTenantId, MultiTenancySide = AbpSession.MultiTenancySide }; } protected virtual AbpUserLocalizationConfigDto GetUserLocalizationConfig() { var currentCulture = CultureInfo.CurrentUICulture; var languages = LanguageManager.GetLanguages(); var config = new AbpUserLocalizationConfigDto { CurrentCulture = new AbpUserCurrentCultureConfigDto { Name = currentCulture.Name, DisplayName = currentCulture.DisplayName }, Languages = languages.ToList() }; if (languages.Count > 0) { config.CurrentLanguage = LanguageManager.CurrentLanguage; } var sources = LocalizationManager.GetAllSources().OrderBy(s => s.Name).ToArray(); config.Sources = sources.Select(s => new AbpLocalizationSourceDto { Name = s.Name, Type = s.GetType().Name }).ToList(); config.Values = new Dictionary<string, Dictionary<string, string>>(); foreach (var source in sources) { var stringValues = source.GetAllStrings(currentCulture).OrderBy(s => s.Name).ToList(); var stringDictionary = stringValues .ToDictionary(_ => _.Name, _ => _.Value); config.Values.Add(source.Name, stringDictionary); } return config; } protected virtual async Task<AbpUserFeatureConfigDto> GetUserFeaturesConfig() { var config = new AbpUserFeatureConfigDto() { AllFeatures = new Dictionary<string, AbpStringValueDto>() }; var allFeatures = FeatureManager.GetAll().ToList(); if (AbpSession.TenantId.HasValue) { var currentTenantId = AbpSession.GetTenantId(); foreach (var feature in allFeatures) { var value = await FeatureChecker.GetValueAsync(currentTenantId, feature.Name); config.AllFeatures.Add(feature.Name, new AbpStringValueDto { Value = value }); } } else { foreach (var feature in allFeatures) { config.AllFeatures.Add(feature.Name, new AbpStringValueDto { Value = feature.DefaultValue }); } } return config; } protected virtual async Task<AbpUserAuthConfigDto> GetUserAuthConfig() { var config = new AbpUserAuthConfigDto(); var allPermissionNames = PermissionManager.GetAllPermissions(false).Select(p => p.Name).ToList(); var grantedPermissionNames = new List<string>(); if (AbpSession.UserId.HasValue) { foreach (var permissionName in allPermissionNames) { if (await PermissionChecker.IsGrantedAsync(permissionName)) { grantedPermissionNames.Add(permissionName); } } } config.AllPermissions = allPermissionNames.ToDictionary(permissionName => permissionName, permissionName => "true"); config.GrantedPermissions = grantedPermissionNames.ToDictionary(permissionName => permissionName, permissionName => "true"); return config; } protected virtual async Task<AbpUserNavConfigDto> GetUserNavConfig() { var userMenus = await UserNavigationManager.GetMenusAsync(AbpSession.ToUserIdentifier()); return new AbpUserNavConfigDto { Menus = userMenus.ToDictionary(userMenu => userMenu.Name, userMenu => userMenu) }; } protected virtual async Task<AbpUserSettingConfigDto> GetUserSettingConfig() { var config = new AbpUserSettingConfigDto { Values = new Dictionary<string, string>() }; var settingDefinitions = SettingDefinitionManager .GetAllSettingDefinitions(); using (var scope = _iocResolver.CreateScope()) { foreach (var settingDefinition in settingDefinitions) { if (!await settingDefinition.ClientVisibilityProvider.CheckVisible(scope)) { continue; } var settingValue = await SettingManager.GetSettingValueAsync(settingDefinition.Name); config.Values.Add(settingDefinition.Name, settingValue); } } return config; } protected virtual AbpUserClockConfigDto GetUserClockConfig() { return new AbpUserClockConfigDto { Provider = Clock.Provider.GetType().Name.ToCamelCase() }; } protected virtual async Task<AbpUserTimingConfigDto> GetUserTimingConfig() { var timezoneId = await SettingManager.GetSettingValueAsync(TimingSettingNames.TimeZone); var timezone = TimezoneHelper.FindTimeZoneInfo(timezoneId); return new AbpUserTimingConfigDto { TimeZoneInfo = new AbpUserTimeZoneConfigDto { Windows = new AbpUserWindowsTimeZoneConfigDto { TimeZoneId = timezoneId, BaseUtcOffsetInMilliseconds = timezone.BaseUtcOffset.TotalMilliseconds, CurrentUtcOffsetInMilliseconds = timezone.GetUtcOffset(Clock.Now).TotalMilliseconds, IsDaylightSavingTimeNow = timezone.IsDaylightSavingTime(Clock.Now) }, Iana = new AbpUserIanaTimeZoneConfigDto { TimeZoneId = TimezoneHelper.WindowsToIana(timezoneId) } } }; } protected virtual AbpUserSecurityConfigDto GetUserSecurityConfig() { return new AbpUserSecurityConfigDto { AntiForgery = new AbpUserAntiForgeryConfigDto { TokenCookieName = AbpAntiForgeryConfiguration.TokenCookieName, TokenHeaderName = AbpAntiForgeryConfiguration.TokenHeaderName } }; } } }
// 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.DotNet.Cli.Build.Framework; using System.Collections.Generic; using System.IO; using System.Linq; using Xunit; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.NativeHosting { public partial class ComponentActivation : IClassFixture<ComponentActivation.SharedTestState> { private const string ComponentActivationArg = "load_assembly_and_get_function_pointer"; private readonly SharedTestState sharedState; public ComponentActivation(SharedTestState sharedTestState) { sharedState = sharedTestState; } [Theory] [InlineData(true, true, true)] [InlineData(false, true, true)] [InlineData(true, false, true)] [InlineData(true, true, false)] public void CallDelegate(bool validPath, bool validType, bool validMethod) { var componentProject = sharedState.ComponentWithNoDependenciesFixture.TestProject; string[] args = { ComponentActivationArg, sharedState.HostFxrPath, componentProject.RuntimeConfigJson, validPath ? componentProject.AppDll : "BadPath...", validType ? sharedState.ComponentTypeName : $"Component.BadType, {componentProject.AssemblyName}", validMethod ? sharedState.ComponentEntryPoint1 : "BadMethod", }; CommandResult result = Command.Create(sharedState.NativeHostPath, args) .CaptureStdErr() .CaptureStdOut() .EnvironmentVariable("COREHOST_TRACE", "1") .EnvironmentVariable("DOTNET_ROOT", sharedState.DotNetRoot) .EnvironmentVariable("DOTNET_ROOT(x86)", sharedState.DotNetRoot) .Execute(); result.Should() .InitializeContextForConfig(componentProject.RuntimeConfigJson); if (validPath && validType && validMethod) { result.Should().Pass() .And.ExecuteComponentEntryPoint(sharedState.ComponentEntryPoint1, 1, 1); } else { result.Should().Fail(); } } [Theory] [InlineData(1)] [InlineData(10)] public void CallDelegate_MultipleEntryPoints(int callCount) { var componentProject = sharedState.ComponentWithNoDependenciesFixture.TestProject; string[] baseArgs = { ComponentActivationArg, sharedState.HostFxrPath, componentProject.RuntimeConfigJson, }; string[] componentInfo = { // ComponentEntryPoint1 componentProject.AppDll, sharedState.ComponentTypeName, sharedState.ComponentEntryPoint1, // ComponentEntryPoint2 componentProject.AppDll, sharedState.ComponentTypeName, sharedState.ComponentEntryPoint2, }; IEnumerable<string> args = baseArgs; for (int i = 0; i < callCount; ++i) { args = args.Concat(componentInfo); } CommandResult result = Command.Create(sharedState.NativeHostPath, args) .CaptureStdErr() .CaptureStdOut() .EnvironmentVariable("COREHOST_TRACE", "1") .EnvironmentVariable("DOTNET_ROOT", sharedState.DotNetRoot) .EnvironmentVariable("DOTNET_ROOT(x86)", sharedState.DotNetRoot) .Execute(); result.Should().Pass() .And.InitializeContextForConfig(componentProject.RuntimeConfigJson); for (int i = 1; i <= callCount; ++i) { result.Should() .ExecuteComponentEntryPoint(sharedState.ComponentEntryPoint1, i * 2 - 1, i) .And.ExecuteComponentEntryPoint(sharedState.ComponentEntryPoint2, i * 2, i); } } [Theory] [InlineData(1)] [InlineData(10)] public void CallDelegate_MultipleComponents(int callCount) { var componentProject = sharedState.ComponentWithNoDependenciesFixture.TestProject; var componentProjectCopy = componentProject.Copy(); string[] baseArgs = { ComponentActivationArg, sharedState.HostFxrPath, componentProject.RuntimeConfigJson, }; string[] componentInfo = { // Component componentProject.AppDll, sharedState.ComponentTypeName, sharedState.ComponentEntryPoint1, // Component copy componentProjectCopy.AppDll, sharedState.ComponentTypeName, sharedState.ComponentEntryPoint2, }; IEnumerable<string> args = baseArgs; for (int i = 0; i < callCount; ++i) { args = args.Concat(componentInfo); } CommandResult result = Command.Create(sharedState.NativeHostPath, args) .CaptureStdErr() .CaptureStdOut() .EnvironmentVariable("COREHOST_TRACE", "1") .EnvironmentVariable("DOTNET_ROOT", sharedState.DotNetRoot) .EnvironmentVariable("DOTNET_ROOT(x86)", sharedState.DotNetRoot) .Execute(); result.Should().Pass() .And.InitializeContextForConfig(componentProject.RuntimeConfigJson); for (int i = 1; i <= callCount; ++i) { result.Should() .ExecuteComponentEntryPoint(sharedState.ComponentEntryPoint1, i, i) .And.ExecuteComponentEntryPoint(sharedState.ComponentEntryPoint2, i, i); } } public class SharedTestState : SharedTestStateBase { public string HostFxrPath { get; } public string DotNetRoot { get; } public TestProjectFixture ComponentWithNoDependenciesFixture { get; } public string ComponentTypeName { get; } public string ComponentEntryPoint1 => "ComponentEntryPoint1"; public string ComponentEntryPoint2 => "ComponentEntryPoint2"; public SharedTestState() { var dotNet = new Microsoft.DotNet.Cli.Build.DotNetCli(Path.Combine(TestArtifact.TestArtifactsPath, "sharedFrameworkPublish")); DotNetRoot = dotNet.BinPath; HostFxrPath = dotNet.GreatestVersionHostFxrFilePath; ComponentWithNoDependenciesFixture = new TestProjectFixture("ComponentWithNoDependencies", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .PublishProject(); ComponentTypeName = $"Component.Component, {ComponentWithNoDependenciesFixture.TestProject.AssemblyName}"; } protected override void Dispose(bool disposing) { if (ComponentWithNoDependenciesFixture != null) ComponentWithNoDependenciesFixture.Dispose(); base.Dispose(disposing); } } } internal static class ComponentActivationResultExtensions { public static FluentAssertions.AndConstraint<CommandResultAssertions> ExecuteComponentEntryPoint(this CommandResultAssertions assertion, string methodName, int componentCallCount, int returnValue) { return assertion.HaveStdOutContaining($"Called {methodName}(0xdeadbeef, 42) - component call count: {componentCallCount}") .And.HaveStdOutContaining($"{methodName} delegate result: 0x{returnValue.ToString("x")}"); } } }
using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Documents; using Lucene.Net.Support; namespace Lucene.Net.Search.Payloads { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Lucene.Net.Analysis; using NUnit.Framework; using System.IO; using BytesRef = Lucene.Net.Util.BytesRef; using DefaultSimilarity = Lucene.Net.Search.Similarities.DefaultSimilarity; using Directory = Lucene.Net.Store.Directory; using DirectoryReader = Lucene.Net.Index.DirectoryReader; using Document = Documents.Document; using English = Lucene.Net.Util.English; using Field = Field; using FieldInvertState = Lucene.Net.Index.FieldInvertState; using IndexReader = Lucene.Net.Index.IndexReader; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MultiSpansWrapper = Lucene.Net.Search.Spans.MultiSpansWrapper; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using Similarity = Lucene.Net.Search.Similarities.Similarity; using Spans = Lucene.Net.Search.Spans.Spans; using SpanTermQuery = Lucene.Net.Search.Spans.SpanTermQuery; using Term = Lucene.Net.Index.Term; [TestFixture] public class TestPayloadTermQuery : LuceneTestCase { private static IndexSearcher Searcher; private static IndexReader Reader; private static readonly Similarity similarity = new BoostingSimilarity(); private static readonly byte[] PayloadField = { 1 }; private static readonly byte[] PayloadMultiField1 = { 2 }; private static readonly byte[] PayloadMultiField2 = { 4 }; protected internal static Directory Directory; private class PayloadAnalyzer : Analyzer { internal PayloadAnalyzer() : base(PER_FIELD_REUSE_STRATEGY) { } protected internal override TokenStreamComponents CreateComponents(string fieldName, TextReader reader) { Tokenizer result = new MockTokenizer(reader, MockTokenizer.SIMPLE, true); return new TokenStreamComponents(result, new PayloadFilter(result, fieldName)); } } private class PayloadFilter : TokenFilter { internal readonly string FieldName; internal int NumSeen = 0; internal readonly IPayloadAttribute PayloadAtt; public PayloadFilter(TokenStream input, string fieldName) : base(input) { this.FieldName = fieldName; PayloadAtt = AddAttribute<IPayloadAttribute>(); } public sealed override bool IncrementToken() { bool hasNext = m_input.IncrementToken(); if (hasNext) { if (FieldName.Equals("field")) { PayloadAtt.Payload = new BytesRef(PayloadField); } else if (FieldName.Equals("multiField")) { if (NumSeen % 2 == 0) { PayloadAtt.Payload = new BytesRef(PayloadMultiField1); } else { PayloadAtt.Payload = new BytesRef(PayloadMultiField2); } NumSeen++; } return true; } else { return false; } } public override void Reset() { base.Reset(); this.NumSeen = 0; } } /// <summary> /// LUCENENET specific /// Is non-static because NewIndexWriterConfig is no longer static. /// </summary> [OneTimeSetUp] public override void BeforeClass() { base.BeforeClass(); Directory = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), Directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new PayloadAnalyzer()).SetSimilarity(similarity).SetMergePolicy(NewLogMergePolicy())); //writer.infoStream = System.out; for (int i = 0; i < 1000; i++) { Document doc = new Document(); Field noPayloadField = NewTextField(PayloadHelper.NO_PAYLOAD_FIELD, English.IntToEnglish(i), Field.Store.YES); //noPayloadField.setBoost(0); doc.Add(noPayloadField); doc.Add(NewTextField("field", English.IntToEnglish(i), Field.Store.YES)); doc.Add(NewTextField("multiField", English.IntToEnglish(i) + " " + English.IntToEnglish(i), Field.Store.YES)); writer.AddDocument(doc); } Reader = writer.Reader; writer.Dispose(); Searcher = NewSearcher(Reader); Searcher.Similarity = similarity; } [OneTimeTearDown] public override void AfterClass() { Searcher = null; Reader.Dispose(); Reader = null; Directory.Dispose(); Directory = null; base.AfterClass(); } [Test] public virtual void Test() { PayloadTermQuery query = new PayloadTermQuery(new Term("field", "seventy"), new MaxPayloadFunction()); TopDocs hits = Searcher.Search(query, null, 100); Assert.IsTrue(hits != null, "hits is null and it shouldn't be"); Assert.IsTrue(hits.TotalHits == 100, "hits Size: " + hits.TotalHits + " is not: " + 100); //they should all have the exact same score, because they all contain seventy once, and we set //all the other similarity factors to be 1 Assert.IsTrue(hits.MaxScore == 1, hits.MaxScore + " does not equal: " + 1); for (int i = 0; i < hits.ScoreDocs.Length; i++) { ScoreDoc doc = hits.ScoreDocs[i]; Assert.IsTrue(doc.Score == 1, doc.Score + " does not equal: " + 1); } CheckHits.CheckExplanations(query, PayloadHelper.FIELD, Searcher, true); Spans spans = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, query); Assert.IsTrue(spans != null, "spans is null and it shouldn't be"); /*float score = hits.Score(0); for (int i =1; i < hits.Length(); i++) { Assert.IsTrue(score == hits.Score(i), "scores are not equal and they should be"); }*/ } [Test] public virtual void TestQuery() { PayloadTermQuery boostingFuncTermQuery = new PayloadTermQuery(new Term(PayloadHelper.MULTI_FIELD, "seventy"), new MaxPayloadFunction()); QueryUtils.Check(boostingFuncTermQuery); SpanTermQuery spanTermQuery = new SpanTermQuery(new Term(PayloadHelper.MULTI_FIELD, "seventy")); Assert.IsTrue(boostingFuncTermQuery.Equals(spanTermQuery) == spanTermQuery.Equals(boostingFuncTermQuery)); PayloadTermQuery boostingFuncTermQuery2 = new PayloadTermQuery(new Term(PayloadHelper.MULTI_FIELD, "seventy"), new AveragePayloadFunction()); QueryUtils.CheckUnequal(boostingFuncTermQuery, boostingFuncTermQuery2); } [Test] public virtual void TestMultipleMatchesPerDoc() { PayloadTermQuery query = new PayloadTermQuery(new Term(PayloadHelper.MULTI_FIELD, "seventy"), new MaxPayloadFunction()); TopDocs hits = Searcher.Search(query, null, 100); Assert.IsTrue(hits != null, "hits is null and it shouldn't be"); Assert.IsTrue(hits.TotalHits == 100, "hits Size: " + hits.TotalHits + " is not: " + 100); //they should all have the exact same score, because they all contain seventy once, and we set //all the other similarity factors to be 1 //System.out.println("Hash: " + seventyHash + " Twice Hash: " + 2*seventyHash); Assert.IsTrue(hits.MaxScore == 4.0, hits.MaxScore + " does not equal: " + 4.0); //there should be exactly 10 items that score a 4, all the rest should score a 2 //The 10 items are: 70 + i*100 where i in [0-9] int numTens = 0; for (int i = 0; i < hits.ScoreDocs.Length; i++) { ScoreDoc doc = hits.ScoreDocs[i]; if (doc.Doc % 10 == 0) { numTens++; Assert.IsTrue(doc.Score == 4.0, doc.Score + " does not equal: " + 4.0); } else { Assert.IsTrue(doc.Score == 2, doc.Score + " does not equal: " + 2); } } Assert.IsTrue(numTens == 10, numTens + " does not equal: " + 10); CheckHits.CheckExplanations(query, "field", Searcher, true); Spans spans = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, query); Assert.IsTrue(spans != null, "spans is null and it shouldn't be"); //should be two matches per document int count = 0; //100 hits times 2 matches per hit, we should have 200 in count while (spans.Next()) { count++; } Assert.IsTrue(count == 200, count + " does not equal: " + 200); } //Set includeSpanScore to false, in which case just the payload score comes through. [Test] public virtual void TestIgnoreSpanScorer() { PayloadTermQuery query = new PayloadTermQuery(new Term(PayloadHelper.MULTI_FIELD, "seventy"), new MaxPayloadFunction(), false); IndexReader reader = DirectoryReader.Open(Directory); IndexSearcher theSearcher = NewSearcher(reader); theSearcher.Similarity = new FullSimilarity(); TopDocs hits = Searcher.Search(query, null, 100); Assert.IsTrue(hits != null, "hits is null and it shouldn't be"); Assert.IsTrue(hits.TotalHits == 100, "hits Size: " + hits.TotalHits + " is not: " + 100); //they should all have the exact same score, because they all contain seventy once, and we set //all the other similarity factors to be 1 //System.out.println("Hash: " + seventyHash + " Twice Hash: " + 2*seventyHash); Assert.IsTrue(hits.MaxScore == 4.0, hits.MaxScore + " does not equal: " + 4.0); //there should be exactly 10 items that score a 4, all the rest should score a 2 //The 10 items are: 70 + i*100 where i in [0-9] int numTens = 0; for (int i = 0; i < hits.ScoreDocs.Length; i++) { ScoreDoc doc = hits.ScoreDocs[i]; if (doc.Doc % 10 == 0) { numTens++; Assert.IsTrue(doc.Score == 4.0, doc.Score + " does not equal: " + 4.0); } else { Assert.IsTrue(doc.Score == 2, doc.Score + " does not equal: " + 2); } } Assert.IsTrue(numTens == 10, numTens + " does not equal: " + 10); CheckHits.CheckExplanations(query, "field", Searcher, true); Spans spans = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, query); Assert.IsTrue(spans != null, "spans is null and it shouldn't be"); //should be two matches per document int count = 0; //100 hits times 2 matches per hit, we should have 200 in count while (spans.Next()) { count++; } reader.Dispose(); } [Test] public virtual void TestNoMatch() { PayloadTermQuery query = new PayloadTermQuery(new Term(PayloadHelper.FIELD, "junk"), new MaxPayloadFunction()); TopDocs hits = Searcher.Search(query, null, 100); Assert.IsTrue(hits != null, "hits is null and it shouldn't be"); Assert.IsTrue(hits.TotalHits == 0, "hits Size: " + hits.TotalHits + " is not: " + 0); } [Test] public virtual void TestNoPayload() { PayloadTermQuery q1 = new PayloadTermQuery(new Term(PayloadHelper.NO_PAYLOAD_FIELD, "zero"), new MaxPayloadFunction()); PayloadTermQuery q2 = new PayloadTermQuery(new Term(PayloadHelper.NO_PAYLOAD_FIELD, "foo"), new MaxPayloadFunction()); BooleanClause c1 = new BooleanClause(q1, Occur.MUST); BooleanClause c2 = new BooleanClause(q2, Occur.MUST_NOT); BooleanQuery query = new BooleanQuery(); query.Add(c1); query.Add(c2); TopDocs hits = Searcher.Search(query, null, 100); Assert.IsTrue(hits != null, "hits is null and it shouldn't be"); Assert.IsTrue(hits.TotalHits == 1, "hits Size: " + hits.TotalHits + " is not: " + 1); int[] results = new int[1]; results[0] = 0; //hits.ScoreDocs[0].Doc; CheckHits.CheckHitCollector(Random(), query, PayloadHelper.NO_PAYLOAD_FIELD, Searcher, results, Similarity); } internal class BoostingSimilarity : DefaultSimilarity { public override float QueryNorm(float sumOfSquaredWeights) { return 1; } public override float Coord(int overlap, int maxOverlap) { return 1; } // TODO: Remove warning after API has been finalized public override float ScorePayload(int docId, int start, int end, BytesRef payload) { //we know it is size 4 here, so ignore the offset/length return payload.Bytes[payload.Offset]; } //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Make everything else 1 so we see the effect of the payload //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! public override float LengthNorm(FieldInvertState state) { return state.Boost; } public override float SloppyFreq(int distance) { return 1; } public override float Idf(long docFreq, long numDocs) { return 1; } public override float Tf(float freq) { return freq == 0 ? 0 : 1; } } internal class FullSimilarity : DefaultSimilarity { public virtual float ScorePayload(int docId, string fieldName, sbyte[] payload, int offset, int length) { //we know it is size 4 here, so ignore the offset/length return payload[offset]; } } } }
//------------------------------------------------------------------------------ // <copyright file="RootAction.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml.Xsl.XsltOld { using Res = System.Xml.Utils.Res; using System; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl.Runtime; using MS.Internal.Xml.XPath; using System.Security; internal class Key { XmlQualifiedName name; int matchKey; int useKey; ArrayList keyNodes; public Key(XmlQualifiedName name, int matchkey, int usekey) { this.name = name; this.matchKey = matchkey; this.useKey = usekey; this.keyNodes = null; } public XmlQualifiedName Name { get { return this.name; } } public int MatchKey { get { return this.matchKey; } } public int UseKey { get { return this.useKey; } } public void AddKey(XPathNavigator root, Hashtable table) { if (this.keyNodes == null) { this.keyNodes = new ArrayList(); } this.keyNodes.Add(new DocumentKeyList(root, table)); } public Hashtable GetKeys(XPathNavigator root) { if (this.keyNodes != null) { for(int i=0; i < keyNodes.Count; i++) { if (((DocumentKeyList)keyNodes[i]).RootNav.IsSamePosition(root)) { return ((DocumentKeyList)keyNodes[i]).KeyTable; } } } return null; } public Key Clone() { return new Key(name, matchKey, useKey); } } internal struct DocumentKeyList { XPathNavigator rootNav; Hashtable keyTable; public DocumentKeyList(XPathNavigator rootNav, Hashtable keyTable) { this.rootNav = rootNav; this.keyTable = keyTable; } public XPathNavigator RootNav { get { return this.rootNav ; } } public Hashtable KeyTable { get { return this.keyTable; } } } internal class RootAction : TemplateBaseAction { private const int QueryInitialized = 2; private const int RootProcessed = 3; private Hashtable attributeSetTable = new Hashtable(); private Hashtable decimalFormatTable = new Hashtable(); private List<Key> keyList; private XsltOutput output; public Stylesheet builtInSheet; public PermissionSet permissions; internal XsltOutput Output { get { if (this.output == null) { this.output = new XsltOutput(); } return this.output; } } /* * Compile */ internal override void Compile(Compiler compiler) { CompileDocument(compiler, /*inInclude*/ false); } internal void InsertKey(XmlQualifiedName name, int MatchKey, int UseKey){ if (this.keyList == null) { this.keyList = new List<Key>(); } this.keyList.Add(new Key(name, MatchKey, UseKey)); } internal AttributeSetAction GetAttributeSet(XmlQualifiedName name) { AttributeSetAction action = (AttributeSetAction) this.attributeSetTable[name]; if(action == null) { throw XsltException.Create(Res.Xslt_NoAttributeSet, name.ToString()); } return action; } public void PorcessAttributeSets(Stylesheet rootStylesheet) { MirgeAttributeSets(rootStylesheet); // As we mentioned we need to invert all lists. foreach (AttributeSetAction attSet in this.attributeSetTable.Values) { if (attSet.containedActions != null) { attSet.containedActions.Reverse(); } } // ensures there are no cycles in the attribute-sets use dfs marking method CheckAttributeSets_RecurceInList(new Hashtable(), this.attributeSetTable.Keys); } private void MirgeAttributeSets(Stylesheet stylesheet) { // mirge stylesheet.AttributeSetTable to this.AttributeSetTable if (stylesheet.AttributeSetTable != null) { foreach (AttributeSetAction srcAttSet in stylesheet.AttributeSetTable.Values) { ArrayList srcAttList = srcAttSet.containedActions; AttributeSetAction dstAttSet = (AttributeSetAction) this.attributeSetTable[srcAttSet.Name]; if (dstAttSet == null) { dstAttSet = new AttributeSetAction(); { dstAttSet.name = srcAttSet.Name; dstAttSet.containedActions = new ArrayList(); } this.attributeSetTable[srcAttSet.Name] = dstAttSet; } ArrayList dstAttList = dstAttSet.containedActions; // We adding attributes in reverse order for purpuse. In the mirged list most importent attset shoud go last one // so we'll need to invert dstAttList finaly. if (srcAttList != null) { for(int src = srcAttList.Count - 1; 0 <= src; src --) { // We can ignore duplicate attibutes here. dstAttList.Add(srcAttList[src]); } } } } foreach (Stylesheet importedStylesheet in stylesheet.Imports) { MirgeAttributeSets(importedStylesheet); } } private void CheckAttributeSets_RecurceInList(Hashtable markTable, ICollection setQNames) { const string PROCESSING = "P"; const string DONE = "D"; foreach (XmlQualifiedName qname in setQNames) { object mark = markTable[qname]; if (mark == (object) PROCESSING) { throw XsltException.Create(Res.Xslt_CircularAttributeSet, qname.ToString()); } else if (mark == (object) DONE) { continue; // optimization: we already investigated this attribute-set. } else { Debug.Assert(mark == null); markTable[qname] = (object) PROCESSING; CheckAttributeSets_RecurceInContainer(markTable, GetAttributeSet(qname)); markTable[qname] = (object) DONE; } } } private void CheckAttributeSets_RecurceInContainer(Hashtable markTable, ContainerAction container) { if (container.containedActions == null) { return; } foreach(Action action in container.containedActions) { if(action is UseAttributeSetsAction) { CheckAttributeSets_RecurceInList(markTable, ((UseAttributeSetsAction)action).UsedSets); } else if(action is ContainerAction) { CheckAttributeSets_RecurceInContainer(markTable, (ContainerAction)action); } } } internal void AddDecimalFormat(XmlQualifiedName name, DecimalFormat formatinfo) { DecimalFormat exist = (DecimalFormat) this.decimalFormatTable[name]; if (exist != null) { NumberFormatInfo info = exist.info; NumberFormatInfo newinfo = formatinfo.info; if (info.NumberDecimalSeparator != newinfo.NumberDecimalSeparator || info.NumberGroupSeparator != newinfo.NumberGroupSeparator || info.PositiveInfinitySymbol != newinfo.PositiveInfinitySymbol || info.NegativeSign != newinfo.NegativeSign || info.NaNSymbol != newinfo.NaNSymbol || info.PercentSymbol != newinfo.PercentSymbol || info.PerMilleSymbol != newinfo.PerMilleSymbol || exist.zeroDigit != formatinfo.zeroDigit || exist.digit != formatinfo.digit || exist.patternSeparator != formatinfo.patternSeparator ) { throw XsltException.Create(Res.Xslt_DupDecimalFormat, name.ToString()); } } this.decimalFormatTable[name] = formatinfo; } internal DecimalFormat GetDecimalFormat(XmlQualifiedName name) { return this.decimalFormatTable[name] as DecimalFormat; } internal List<Key> KeyList{ get { return this.keyList; } } internal override void Execute(Processor processor, ActionFrame frame) { Debug.Assert(processor != null && frame != null); switch (frame.State) { case Initialized: frame.AllocateVariables(variableCount); XPathNavigator root = processor.Document.Clone(); root.MoveToRoot(); frame.InitNodeSet(new XPathSingletonIterator(root)); if (this.containedActions != null && this.containedActions.Count > 0) { processor.PushActionFrame(frame); } frame.State = QueryInitialized; break; case QueryInitialized: Debug.Assert(frame.State == QueryInitialized); frame.NextNode(processor); Debug.Assert(Processor.IsRoot(frame.Node)); if (processor.Debugger != null) { // this is like apply-templates, but we don't have it on stack. // Pop the stack, otherwise last instruction will be on it. processor.PopDebuggerStack(); } processor.PushTemplateLookup(frame.NodeSet, /*mode:*/null, /*importsOf:*/null); frame.State = RootProcessed; break; case RootProcessed: Debug.Assert(frame.State == RootProcessed); frame.Finished(); break; default: Debug.Fail("Invalid RootAction execution state"); break; } } } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall; using FlatRedBall.Gui; using FlatRedBall.Content.AnimationChain; using FlatRedBall.Graphics; using FlatRedBall.Math; using System.Collections; using FlatRedBall.Graphics.Animation; namespace EditorObjects.Gui { public class SpritePropertyGrid : PropertyGrid<Sprite> { #region Fields public static PositionedObjectList<Camera> ExtraCamerasForScale = new PositionedObjectList<Camera>(); private ComboBox mCurrentChainNameComboBox; private ToggleButton mPixelPerfectTextureCoordinates; // Store these in case we need to round the values for pixel-perfect values private UpDown mTopTextureCoordinateUpDown; private UpDown mBottomTextureCoordinateUpDown; private UpDown mLeftTextureCoordinateUpDown; private UpDown mRightTextureCoordinateUpDown; private FileTextBox mAnimationChainFileTextBox; private ComboBox mOrderingMode; private Button mSetPixelPerfectScaleButton; SpriteList mSpriteList; UpDown mLeftPixel; UpDown mTopPixel; UpDown mPixelWidth; UpDown mPixelHeight; #endregion #region Properties public bool ShowWarningOnNonPowerOfTwoTexture { get; set; } public override Sprite SelectedObject { get { return base.SelectedObject; } set { base.SelectedObject = value; if (MakeVisibleOnSpriteSet) { if (!Visible && (SelectedObject != null)) { GuiManager.BringToFront(this); } Visible = (SelectedObject != null); } #region Update the Ordered GUI if (SelectedObject != null) { // for performance reasons this only updates when the selected changes if (SpriteManager.ZBufferedSprites.Contains(SelectedObject)) { mOrderingMode.Text = OrderingMode.ZBuffered.ToString(); } else { mOrderingMode.Text = OrderingMode.DistanceFromCamera.ToString(); } } #endregion } } public bool MakeVisibleOnSpriteSet { get; set; } #endregion #region Event Methods private void SetAnimationChainOnSprite(Window callingWindow) { if (mSelectedObject != null) { mSelectedObject.AnimationChains = AnimationChainListSave.FromFile(((FileTextBox)callingWindow).Text).ToAnimationChainList(this.ContentManagerName); } } private void SetOrderingMode(Window callingWindow) { if (SelectedObject != null) { ComboBox asComboBox = callingWindow as ComboBox; OrderingMode orderingMode = ((OrderingMode)asComboBox.SelectedObject); if (orderingMode == OrderingMode.ZBuffered) { SpriteManager.ConvertToZBufferedSprite(SelectedObject); } else { SpriteManager.ConvertToOrderedSprite(SelectedObject); } } } private void SetPixelPerfectScaleClick(Window callingWindow) { OkListWindow okListWindow = new OkListWindow("Which camera would you like to scale according to?", "Select Camera"); foreach (Camera camera in SpriteManager.Cameras) { okListWindow.AddItem(camera.Name, camera); } foreach (Camera camera in ExtraCamerasForScale) { okListWindow.AddItem(camera.Name, camera); } okListWindow.OkButtonClick += SetPixelPerfectScaleOk; } private void SetPixelPerfectScaleOk(Window callingWindow) { if (SelectedObject != null && SelectedObject.Texture != null) { OkListWindow okListWindow = callingWindow as OkListWindow; Camera camera = okListWindow.GetFirstHighlightedObject() as Camera; if (camera == null) { GuiManager.ShowMessageBox("No Camera was selected, so Scale has not changed", "No Camera"); } else { float pixelsPerUnit = camera.PixelsPerUnitAt(SelectedObject.Z); SelectedObject.ScaleX = .5f * SelectedObject.Texture.Width / pixelsPerUnit; SelectedObject.ScaleY = .5f * SelectedObject.Texture.Height / pixelsPerUnit; } } } private void ShowCantEditAbsoluteValuesMessage(Window callingWindow) { if (SelectedObject.Parent != null) { GuiManager.ShowMessageBox( "The Sprite that you are editing is attached to another parent object. " + "To edit the position or rotation of this object, use the Relative category.", "Can't edit absolute values"); } } private void ShowAnimationPopup(Window callingWindow) { GuiManager.ToolTipText = mAnimationChainFileTextBox.Text; } private void SplitSpriteClick(Window callingWindow) { if (ObjectDisplaying != null) { float textureWidth = ObjectDisplaying.RightTextureCoordinate - ObjectDisplaying.LeftTextureCoordinate; int wide = (int)(.5 + Math.Ceiling(textureWidth)); float textureHeight = ObjectDisplaying.BottomTextureCoordinate - ObjectDisplaying.TopTextureCoordinate; int height = (int)(.5 + Math.Ceiling(textureHeight)); float scaleXOverTextureWidth = ObjectDisplaying.ScaleX / textureWidth; float scaleYOverTextureHeight = ObjectDisplaying.ScaleY / textureHeight; float currentLeftTextureCoordinate = ObjectDisplaying.LeftTextureCoordinate; float currentRightTextureCoordinate = Math.Min(ObjectDisplaying.RightTextureCoordinate, 1); float currentTopTextureCoordinate = ObjectDisplaying.TopTextureCoordinate; float currentBottomTextureCoordinate = Math.Min(ObjectDisplaying.BottomTextureCoordinate, 1) ; float maxRightTextureCoordinate = ObjectDisplaying.RightTextureCoordinate; float maxBottomTextureCoordinate = ObjectDisplaying.BottomTextureCoordinate; float startLeft = ObjectDisplaying.X - ObjectDisplaying.ScaleX; float startTop = ObjectDisplaying.Y + ObjectDisplaying.ScaleY; for (int x = 0; x < wide; x++) { currentTopTextureCoordinate = ObjectDisplaying.TopTextureCoordinate; currentBottomTextureCoordinate = Math.Min(ObjectDisplaying.BottomTextureCoordinate, 1); for (int y = 0; y < height; y++) { Sprite newSprite = null; if (x == 0 && y == 0) { newSprite = ObjectDisplaying; } else { newSprite = ObjectDisplaying.Clone(); SpriteManager.AddSprite(newSprite); mSpriteList.Add(newSprite); FlatRedBall.Utilities.StringFunctions.MakeNameUnique<Sprite>( newSprite, mSpriteList); } newSprite.LeftTextureCoordinate = currentLeftTextureCoordinate; newSprite.RightTextureCoordinate = currentRightTextureCoordinate; newSprite.TopTextureCoordinate = currentTopTextureCoordinate; newSprite.BottomTextureCoordinate = currentBottomTextureCoordinate; newSprite.ScaleX = scaleXOverTextureWidth * (newSprite.RightTextureCoordinate - newSprite.LeftTextureCoordinate); newSprite.ScaleY = scaleYOverTextureHeight * (newSprite.BottomTextureCoordinate - newSprite.TopTextureCoordinate); newSprite.X = startLeft + 2 * scaleXOverTextureWidth * (newSprite.LeftTextureCoordinate - ObjectDisplaying.LeftTextureCoordinate) + newSprite.ScaleX; newSprite.Y = startTop - 2 * scaleYOverTextureHeight * (newSprite.TopTextureCoordinate - ObjectDisplaying.TopTextureCoordinate) - newSprite.ScaleY; currentTopTextureCoordinate = currentBottomTextureCoordinate; currentBottomTextureCoordinate = currentTopTextureCoordinate + 1; // Since FSB only allows texture coordinates between 0 and 1, let's make sure that we're not exceeding that. if (newSprite.LeftTextureCoordinate >= 1) { int leftInt = (int)newSprite.LeftTextureCoordinate; newSprite.LeftTextureCoordinate -= leftInt; newSprite.RightTextureCoordinate -= leftInt; } if (newSprite.TopTextureCoordinate >= 1) { int topInt = (int)newSprite.TopTextureCoordinate; newSprite.TopTextureCoordinate -= topInt; newSprite.BottomTextureCoordinate -= topInt; } } currentLeftTextureCoordinate = currentRightTextureCoordinate; currentRightTextureCoordinate = currentLeftTextureCoordinate + 1; } //// let's just add 3 new Sprites. //Sprite sprite = SpriteManager.AddSprite("redball.bmp"); //mSpriteList.Add(sprite); //sprite.XVelocity = 1; //sprite.Name = "test"; } } private void OnTextureChange(Window callingWindow) { if (ShowWarningOnNonPowerOfTwoTexture && SelectedObject.Texture != null) { if (MathFunctions.IsPowerOfTwo(SelectedObject.Texture.Width) == false || MathFunctions.IsPowerOfTwo(SelectedObject.Texture.Height) == false) { GuiManager.ShowMessageBox("The texture " + SelectedObject.Texture.Name + " is not power of two. " + "Its dimensions are " + SelectedObject.Texture.Width + " x " + SelectedObject.Texture.Height, "Texture dimensions not power of two"); } } } private void ChangeLeftPixel(Window callingWindow) { if (mSelectedObject != null && mSelectedObject.Texture != null) { mSelectedObject.LeftTextureCoordinate = mLeftPixel.CurrentValue / mSelectedObject.Texture.Width; mSelectedObject.RightTextureCoordinate = mSelectedObject.LeftTextureCoordinate + mPixelWidth.CurrentValue / mSelectedObject.Texture.Width; } } private void ChangeTopPixel(Window callingWindow) { if (mSelectedObject != null && mSelectedObject.Texture != null) { mSelectedObject.TopTextureCoordinate = mTopPixel.CurrentValue / mSelectedObject.Texture.Height; mSelectedObject.BottomTextureCoordinate = mSelectedObject.TopTextureCoordinate + mPixelHeight.CurrentValue / mSelectedObject.Texture.Height; } } private void ChangePixelWidth(Window callingWindow) { if (mSelectedObject != null && mSelectedObject.Texture != null) { mSelectedObject.RightTextureCoordinate = (mLeftPixel.CurrentValue + mPixelWidth.CurrentValue) / mSelectedObject.Texture.Width; } } private void ChangePixelHeight(Window callingWindow) { if (mSelectedObject != null && mSelectedObject.Texture != null) { mSelectedObject.BottomTextureCoordinate = (mTopPixel.CurrentValue + mPixelHeight.CurrentValue) / mSelectedObject.Texture.Height; } } private void UpdateCustomUI(Window callingWindow) { if (SelectedObject != null && SelectedObject.Texture != null) { if (!mLeftPixel.IsWindowOrChildrenReceivingInput) { int leftPixel = (int)(.5f + SelectedObject.Texture.Width * SelectedObject.LeftTextureCoordinate); mLeftPixel.CurrentValue = leftPixel; } if (!mTopPixel.IsWindowOrChildrenReceivingInput) { int topPixel = (int)(.5f + SelectedObject.Texture.Height * SelectedObject.TopTextureCoordinate); mTopPixel.CurrentValue = topPixel; } if (!mPixelWidth.IsWindowOrChildrenReceivingInput) { int width = (int)(.5f + SelectedObject.Texture.Width * Math.Abs(SelectedObject.RightTextureCoordinate - SelectedObject.LeftTextureCoordinate)); mPixelWidth.CurrentValue = width; } if (!mPixelHeight.IsWindowOrChildrenReceivingInput) { int height = (int)(.5f + SelectedObject.Texture.Height * Math.Abs(SelectedObject.BottomTextureCoordinate - SelectedObject.TopTextureCoordinate)); mPixelHeight.CurrentValue = height; } } } #endregion #region Methods #region Constructor public SpritePropertyGrid(Cursor cursor) : base(cursor) { MakeVisibleOnSpriteSet = true; InitialExcludeIncludeMembers(); #region Category Cleanup RemoveCategory("Uncategorized"); SelectCategory("Basic"); #endregion #region UI Replacement #region Replace the CurrentChainName UI element mCurrentChainNameComboBox = new ComboBox(this.mCursor); mCurrentChainNameComboBox.ScaleX = 5; ReplaceMemberUIElement("CurrentChainName", mCurrentChainNameComboBox); #endregion mAnimationChainFileTextBox = new FileTextBox(this.mCursor); mAnimationChainFileTextBox.ScaleX = 8; mAnimationChainFileTextBox.TextBox.CursorOver += ShowAnimationPopup; this.AddWindow(mAnimationChainFileTextBox, "Animation"); mAnimationChainFileTextBox.SetFileType("achx"); this.SetLabelForWindow(mAnimationChainFileTextBox, "Animation File"); mAnimationChainFileTextBox.FileSelect += SetAnimationChainOnSprite; #endregion this.MinimumScaleY = 10; SetMemberDisplayName("CursorSelectable", "Active"); } private void InitialExcludeIncludeMembers() { ExcludeAllMembers(); #region Basic Members IncludeMember("X", "Basic"); SetMemberChangeEvent("X", ShowCantEditAbsoluteValuesMessage); IncludeMember("Y", "Basic"); SetMemberChangeEvent("Y", ShowCantEditAbsoluteValuesMessage); IncludeMember("Z", "Basic"); SetMemberChangeEvent("Z", ShowCantEditAbsoluteValuesMessage); IncludeMember("Visible", "Basic"); IncludeMember("CursorSelectable", "Basic"); IncludeMember("Name", "Basic"); mOrderingMode = new ComboBox(mCursor); mOrderingMode.AddItem("Distance from Camera", OrderingMode.DistanceFromCamera); mOrderingMode.AddItem("ZBuffered", OrderingMode.ZBuffered); mOrderingMode.ScaleX = 6.5f; AddWindow(mOrderingMode, "Basic"); SetLabelForWindow(mOrderingMode, "OrderingMode"); mOrderingMode.ItemClick += SetOrderingMode; #endregion #region Rotation Members IncludeMember("RotationX", "Rotation"); SetMemberChangeEvent("RotationX", ShowCantEditAbsoluteValuesMessage); IncludeMember("RotationY", "Rotation"); SetMemberChangeEvent("RotationY", ShowCantEditAbsoluteValuesMessage); IncludeMember("RotationZ", "Rotation"); SetMemberChangeEvent("RotationZ", ShowCantEditAbsoluteValuesMessage); #endregion #region Scale Members IncludeMember("ScaleX", "Scale"); IncludeMember("ScaleY", "Scale"); IncludeMember("PixelSize", "Scale"); ((UpDown)GetUIElementForMember("PixelSize")).Sensitivity = .01f; // Vic says: Any value for PixelSize above 0 will result in the // Sprite having a valid PixelSize. Values below 0 are ignored. // This isn't the best solution, but there's really no reason for // a user to ever set a value below -1, so we'll put a cap on that. // Eventualy we may want to make this more robust by "hopping" to -1 // if the user drags the value down below 0, and "hopping" to 0 if the // user drags the value up from -1. ((UpDown)GetUIElementForMember("PixelSize")).MinValue = -1; mSetPixelPerfectScaleButton = new Button(mCursor); mSetPixelPerfectScaleButton.Text = "Set Pixel\nPerfect Scale"; mSetPixelPerfectScaleButton.ScaleX = 6; mSetPixelPerfectScaleButton.ScaleY = 2f; AddWindow(mSetPixelPerfectScaleButton, "Scale"); mSetPixelPerfectScaleButton.Click += SetPixelPerfectScaleClick; #endregion #region Animation IncludeMember("AnimationChains", "Animation"); IncludeMember("CurrentChainName", "Animation"); IncludeMember("Animate", "Animation"); IncludeMember("AnimationSpeed", "Animation"); #endregion #region Texture Members IncludeMember("Texture", "Texture"); SetMemberChangeEvent("Texture", OnTextureChange); IncludeMember("TextureAddressMode", "Texture"); //mTopTextureCoordinateUpDown = IncludeMember("TopTextureCoordinate", "Texture") as UpDown; //mTopTextureCoordinateUpDown.Sensitivity = .01f; //mBottomTextureCoordinateUpDown = IncludeMember("BottomTextureCoordinate", "Texture") as UpDown; //mBottomTextureCoordinateUpDown.Sensitivity = .01f; //mLeftTextureCoordinateUpDown = IncludeMember("LeftTextureCoordinate", "Texture") as UpDown; //mLeftTextureCoordinateUpDown.Sensitivity = .01f; //mRightTextureCoordinateUpDown = IncludeMember("RightTextureCoordinate", "Texture") as UpDown; //mRightTextureCoordinateUpDown.Sensitivity = .01f; TextureCoordinatePropertyGridHelper.CreatePixelCoordinateUi( this, "TopCoordinate", "BottomCoordinate", "LeftCoordinate", "RightCoordinate", "Texture", out mTopPixel, out mLeftPixel, out mPixelHeight, out mPixelWidth); mLeftPixel.ValueChanged += ChangeLeftPixel; mTopPixel.ValueChanged += ChangeTopPixel; mPixelWidth.ValueChanged += ChangePixelWidth; mPixelHeight.ValueChanged += ChangePixelHeight; this.AfterUpdateDisplayedProperties += UpdateCustomUI; IncludeMember("FlipHorizontal", "Texture"); IncludeMember("FlipVertical", "Texture"); mPixelPerfectTextureCoordinates = new ToggleButton(this.mCursor); mPixelPerfectTextureCoordinates.Text = "Pixel Perfect\nCoordinates"; mPixelPerfectTextureCoordinates.ScaleX = 5.5f; mPixelPerfectTextureCoordinates.ScaleY = 2.1f; AddWindow(mPixelPerfectTextureCoordinates, "Texture"); #endregion #region Relative IncludeMember("RelativeX", "Relative"); IncludeMember("RelativeY", "Relative"); IncludeMember("RelativeZ", "Relative"); IncludeMember("RelativeRotationX", "Relative"); IncludeMember("RelativeRotationY", "Relative"); IncludeMember("RelativeRotationZ", "Relative"); #endregion #region Color IncludeMember("ColorOperation", "Color"); #if !FRB_XNA ComboBox colorOperationComboBox = GetUIElementForMember("ColorOperation") as ComboBox; for (int i = colorOperationComboBox.Count - 1; i > -1; i--) { Microsoft.DirectX.Direct3D.TextureOperation textureOperation = ((Microsoft.DirectX.Direct3D.TextureOperation)colorOperationComboBox[i].ReferenceObject); if (!FlatRedBall.Graphics.GraphicalEnumerations.IsTextureOperationSupportedInFrbXna( textureOperation)) { colorOperationComboBox.RemoveAt(i); } } #endif IncludeMember("Red", "Color"); IncludeMember("Green", "Color"); IncludeMember("Blue", "Color"); IncludeMember("BlendOperation", "Blend"); IncludeMember("Alpha", "Blend"); #endregion } #endregion #region Public Methods public void EnableSplittingSprite(SpriteList listToAddNewSpritesTo) { mSpriteList = listToAddNewSpritesTo; Button splitSpriteButton = new Button(mCursor); splitSpriteButton.Text = "Split Sprite"; splitSpriteButton.ScaleX = 10; this.AddWindow(splitSpriteButton, "Actions"); splitSpriteButton.Click += SplitSpriteClick; } public override void UpdateDisplayedProperties() { base.UpdateDisplayedProperties(); UpdateAnimationChainUi(SelectedObject, mCurrentChainNameComboBox, mAnimationChainFileTextBox); #region Update the RoundTo property for the texture coordinate UpDowns if (SelectedObject != null && SelectedObject.Texture != null && mTopTextureCoordinateUpDown != null) { float roundToX = 0; float roundToY = 0; if (mPixelPerfectTextureCoordinates.IsPressed) { roundToX = 1.0f / SelectedObject.Texture.Width; roundToY = 1.0f / SelectedObject.Texture.Height; } mTopTextureCoordinateUpDown.RoundTo = roundToY; mBottomTextureCoordinateUpDown.RoundTo = roundToY; mLeftTextureCoordinateUpDown.RoundTo = roundToX; mRightTextureCoordinateUpDown.RoundTo = roundToX; } #endregion } public static void UpdateAnimationChainUi(IAnimationChainAnimatable selectedObject, ComboBox currentChainNameComboBox, FileTextBox animationChainFileTextBox) { #region Update mCurrentChainComboBox items if (selectedObject != null && selectedObject.AnimationChains.Count != 0) { for (int i = 0; i < selectedObject.AnimationChains.Count; i++) { if (currentChainNameComboBox.Count <= i || currentChainNameComboBox[i].Text != selectedObject.AnimationChains[i].Name) { currentChainNameComboBox.InsertItem(i, selectedObject.AnimationChains[i].Name, selectedObject.AnimationChains[i]); } } while (currentChainNameComboBox.Count > selectedObject.AnimationChains.Count) { currentChainNameComboBox.RemoveAt(currentChainNameComboBox.Count - 1); } } #endregion #region Update the Animation File UI if (selectedObject != null && selectedObject.AnimationChains != null && selectedObject.AnimationChains.Name != null) { if (!animationChainFileTextBox.IsWindowOrChildrenReceivingInput) { animationChainFileTextBox.Text = selectedObject.AnimationChains.Name; } } #endregion } #endregion #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // Copyright (c) 2004 Mainsoft Co. // // 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 Xunit; using System.ComponentModel; using System.Collections; using System.Runtime.Serialization; using System.Xml; using System.Xml.Schema; using System.IO; using System.Globalization; namespace System.Data.Tests { public class DataSetTypedDataSetTest { private string _eventStatus = string.Empty; [Fact] public void TypedDataSet() { int i = 0; //check dataset constructor myTypedDataSet ds = null; DataSet unTypedDs = new DataSet(); ds = new myTypedDataSet(); Assert.False(ds == null); Assert.Equal(typeof(myTypedDataSet), ds.GetType()); // fill dataset ds.ReadXml(new StringReader( @"<?xml version=""1.0"" standalone=""yes""?> <myTypedDataSet xmlns=""http://www.tempuri.org/myTypedDataSet.xsd""> <Order_x0020_Details> <OrderID>10250</OrderID> <ProductID>41</ProductID> <UnitPrice>7.7000</UnitPrice> <Quantity>10</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10250</OrderID> <ProductID>51</ProductID> <UnitPrice>42.4000</UnitPrice> <Quantity>35</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10250</OrderID> <ProductID>65</ProductID> <UnitPrice>16.8000</UnitPrice> <Quantity>15</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10251</OrderID> <ProductID>22</ProductID> <UnitPrice>16.8000</UnitPrice> <Quantity>6</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10251</OrderID> <ProductID>57</ProductID> <UnitPrice>15.6000</UnitPrice> <Quantity>15</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10251</OrderID> <ProductID>65</ProductID> <UnitPrice>16.8000</UnitPrice> <Quantity>20</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10252</OrderID> <ProductID>20</ProductID> <UnitPrice>64.8000</UnitPrice> <Quantity>40</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10252</OrderID> <ProductID>33</ProductID> <UnitPrice>2.0000</UnitPrice> <Quantity>25</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10252</OrderID> <ProductID>60</ProductID> <UnitPrice>27.2000</UnitPrice> <Quantity>40</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10253</OrderID> <ProductID>31</ProductID> <UnitPrice>10.0000</UnitPrice> <Quantity>20</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10253</OrderID> <ProductID>39</ProductID> <UnitPrice>14.4000</UnitPrice> <Quantity>42</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10253</OrderID> <ProductID>49</ProductID> <UnitPrice>16.0000</UnitPrice> <Quantity>40</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10254</OrderID> <ProductID>24</ProductID> <UnitPrice>3.6000</UnitPrice> <Quantity>15</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10254</OrderID> <ProductID>55</ProductID> <UnitPrice>19.2000</UnitPrice> <Quantity>21</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10254</OrderID> <ProductID>74</ProductID> <UnitPrice>8.0000</UnitPrice> <Quantity>21</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10255</OrderID> <ProductID>2</ProductID> <UnitPrice>15.2000</UnitPrice> <Quantity>20</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10255</OrderID> <ProductID>16</ProductID> <UnitPrice>13.9000</UnitPrice> <Quantity>35</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10255</OrderID> <ProductID>36</ProductID> <UnitPrice>15.2000</UnitPrice> <Quantity>25</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10255</OrderID> <ProductID>59</ProductID> <UnitPrice>44.0000</UnitPrice> <Quantity>30</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10256</OrderID> <ProductID>53</ProductID> <UnitPrice>26.2000</UnitPrice> <Quantity>15</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10256</OrderID> <ProductID>77</ProductID> <UnitPrice>10.4000</UnitPrice> <Quantity>12</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10257</OrderID> <ProductID>27</ProductID> <UnitPrice>35.1000</UnitPrice> <Quantity>25</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10257</OrderID> <ProductID>39</ProductID> <UnitPrice>14.4000</UnitPrice> <Quantity>6</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10257</OrderID> <ProductID>77</ProductID> <UnitPrice>10.4000</UnitPrice> <Quantity>15</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10258</OrderID> <ProductID>2</ProductID> <UnitPrice>15.2000</UnitPrice> <Quantity>50</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10258</OrderID> <ProductID>5</ProductID> <UnitPrice>17.0000</UnitPrice> <Quantity>65</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10258</OrderID> <ProductID>32</ProductID> <UnitPrice>25.6000</UnitPrice> <Quantity>6</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10259</OrderID> <ProductID>21</ProductID> <UnitPrice>8.0000</UnitPrice> <Quantity>10</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10259</OrderID> <ProductID>37</ProductID> <UnitPrice>20.8000</UnitPrice> <Quantity>1</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10260</OrderID> <ProductID>41</ProductID> <UnitPrice>7.7000</UnitPrice> <Quantity>16</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10260</OrderID> <ProductID>57</ProductID> <UnitPrice>15.6000</UnitPrice> <Quantity>50</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10260</OrderID> <ProductID>62</ProductID> <UnitPrice>39.4000</UnitPrice> <Quantity>15</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10260</OrderID> <ProductID>70</ProductID> <UnitPrice>12.0000</UnitPrice> <Quantity>21</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10261</OrderID> <ProductID>21</ProductID> <UnitPrice>8.0000</UnitPrice> <Quantity>20</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10261</OrderID> <ProductID>35</ProductID> <UnitPrice>14.4000</UnitPrice> <Quantity>20</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10262</OrderID> <ProductID>5</ProductID> <UnitPrice>17.0000</UnitPrice> <Quantity>12</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10262</OrderID> <ProductID>7</ProductID> <UnitPrice>24.0000</UnitPrice> <Quantity>15</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10262</OrderID> <ProductID>56</ProductID> <UnitPrice>30.4000</UnitPrice> <Quantity>2</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10263</OrderID> <ProductID>16</ProductID> <UnitPrice>13.9000</UnitPrice> <Quantity>60</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10263</OrderID> <ProductID>24</ProductID> <UnitPrice>3.6000</UnitPrice> <Quantity>28</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10263</OrderID> <ProductID>30</ProductID> <UnitPrice>20.7000</UnitPrice> <Quantity>60</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10263</OrderID> <ProductID>74</ProductID> <UnitPrice>8.0000</UnitPrice> <Quantity>36</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10264</OrderID> <ProductID>2</ProductID> <UnitPrice>15.2000</UnitPrice> <Quantity>35</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10264</OrderID> <ProductID>41</ProductID> <UnitPrice>7.7000</UnitPrice> <Quantity>25</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10265</OrderID> <ProductID>17</ProductID> <UnitPrice>31.2000</UnitPrice> <Quantity>30</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10265</OrderID> <ProductID>70</ProductID> <UnitPrice>12.0000</UnitPrice> <Quantity>20</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10266</OrderID> <ProductID>12</ProductID> <UnitPrice>30.4000</UnitPrice> <Quantity>12</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10267</OrderID> <ProductID>40</ProductID> <UnitPrice>14.7000</UnitPrice> <Quantity>50</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10267</OrderID> <ProductID>59</ProductID> <UnitPrice>44.0000</UnitPrice> <Quantity>70</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10267</OrderID> <ProductID>76</ProductID> <UnitPrice>14.4000</UnitPrice> <Quantity>15</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10268</OrderID> <ProductID>29</ProductID> <UnitPrice>99.0000</UnitPrice> <Quantity>10</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10268</OrderID> <ProductID>72</ProductID> <UnitPrice>27.8000</UnitPrice> <Quantity>4</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10269</OrderID> <ProductID>33</ProductID> <UnitPrice>2.0000</UnitPrice> <Quantity>60</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10269</OrderID> <ProductID>72</ProductID> <UnitPrice>27.8000</UnitPrice> <Quantity>20</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10270</OrderID> <ProductID>36</ProductID> <UnitPrice>15.2000</UnitPrice> <Quantity>30</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Order_x0020_Details> <OrderID>10270</OrderID> <ProductID>43</ProductID> <UnitPrice>36.8000</UnitPrice> <Quantity>25</Quantity> <Discount>5.0</Discount> </Order_x0020_Details> <Orders> <OrderID>10250</OrderID> <CustomerID>HANAR</CustomerID> <EmployeeID>4</EmployeeID> <OrderDate>1996-07-08T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-05T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-12T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10251</OrderID> <CustomerID>VICTE</CustomerID> <EmployeeID>3</EmployeeID> <OrderDate>1996-07-08T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-05T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-15T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10252</OrderID> <CustomerID>SUPRD</CustomerID> <EmployeeID>4</EmployeeID> <OrderDate>1996-07-09T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-06T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-11T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10253</OrderID> <CustomerID>HANAR</CustomerID> <EmployeeID>3</EmployeeID> <OrderDate>1996-07-10T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-07-24T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-16T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10254</OrderID> <CustomerID>CHOPS</CustomerID> <EmployeeID>5</EmployeeID> <OrderDate>1996-07-11T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-08T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-23T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10255</OrderID> <CustomerID>RICSU</CustomerID> <EmployeeID>9</EmployeeID> <OrderDate>1996-07-12T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-09T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-15T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10256</OrderID> <CustomerID>WELLI</CustomerID> <EmployeeID>3</EmployeeID> <OrderDate>1996-07-15T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-12T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-17T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10257</OrderID> <CustomerID>HILAA</CustomerID> <EmployeeID>4</EmployeeID> <OrderDate>1996-07-16T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-13T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-22T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10258</OrderID> <CustomerID>ERNSH</CustomerID> <EmployeeID>1</EmployeeID> <OrderDate>1996-07-17T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-14T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-23T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10259</OrderID> <CustomerID>CENTC</CustomerID> <EmployeeID>4</EmployeeID> <OrderDate>1996-07-18T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-15T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-25T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10260</OrderID> <CustomerID>OTTIK</CustomerID> <EmployeeID>4</EmployeeID> <OrderDate>1996-07-19T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-16T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-29T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10261</OrderID> <CustomerID>QUEDE</CustomerID> <EmployeeID>4</EmployeeID> <OrderDate>1996-07-19T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-16T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-30T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10262</OrderID> <CustomerID>RATTC</CustomerID> <EmployeeID>8</EmployeeID> <OrderDate>1996-07-22T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-19T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-25T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10263</OrderID> <CustomerID>ERNSH</CustomerID> <EmployeeID>9</EmployeeID> <OrderDate>1996-07-23T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-20T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-31T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10264</OrderID> <CustomerID>FOLKO</CustomerID> <EmployeeID>6</EmployeeID> <OrderDate>1996-07-24T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-21T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-08-23T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10265</OrderID> <CustomerID>BLONP</CustomerID> <EmployeeID>2</EmployeeID> <OrderDate>1996-07-25T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-22T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-08-12T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10266</OrderID> <CustomerID>WARTH</CustomerID> <EmployeeID>3</EmployeeID> <OrderDate>1996-07-26T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-09-06T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-07-31T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10267</OrderID> <CustomerID>FRANK</CustomerID> <EmployeeID>4</EmployeeID> <OrderDate>1996-07-29T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-26T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-08-06T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10268</OrderID> <CustomerID>GROSR</CustomerID> <EmployeeID>8</EmployeeID> <OrderDate>1996-07-30T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-27T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-08-02T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10269</OrderID> <CustomerID>WHITC</CustomerID> <EmployeeID>5</EmployeeID> <OrderDate>1996-07-31T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-14T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-08-09T00:00:00.0000000+03:00</ShippedDate> </Orders> <Orders> <OrderID>10270</OrderID> <CustomerID>WARTH</CustomerID> <EmployeeID>1</EmployeeID> <OrderDate>1996-08-01T00:00:00.0000000+03:00</OrderDate> <RequiredDate>1996-08-29T00:00:00.0000000+03:00</RequiredDate> <ShippedDate>1996-08-02T00:00:00.0000000+03:00</ShippedDate> </Orders> </myTypedDataSet>")); // check DataSet named property "Orders" myTypedDataSet.OrdersDataTable tblOrders = null; tblOrders = ds.Orders; Assert.Equal(ds.Tables["Orders"], tblOrders); //check DataSet named property Orders - by index"); tblOrders = ds.Orders; Assert.Equal(ds.Tables[1], tblOrders); //add new row AddTableNameRow, check row count"); i = tblOrders.Rows.Count; tblOrders.AddOrdersRow("SAVEA", 1, new DateTime(1998, 05, 01, 00, 00, 00, 000) , new DateTime(1998, 05, 29, 00, 00, 00, 000) , new DateTime(1998, 05, 04, 00, 00, 00, 000), 1, 30.0900m , "Save-a-lot Markets", "187 Suffolk Ln.", "Boise", "ID", "83720", "USA"); Assert.Equal(i + 1, tblOrders.Rows.Count); //check the new row AutoIncrement field - AddTableNameRow i = (int)tblOrders.Rows[tblOrders.Rows.Count - 2][0]; Assert.Equal(i + 1, (int)tblOrders.Rows[tblOrders.Rows.Count - 1][0]); //Create New Row using NewTableNameRow, check row != null myTypedDataSet.OrdersRow drOrders = null; drOrders = tblOrders.NewOrdersRow(); Assert.False(drOrders == null); //Create New Row using NewTableNameRow, check row state Assert.Equal(DataRowState.Detached, drOrders.RowState); //add new row NewTableNameRow, check row count //drOrders.OrderID = DBNull.Value; drOrders.CustomerID = "GREAL"; drOrders.EmployeeID = 4; drOrders.OrderDate = new DateTime(1998, 04, 30, 00, 00, 00, 000); drOrders.RequiredDate = new DateTime(1998, 06, 11, 00, 00, 00, 000); drOrders["ShippedDate"] = DBNull.Value; drOrders.ShipVia = 3; drOrders.Freight = 14.0100m; drOrders.ShipName = "Great Lakes"; drOrders.ShipAddress = "Food Market"; drOrders.ShipCity = "Baker Blvd."; drOrders.ShipRegion = "Eugene"; drOrders.ShipPostalCode = "OR 97403"; drOrders.ShipCountry = "USA"; i = tblOrders.Rows.Count; tblOrders.AddOrdersRow(drOrders); Assert.Equal(i + 1, tblOrders.Rows.Count); //check StrongTypingException Assert.Throws<StrongTypingException>(() => { DateTime d = drOrders.ShippedDate; //drOrders.ShippedDate = null, will raise exception }); //check the new row AutoIncrement field - NewTableNameRow i = (int)tblOrders.Rows[tblOrders.Rows.Count - 2][0]; Assert.Equal(i + 1, (int)tblOrders.Rows[tblOrders.Rows.Count - 1][0]); // convenience IsNull functions // only if it can be null Assert.False(drOrders.IsShipAddressNull()); drOrders.SetShipAddressNull(); Assert.True(drOrders.IsShipAddressNull()); // Table exposes a public property Count == table.Rows.Count Assert.Equal(tblOrders.Count, tblOrders.Rows.Count); // find function myTypedDataSet.OrdersRow dr = tblOrders[0]; Assert.Equal(tblOrders.FindByOrderID(dr.OrderID), dr); //Remove row and check row count i = tblOrders.Count; myTypedDataSet.OrdersRow drr = tblOrders[0]; tblOrders.RemoveOrdersRow(drr); Assert.Equal(i - 1, tblOrders.Count); //first column is readonly Assert.True(tblOrders.OrderIDColumn.ReadOnly); //read only exception Assert.Throws<ReadOnlyException>(() => { tblOrders[0].OrderID = 99; }); tblOrders.AcceptChanges(); //Check table events // add event handlers ds.Orders.OrdersRowChanging += new myTypedDataSet.OrdersRowChangeEventHandler(T_Changing); ds.Orders.OrdersRowChanged += new myTypedDataSet.OrdersRowChangeEventHandler(T_Changed); ds.Orders.OrdersRowDeleting += new myTypedDataSet.OrdersRowChangeEventHandler(T_Deleting); ds.Orders.OrdersRowDeleted += new myTypedDataSet.OrdersRowChangeEventHandler(T_Deleted); //RowChange event order tblOrders[0].ShipCity = "Tel Aviv"; Assert.Equal("AB", _eventStatus); _eventStatus = string.Empty; //RowDelet event order tblOrders[0].Delete(); Assert.Equal("AB", _eventStatus); //expose DataColumn as property Assert.Equal(ds.Orders.OrderIDColumn, ds.Tables["Orders"].Columns["OrderID"]); //Accept changes for all deleted and changedd rows. ds.AcceptChanges(); //check relations //ChildTableRow has property ParentTableRow myTypedDataSet.OrdersRow dr1 = ds.Order_Details[0].OrdersRow; DataRow dr2 = ds.Order_Details[0].GetParentRow(ds.Relations[0]); Assert.Equal(dr1, dr2); //ParentTableRow has property ChildTableRow myTypedDataSet.Order_DetailsRow[] drArr1 = ds.Orders[0].GetOrder_DetailsRows(); DataRow[] drArr2 = ds.Orders[0].GetChildRows(ds.Relations[0]); Assert.Equal(drArr1, drArr2); //now test serialization of a typed dataset generated by microsoft's xsd.exe DataSet1 ds1 = new DataSet1(); ds1.DataTable1.AddDataTable1Row("test"); ds1.DataTable1.AddDataTable1Row("test2"); global::System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new global::System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); MemoryStream stream = new MemoryStream(); formatter.Serialize(stream, ds1); stream.Seek(0, SeekOrigin.Begin); DataSet1 ds1load = (DataSet1)formatter.Deserialize(stream); Assert.True(ds1load.Tables.Contains("DataTable1")); Assert.Equal("DataTable1DataTable", ds1load.Tables["DataTable1"].GetType().Name); Assert.Equal(2, ds1load.DataTable1.Rows.Count); Assert.Equal("DataTable1Row", ds1load.DataTable1[0].GetType().Name); if (ds1load.DataTable1[0].Column1 == "test") { Assert.Equal("test2", ds1load.DataTable1[1].Column1); } else if (ds1load.DataTable1[0].Column1 == "test2") { Assert.Equal("test", ds1load.DataTable1[1].Column1); } else { Assert.False(true); } //now test when the mode is exclude schema ds1.SchemaSerializationMode = global::System.Data.SchemaSerializationMode.ExcludeSchema; stream = new MemoryStream(); formatter.Serialize(stream, ds1); stream.Seek(0, SeekOrigin.Begin); ds1load = (DataSet1)formatter.Deserialize(stream); Assert.True(ds1load.Tables.Contains("DataTable1")); Assert.Equal("DataTable1DataTable", ds1load.Tables["DataTable1"].GetType().Name); Assert.Equal(2, ds1load.DataTable1.Rows.Count); Assert.Equal("DataTable1Row", ds1load.DataTable1[0].GetType().Name); if (ds1load.DataTable1[0].Column1 == "test") { Assert.Equal("test2", ds1load.DataTable1[1].Column1); } else if (ds1load.DataTable1[0].Column1 == "test2") { Assert.Equal("test", ds1load.DataTable1[1].Column1); } else { Assert.False(true); } } protected void T_Changing(object sender, myTypedDataSet.OrdersRowChangeEvent e) { _eventStatus += "A"; } protected void T_Changed(object sender, myTypedDataSet.OrdersRowChangeEvent e) { _eventStatus += "B"; } protected void T_Deleting(object sender, myTypedDataSet.OrdersRowChangeEvent e) { _eventStatus += "A"; } protected void T_Deleted(object sender, myTypedDataSet.OrdersRowChangeEvent e) { _eventStatus += "B"; } [Serializable] [DesignerCategoryAttribute("code")] [ToolboxItem(true)] public class myTypedDataSet : DataSet { private Order_DetailsDataTable _tableOrder_Details; private OrdersDataTable _tableOrders; private DataRelation _relationOrdersOrder_x0020_Details; public myTypedDataSet() { InitClass(); CollectionChangeEventHandler schemaChangedHandler = new CollectionChangeEventHandler(SchemaChanged); Tables.CollectionChanged += schemaChangedHandler; Relations.CollectionChanged += schemaChangedHandler; } protected myTypedDataSet(SerializationInfo info, StreamingContext context) { string strSchema = ((string)(info.GetValue("XmlSchema", typeof(string)))); if ((strSchema != null)) { var ds = new DataSet(); ds.ReadXmlSchema(new XmlTextReader(new StringReader(strSchema))); if ((ds.Tables["Order Details"] != null)) { Tables.Add(new Order_DetailsDataTable(ds.Tables["Order Details"])); } if ((ds.Tables["Orders"] != null)) { Tables.Add(new OrdersDataTable(ds.Tables["Orders"])); } DataSetName = ds.DataSetName; Prefix = ds.Prefix; Namespace = ds.Namespace; Locale = ds.Locale; CaseSensitive = ds.CaseSensitive; EnforceConstraints = ds.EnforceConstraints; Merge(ds, false, MissingSchemaAction.Add); InitVars(); } else { InitClass(); } GetSerializationData(info, context); CollectionChangeEventHandler schemaChangedHandler = new CollectionChangeEventHandler(SchemaChanged); Tables.CollectionChanged += schemaChangedHandler; Relations.CollectionChanged += schemaChangedHandler; } [Browsable(false)] [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Content)] public Order_DetailsDataTable Order_Details { get { return _tableOrder_Details; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Content)] public OrdersDataTable Orders { get { return _tableOrders; } } public override DataSet Clone() { myTypedDataSet cln = ((myTypedDataSet)(base.Clone())); cln.InitVars(); return cln; } protected override bool ShouldSerializeTables() { return false; } protected override bool ShouldSerializeRelations() { return false; } protected override void ReadXmlSerializable(XmlReader reader) { Reset(); var ds = new DataSet(); ds.ReadXml(reader); if ((ds.Tables["Order Details"] != null)) { Tables.Add(new Order_DetailsDataTable(ds.Tables["Order Details"])); } if ((ds.Tables["Orders"] != null)) { Tables.Add(new OrdersDataTable(ds.Tables["Orders"])); } DataSetName = ds.DataSetName; Prefix = ds.Prefix; Namespace = ds.Namespace; Locale = ds.Locale; CaseSensitive = ds.CaseSensitive; EnforceConstraints = ds.EnforceConstraints; Merge(ds, false, MissingSchemaAction.Add); InitVars(); } protected override XmlSchema GetSchemaSerializable() { MemoryStream stream = new MemoryStream(); WriteXmlSchema(new XmlTextWriter(stream, null)); stream.Position = 0; return XmlSchema.Read(new XmlTextReader(stream), null); } internal void InitVars() { _tableOrder_Details = ((Order_DetailsDataTable)(Tables["Order Details"])); if ((_tableOrder_Details != null)) { _tableOrder_Details.InitVars(); } _tableOrders = ((OrdersDataTable)(Tables["Orders"])); if ((_tableOrders != null)) { _tableOrders.InitVars(); } _relationOrdersOrder_x0020_Details = Relations["OrdersOrder_x0020_Details"]; } private void InitClass() { DataSetName = "myTypedDataSet"; Prefix = ""; Namespace = "http://www.tempuri.org/myTypedDataSet.xsd"; Locale = new CultureInfo("en-US"); CaseSensitive = false; EnforceConstraints = true; _tableOrder_Details = new Order_DetailsDataTable(); Tables.Add(_tableOrder_Details); _tableOrders = new OrdersDataTable(); Tables.Add(_tableOrders); ForeignKeyConstraint fkc; fkc = new ForeignKeyConstraint("OrdersOrder_x0020_Details", new DataColumn[] { _tableOrders.OrderIDColumn}, new DataColumn[] { _tableOrder_Details.OrderIDColumn}); _tableOrder_Details.Constraints.Add(fkc); fkc.AcceptRejectRule = AcceptRejectRule.None; fkc.DeleteRule = Rule.Cascade; fkc.UpdateRule = Rule.Cascade; _relationOrdersOrder_x0020_Details = new DataRelation("OrdersOrder_x0020_Details", new DataColumn[] { _tableOrders.OrderIDColumn}, new DataColumn[] { _tableOrder_Details.OrderIDColumn}, false); Relations.Add(_relationOrdersOrder_x0020_Details); } private bool ShouldSerializeOrder_Details() { return false; } private bool ShouldSerializeOrders() { return false; } private void SchemaChanged(object sender, CollectionChangeEventArgs e) { if ((e.Action == CollectionChangeAction.Remove)) { InitVars(); } } public delegate void Order_DetailsRowChangeEventHandler(object sender, Order_DetailsRowChangeEvent e); public delegate void OrdersRowChangeEventHandler(object sender, OrdersRowChangeEvent e); public class Order_DetailsDataTable : DataTable, IEnumerable { private DataColumn _columnOrderID; private DataColumn _columnProductID; private DataColumn _columnUnitPrice; private DataColumn _columnQuantity; private DataColumn _columnDiscount; internal Order_DetailsDataTable() : base("Order Details") { InitClass(); } internal Order_DetailsDataTable(DataTable table) : base(table.TableName) { if ((table.CaseSensitive != table.DataSet.CaseSensitive)) { CaseSensitive = table.CaseSensitive; } if ((table.Locale.ToString() != table.DataSet.Locale.ToString())) { Locale = table.Locale; } if ((table.Namespace != table.DataSet.Namespace)) { Namespace = table.Namespace; } Prefix = table.Prefix; MinimumCapacity = table.MinimumCapacity; DisplayExpression = table.DisplayExpression; } [Browsable(false)] public int Count { get { return Rows.Count; } } internal DataColumn OrderIDColumn { get { return _columnOrderID; } } internal DataColumn ProductIDColumn { get { return _columnProductID; } } internal DataColumn UnitPriceColumn { get { return _columnUnitPrice; } } internal DataColumn QuantityColumn { get { return _columnQuantity; } } internal DataColumn DiscountColumn { get { return _columnDiscount; } } public Order_DetailsRow this[int index] { get { return ((Order_DetailsRow)(Rows[index])); } } public event Order_DetailsRowChangeEventHandler Order_DetailsRowChanged; public event Order_DetailsRowChangeEventHandler Order_DetailsRowChanging; public event Order_DetailsRowChangeEventHandler Order_DetailsRowDeleted; public event Order_DetailsRowChangeEventHandler Order_DetailsRowDeleting; public void AddOrder_DetailsRow(Order_DetailsRow row) { Rows.Add(row); } public Order_DetailsRow AddOrder_DetailsRow(OrdersRow parentOrdersRowByOrdersOrder_x0020_Details, int ProductID, decimal UnitPrice, short Quantity, string Discount) { Order_DetailsRow rowOrder_DetailsRow = ((Order_DetailsRow)(NewRow())); rowOrder_DetailsRow.ItemArray = new object[] { parentOrdersRowByOrdersOrder_x0020_Details[0], ProductID, UnitPrice, Quantity, Discount}; Rows.Add(rowOrder_DetailsRow); return rowOrder_DetailsRow; } public Order_DetailsRow FindByOrderIDProductID(int OrderID, int ProductID) { return ((Order_DetailsRow)(Rows.Find(new object[] { OrderID, ProductID}))); } public IEnumerator GetEnumerator() { return Rows.GetEnumerator(); } public override DataTable Clone() { Order_DetailsDataTable cln = ((Order_DetailsDataTable)(base.Clone())); cln.InitVars(); return cln; } protected override DataTable CreateInstance() { return new Order_DetailsDataTable(); } internal void InitVars() { _columnOrderID = Columns["OrderID"]; _columnProductID = Columns["ProductID"]; _columnUnitPrice = Columns["UnitPrice"]; _columnQuantity = Columns["Quantity"]; _columnDiscount = Columns["Discount"]; } private void InitClass() { _columnOrderID = new DataColumn("OrderID", typeof(int), null, MappingType.Element); Columns.Add(_columnOrderID); _columnProductID = new DataColumn("ProductID", typeof(int), null, MappingType.Element); Columns.Add(_columnProductID); _columnUnitPrice = new DataColumn("UnitPrice", typeof(decimal), null, MappingType.Element); Columns.Add(_columnUnitPrice); _columnQuantity = new DataColumn("Quantity", typeof(short), null, MappingType.Element); Columns.Add(_columnQuantity); _columnDiscount = new DataColumn("Discount", typeof(string), null, MappingType.Element); Columns.Add(_columnDiscount); Constraints.Add(new UniqueConstraint("Constraint1", new DataColumn[] { _columnOrderID, _columnProductID}, true)); _columnOrderID.AllowDBNull = false; _columnProductID.AllowDBNull = false; _columnUnitPrice.AllowDBNull = false; _columnQuantity.AllowDBNull = false; _columnDiscount.ReadOnly = true; } public Order_DetailsRow NewOrder_DetailsRow() { return ((Order_DetailsRow)(NewRow())); } protected override DataRow NewRowFromBuilder(DataRowBuilder builder) { return new Order_DetailsRow(builder); } protected override Type GetRowType() { return typeof(Order_DetailsRow); } protected override void OnRowChanged(DataRowChangeEventArgs e) { base.OnRowChanged(e); if ((Order_DetailsRowChanged != null)) { Order_DetailsRowChanged(this, new Order_DetailsRowChangeEvent(((Order_DetailsRow)(e.Row)), e.Action)); } } protected override void OnRowChanging(DataRowChangeEventArgs e) { base.OnRowChanging(e); if ((Order_DetailsRowChanging != null)) { Order_DetailsRowChanging(this, new Order_DetailsRowChangeEvent(((Order_DetailsRow)(e.Row)), e.Action)); } } protected override void OnRowDeleted(DataRowChangeEventArgs e) { base.OnRowDeleted(e); if ((Order_DetailsRowDeleted != null)) { Order_DetailsRowDeleted(this, new Order_DetailsRowChangeEvent(((Order_DetailsRow)(e.Row)), e.Action)); } } protected override void OnRowDeleting(DataRowChangeEventArgs e) { base.OnRowDeleting(e); if ((Order_DetailsRowDeleting != null)) { Order_DetailsRowDeleting(this, new Order_DetailsRowChangeEvent(((Order_DetailsRow)(e.Row)), e.Action)); } } public void RemoveOrder_DetailsRow(Order_DetailsRow row) { Rows.Remove(row); } } public class Order_DetailsRow : DataRow { private Order_DetailsDataTable _tableOrder_Details; internal Order_DetailsRow(DataRowBuilder rb) : base(rb) { _tableOrder_Details = ((Order_DetailsDataTable)(Table)); } public int OrderID { get { return ((int)(this[_tableOrder_Details.OrderIDColumn])); } set { this[_tableOrder_Details.OrderIDColumn] = value; } } public int ProductID { get { return ((int)(this[_tableOrder_Details.ProductIDColumn])); } set { this[_tableOrder_Details.ProductIDColumn] = value; } } public decimal UnitPrice { get { return ((decimal)(this[_tableOrder_Details.UnitPriceColumn])); } set { this[_tableOrder_Details.UnitPriceColumn] = value; } } public short Quantity { get { return ((short)(this[_tableOrder_Details.QuantityColumn])); } set { this[_tableOrder_Details.QuantityColumn] = value; } } public string Discount { get { try { return ((string)(this[_tableOrder_Details.DiscountColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrder_Details.DiscountColumn] = value; } } public OrdersRow OrdersRow { get { return ((OrdersRow)(GetParentRow(Table.ParentRelations["OrdersOrder_x0020_Details"]))); } set { SetParentRow(value, Table.ParentRelations["OrdersOrder_x0020_Details"]); } } public bool IsDiscountNull() { return IsNull(_tableOrder_Details.DiscountColumn); } public void SetDiscountNull() { this[_tableOrder_Details.DiscountColumn] = DBNull.Value; } } public class Order_DetailsRowChangeEvent : EventArgs { private Order_DetailsRow _eventRow; private DataRowAction _eventAction; public Order_DetailsRowChangeEvent(Order_DetailsRow row, DataRowAction action) { _eventRow = row; _eventAction = action; } public Order_DetailsRow Row { get { return _eventRow; } } public DataRowAction Action { get { return _eventAction; } } } public class OrdersDataTable : DataTable, IEnumerable { private DataColumn _columnOrderID; private DataColumn _columnCustomerID; private DataColumn _columnEmployeeID; private DataColumn _columnOrderDate; private DataColumn _columnRequiredDate; private DataColumn _columnShippedDate; private DataColumn _columnShipVia; private DataColumn _columnFreight; private DataColumn _columnShipName; private DataColumn _columnShipAddress; private DataColumn _columnShipCity; private DataColumn _columnShipRegion; private DataColumn _columnShipPostalCode; private DataColumn _columnShipCountry; internal OrdersDataTable() : base("Orders") { InitClass(); } internal OrdersDataTable(DataTable table) : base(table.TableName) { if ((table.CaseSensitive != table.DataSet.CaseSensitive)) { CaseSensitive = table.CaseSensitive; } if ((table.Locale.ToString() != table.DataSet.Locale.ToString())) { Locale = table.Locale; } if ((table.Namespace != table.DataSet.Namespace)) { Namespace = table.Namespace; } Prefix = table.Prefix; MinimumCapacity = table.MinimumCapacity; DisplayExpression = table.DisplayExpression; } [Browsable(false)] public int Count { get { return Rows.Count; } } internal DataColumn OrderIDColumn { get { return _columnOrderID; } } internal DataColumn CustomerIDColumn { get { return _columnCustomerID; } } internal DataColumn EmployeeIDColumn { get { return _columnEmployeeID; } } internal DataColumn OrderDateColumn { get { return _columnOrderDate; } } internal DataColumn RequiredDateColumn { get { return _columnRequiredDate; } } internal DataColumn ShippedDateColumn { get { return _columnShippedDate; } } internal DataColumn ShipViaColumn { get { return _columnShipVia; } } internal DataColumn FreightColumn { get { return _columnFreight; } } internal DataColumn ShipNameColumn { get { return _columnShipName; } } internal DataColumn ShipAddressColumn { get { return _columnShipAddress; } } internal DataColumn ShipCityColumn { get { return _columnShipCity; } } internal DataColumn ShipRegionColumn { get { return _columnShipRegion; } } internal DataColumn ShipPostalCodeColumn { get { return _columnShipPostalCode; } } internal DataColumn ShipCountryColumn { get { return _columnShipCountry; } } public OrdersRow this[int index] { get { return ((OrdersRow)(Rows[index])); } } public event OrdersRowChangeEventHandler OrdersRowChanged; public event OrdersRowChangeEventHandler OrdersRowChanging; public event OrdersRowChangeEventHandler OrdersRowDeleted; public event OrdersRowChangeEventHandler OrdersRowDeleting; public void AddOrdersRow(OrdersRow row) { Rows.Add(row); } public OrdersRow AddOrdersRow(string CustomerID, int EmployeeID, DateTime OrderDate, DateTime RequiredDate, DateTime ShippedDate, int ShipVia, decimal Freight, string ShipName, string ShipAddress, string ShipCity, string ShipRegion, string ShipPostalCode, string ShipCountry) { OrdersRow rowOrdersRow = ((OrdersRow)(NewRow())); rowOrdersRow.ItemArray = new object[] { null, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry}; Rows.Add(rowOrdersRow); return rowOrdersRow; } public OrdersRow FindByOrderID(int OrderID) { return ((OrdersRow)(Rows.Find(new object[] { OrderID}))); } public IEnumerator GetEnumerator() { return Rows.GetEnumerator(); } public override DataTable Clone() { OrdersDataTable cln = ((OrdersDataTable)(base.Clone())); cln.InitVars(); return cln; } protected override DataTable CreateInstance() { return new OrdersDataTable(); } internal void InitVars() { _columnOrderID = Columns["OrderID"]; _columnCustomerID = Columns["CustomerID"]; _columnEmployeeID = Columns["EmployeeID"]; _columnOrderDate = Columns["OrderDate"]; _columnRequiredDate = Columns["RequiredDate"]; _columnShippedDate = Columns["ShippedDate"]; _columnShipVia = Columns["ShipVia"]; _columnFreight = Columns["Freight"]; _columnShipName = Columns["ShipName"]; _columnShipAddress = Columns["ShipAddress"]; _columnShipCity = Columns["ShipCity"]; _columnShipRegion = Columns["ShipRegion"]; _columnShipPostalCode = Columns["ShipPostalCode"]; _columnShipCountry = Columns["ShipCountry"]; } private void InitClass() { _columnOrderID = new DataColumn("OrderID", typeof(int), null, MappingType.Element); Columns.Add(_columnOrderID); _columnCustomerID = new DataColumn("CustomerID", typeof(string), null, MappingType.Element); Columns.Add(_columnCustomerID); _columnEmployeeID = new DataColumn("EmployeeID", typeof(int), null, MappingType.Element); Columns.Add(_columnEmployeeID); _columnOrderDate = new DataColumn("OrderDate", typeof(DateTime), null, MappingType.Element); Columns.Add(_columnOrderDate); _columnRequiredDate = new DataColumn("RequiredDate", typeof(DateTime), null, MappingType.Element); Columns.Add(_columnRequiredDate); _columnShippedDate = new DataColumn("ShippedDate", typeof(DateTime), null, MappingType.Element); Columns.Add(_columnShippedDate); _columnShipVia = new DataColumn("ShipVia", typeof(int), null, MappingType.Element); Columns.Add(_columnShipVia); _columnFreight = new DataColumn("Freight", typeof(decimal), null, MappingType.Element); Columns.Add(_columnFreight); _columnShipName = new DataColumn("ShipName", typeof(string), null, MappingType.Element); Columns.Add(_columnShipName); _columnShipAddress = new DataColumn("ShipAddress", typeof(string), null, MappingType.Element); Columns.Add(_columnShipAddress); _columnShipCity = new DataColumn("ShipCity", typeof(string), null, MappingType.Element); Columns.Add(_columnShipCity); _columnShipRegion = new DataColumn("ShipRegion", typeof(string), null, MappingType.Element); Columns.Add(_columnShipRegion); _columnShipPostalCode = new DataColumn("ShipPostalCode", typeof(string), null, MappingType.Element); Columns.Add(_columnShipPostalCode); _columnShipCountry = new DataColumn("ShipCountry", typeof(string), null, MappingType.Element); Columns.Add(_columnShipCountry); Constraints.Add(new UniqueConstraint("Constraint1", new DataColumn[] { _columnOrderID}, true)); _columnOrderID.AutoIncrement = true; _columnOrderID.AllowDBNull = false; _columnOrderID.ReadOnly = true; _columnOrderID.Unique = true; } public OrdersRow NewOrdersRow() { return ((OrdersRow)(NewRow())); } protected override DataRow NewRowFromBuilder(DataRowBuilder builder) { return new OrdersRow(builder); } protected override Type GetRowType() { return typeof(OrdersRow); } protected override void OnRowChanged(DataRowChangeEventArgs e) { base.OnRowChanged(e); if ((OrdersRowChanged != null)) { OrdersRowChanged(this, new OrdersRowChangeEvent(((OrdersRow)(e.Row)), e.Action)); } } protected override void OnRowChanging(DataRowChangeEventArgs e) { base.OnRowChanging(e); if ((OrdersRowChanging != null)) { OrdersRowChanging(this, new OrdersRowChangeEvent(((OrdersRow)(e.Row)), e.Action)); } } protected override void OnRowDeleted(DataRowChangeEventArgs e) { base.OnRowDeleted(e); if ((OrdersRowDeleted != null)) { OrdersRowDeleted(this, new OrdersRowChangeEvent(((OrdersRow)(e.Row)), e.Action)); } } protected override void OnRowDeleting(DataRowChangeEventArgs e) { base.OnRowDeleting(e); if ((OrdersRowDeleting != null)) { OrdersRowDeleting(this, new OrdersRowChangeEvent(((OrdersRow)(e.Row)), e.Action)); } } public void RemoveOrdersRow(OrdersRow row) { Rows.Remove(row); } } public class OrdersRow : DataRow { private OrdersDataTable _tableOrders; internal OrdersRow(DataRowBuilder rb) : base(rb) { _tableOrders = ((OrdersDataTable)(Table)); } public int OrderID { get { return ((int)(this[_tableOrders.OrderIDColumn])); } set { this[_tableOrders.OrderIDColumn] = value; } } public string CustomerID { get { try { return ((string)(this[_tableOrders.CustomerIDColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.CustomerIDColumn] = value; } } public int EmployeeID { get { try { return ((int)(this[_tableOrders.EmployeeIDColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.EmployeeIDColumn] = value; } } public DateTime OrderDate { get { try { return ((DateTime)(this[_tableOrders.OrderDateColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.OrderDateColumn] = value; } } public DateTime RequiredDate { get { try { return ((DateTime)(this[_tableOrders.RequiredDateColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.RequiredDateColumn] = value; } } public DateTime ShippedDate { get { try { return ((DateTime)(this[_tableOrders.ShippedDateColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.ShippedDateColumn] = value; } } public int ShipVia { get { try { return ((int)(this[_tableOrders.ShipViaColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.ShipViaColumn] = value; } } public decimal Freight { get { try { return ((decimal)(this[_tableOrders.FreightColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.FreightColumn] = value; } } public string ShipName { get { try { return ((string)(this[_tableOrders.ShipNameColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.ShipNameColumn] = value; } } public string ShipAddress { get { try { return ((string)(this[_tableOrders.ShipAddressColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.ShipAddressColumn] = value; } } public string ShipCity { get { try { return ((string)(this[_tableOrders.ShipCityColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.ShipCityColumn] = value; } } public string ShipRegion { get { try { return ((string)(this[_tableOrders.ShipRegionColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.ShipRegionColumn] = value; } } public string ShipPostalCode { get { try { return ((string)(this[_tableOrders.ShipPostalCodeColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.ShipPostalCodeColumn] = value; } } public string ShipCountry { get { try { return ((string)(this[_tableOrders.ShipCountryColumn])); } catch (InvalidCastException e) { throw new StrongTypingException("Cannot get value because it is DBNull.", e); } } set { this[_tableOrders.ShipCountryColumn] = value; } } public bool IsCustomerIDNull() { return IsNull(_tableOrders.CustomerIDColumn); } public void SetCustomerIDNull() { this[_tableOrders.CustomerIDColumn] = DBNull.Value; } public bool IsEmployeeIDNull() { return IsNull(_tableOrders.EmployeeIDColumn); } public void SetEmployeeIDNull() { this[_tableOrders.EmployeeIDColumn] = DBNull.Value; } public bool IsOrderDateNull() { return IsNull(_tableOrders.OrderDateColumn); } public void SetOrderDateNull() { this[_tableOrders.OrderDateColumn] = DBNull.Value; } public bool IsRequiredDateNull() { return IsNull(_tableOrders.RequiredDateColumn); } public void SetRequiredDateNull() { this[_tableOrders.RequiredDateColumn] = DBNull.Value; } public bool IsShippedDateNull() { return IsNull(_tableOrders.ShippedDateColumn); } public void SetShippedDateNull() { this[_tableOrders.ShippedDateColumn] = DBNull.Value; } public bool IsShipViaNull() { return IsNull(_tableOrders.ShipViaColumn); } public void SetShipViaNull() { this[_tableOrders.ShipViaColumn] = DBNull.Value; } public bool IsFreightNull() { return IsNull(_tableOrders.FreightColumn); } public void SetFreightNull() { this[_tableOrders.FreightColumn] = DBNull.Value; } public bool IsShipNameNull() { return IsNull(_tableOrders.ShipNameColumn); } public void SetShipNameNull() { this[_tableOrders.ShipNameColumn] = DBNull.Value; } public bool IsShipAddressNull() { return IsNull(_tableOrders.ShipAddressColumn); } public void SetShipAddressNull() { this[_tableOrders.ShipAddressColumn] = DBNull.Value; } public bool IsShipCityNull() { return IsNull(_tableOrders.ShipCityColumn); } public void SetShipCityNull() { this[_tableOrders.ShipCityColumn] = DBNull.Value; } public bool IsShipRegionNull() { return IsNull(_tableOrders.ShipRegionColumn); } public void SetShipRegionNull() { this[_tableOrders.ShipRegionColumn] = DBNull.Value; } public bool IsShipPostalCodeNull() { return IsNull(_tableOrders.ShipPostalCodeColumn); } public void SetShipPostalCodeNull() { this[_tableOrders.ShipPostalCodeColumn] = DBNull.Value; } public bool IsShipCountryNull() { return IsNull(_tableOrders.ShipCountryColumn); } public void SetShipCountryNull() { this[_tableOrders.ShipCountryColumn] = DBNull.Value; } public Order_DetailsRow[] GetOrder_DetailsRows() { return ((Order_DetailsRow[])(GetChildRows(Table.ChildRelations["OrdersOrder_x0020_Details"]))); } } public class OrdersRowChangeEvent : EventArgs { private OrdersRow _eventRow; private DataRowAction _eventAction; public OrdersRowChangeEvent(OrdersRow row, DataRowAction action) { _eventRow = row; _eventAction = action; } public OrdersRow Row { get { return _eventRow; } } public DataRowAction Action { get { return _eventAction; } } } } } }
using System; using System.Net.Configuration; using Karl.Core; using Karl.Entities; using Karl.Game; using Karl.Graphics; using Karl.Graphics.Extensions; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using QuadtreeDemo.Collision; using QuadtreeDemo.Entities; using QuadtreeDemo.Quadtree; namespace QuadtreeDemo.States { public class DemoGameState : GameState { struct UiFlags { public bool ShowQuadtreeNodes; public bool ShowEntityNodeAssociations; public bool ShowEntityBoundingBoxes; public bool ShowEntityIndex; } private const int NumWuschels = 40000; private int _wuschelCount; private readonly Timer _wuschelCreationTimer = new Timer(); private Layer _wuschelLayer; private Layer _uiLayer; private World _world; private SpriteBatch _spriteBatch; private Camera _camera; private bool _enableAutoSpawn = false; private readonly TimeSpan _wuschelSpawnInterval = TimeSpan.FromMilliseconds(2); private KeyboardState _previousKeyboardState; private KeyboardState _currentKeyboardState; private Quadtree<BaseEntity> _quadtree; private DrawingUtils _drawingUtils; private readonly Random _random = new Random(1); private readonly Rectangle _creationBounds = new Rectangle(-250, -250, 500, 500); private SpriteFont _uiFont; private TextInstance _wuschelCounterText; private UiFlags _uiFlags = new UiFlags() { ShowEntityBoundingBoxes = false, ShowEntityIndex = false, ShowEntityNodeAssociations = false, ShowQuadtreeNodes = true }; public override void Initialize(GameStateManager manager) { base.Initialize(manager); _drawingUtils = new DrawingUtils(); _spriteBatch = new SpriteBatch(GraphicsDevice); _camera = new Camera(Transform.Identity); _world = new World( () => new QuadtreeSpace(_creationBounds) ); _wuschelLayer = new Layer(1.0f, 1.0f); _world.Layers.Add(_wuschelLayer); _uiLayer = new Layer(0f, 1f); _world.Layers.Add(_uiLayer); _wuschelCounterText = new TextInstance() { Transform = new Transform(380, -230), Align = Align.TopRight }; _uiLayer.Texts.Add(_wuschelCounterText); _quadtree = new Quadtree<BaseEntity>(_creationBounds); } public override void LoadContent() { _uiFont = Content.Load<SpriteFont>("Arial20"); _wuschelCounterText.Font = _uiFont; _world.LoadContent(Content); } private void CreateWuschel() { _wuschelCount += 1; _wuschelCreationTimer.Start(_wuschelSpawnInterval); _wuschelCounterText.Text = "Wuschels: " + _wuschelCount; var wuschel = new Wuschel(_wuschelLayer) {Index = _wuschelCount}; var pos = new Vector2( _random.Next(_creationBounds.Left, _creationBounds.Right), _random.Next(_creationBounds.Top, _creationBounds.Bottom) ); wuschel.Transform = new Transform(pos); _world.AddEntity(wuschel); _quadtree.AddObject(wuschel); } public override void Update(GameTime gameTime) { var elapsedTime = gameTime.ElapsedGameTime; UpdateInput(elapsedTime); UpdateTimers(elapsedTime); if (_wuschelCount < NumWuschels && _wuschelCreationTimer.TimeLeft <= TimeSpan.Zero && _enableAutoSpawn) { CreateWuschel(); } _world.Update(elapsedTime); } private void UpdateTimers(TimeSpan elapsedTime) { _wuschelCreationTimer.Update(elapsedTime); } private void UpdateInput(TimeSpan elapsedTime) { _currentKeyboardState = Keyboard.GetState(); if (KeyPressed(Keys.F1)) { CreateWuschel(); } if (KeyPressed(Keys.F2)) _uiFlags.ShowEntityBoundingBoxes = !_uiFlags.ShowEntityBoundingBoxes; if (KeyPressed(Keys.F3)) _uiFlags.ShowEntityIndex = !_uiFlags.ShowEntityIndex; if (KeyPressed(Keys.F4)) _uiFlags.ShowEntityNodeAssociations = !_uiFlags.ShowEntityNodeAssociations; if (KeyPressed(Keys.F5)) _uiFlags.ShowQuadtreeNodes = !_uiFlags.ShowQuadtreeNodes; var cameraDelta = Vector2.Zero; float camSpeed = (float)(200 * elapsedTime.TotalSeconds); if (KeyDown(Keys.A)) cameraDelta.X -= camSpeed; if(KeyDown(Keys.D)) cameraDelta.X += camSpeed; if(KeyDown(Keys.W)) cameraDelta.Y -= camSpeed; if (KeyDown(Keys.S)) cameraDelta.Y += camSpeed; if (KeyDown(Keys.Q)) _camera.Scale = (float)Math.Max(_camera.Scale - 1*elapsedTime.TotalSeconds, 0.001f); if (KeyDown(Keys.E)) _camera.Scale = (float)Math.Min(_camera.Scale + 1 * elapsedTime.TotalSeconds, 100f); _camera.Position += cameraDelta; _previousKeyboardState = _currentKeyboardState; } private bool KeyPressed(Keys key) { return _currentKeyboardState.IsKeyDown(key) && _previousKeyboardState.IsKeyUp(key); } private bool KeyDown(Keys key) { return _currentKeyboardState.IsKeyDown(key); } public override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); _world.Draw(_spriteBatch, _camera); VisualizeQuadtree(); } private void VisualizeQuadtree() { var tempCamera = _camera; tempCamera.Position *= _wuschelLayer.Speed; tempCamera.Scale /= _wuschelLayer.Scale; _spriteBatch.Begin(tempCamera); _quadtree.RunVisitor((node, depth) => { if(_uiFlags.ShowQuadtreeNodes) _drawingUtils.Draw(_spriteBatch, node.BoundingBox, Color.BurlyWood); var nodeCenter = new Vector2( node.BoundingBox.Center.X, node.BoundingBox.Center.Y ); foreach (var entity in node.Data) { if(_uiFlags.ShowEntityBoundingBoxes) _drawingUtils.Draw(_spriteBatch, entity.BoundingBox, Color.DarkGreen); if(_uiFlags.ShowEntityNodeAssociations) _drawingUtils.DrawLine(_spriteBatch, entity.Transform.Position, nodeCenter, Color.BlueViolet); if(_uiFlags.ShowEntityIndex) _spriteBatch.DrawString(_uiFont, entity.Index.ToString(), entity.Transform.Position, Color.AntiqueWhite); } return true; }); _spriteBatch.End(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// RouteTablesOperations operations. /// </summary> internal partial class RouteTablesOperations : IServiceOperations<NetworkManagementClient>, IRouteTablesOperations { /// <summary> /// Initializes a new instance of the RouteTablesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal RouteTablesOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Deletes the specified route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<RouteTable>> GetWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeTableName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("routeTableName", routeTableName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<RouteTable>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteTable>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create or updates a route table in a specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update route table operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<RouteTable>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, RouteTable parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<RouteTable> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all route tables in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<RouteTable>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<RouteTable>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteTable>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all route tables in a subscription. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<RouteTable>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/routeTables").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<RouteTable>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteTable>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeTableName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("routeTableName", routeTableName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create or updates a route table in a specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update route table operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<RouteTable>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, RouteTable parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeTableName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("routeTableName", routeTableName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<RouteTable>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteTable>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteTable>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all route tables in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<RouteTable>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<RouteTable>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteTable>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all route tables in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<RouteTable>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<RouteTable>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RouteTable>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// 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. using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Firebase; using Firebase.Firestore; using NUnit.Framework; using UnityEngine.TestTools; using static Tests.TestAsserts; namespace Tests { // Tests that passing invalid input to SWIG-wrapped functions results in a C# exception instead // of a crash. public class InvalidArgumentsTest : FirestoreIntegrationTests { [Test] public void CollectionReference_AddAsync_NullDocumentData() { CollectionReference collection = db.Collection("a"); Assert.Throws<ArgumentNullException>(() => collection.AddAsync(null)); } [UnityTest] public IEnumerator CollectionReference_AddAsync_DocumentDataWithEmptyKey() { CollectionReference collection = db.Collection("a"); yield return AwaitFaults(collection.AddAsync(new Dictionary<string, object> { { "", 42 } })); } [UnityTest] public IEnumerator CollectionReference_AddAsync_InvalidDocumentDataType() { CollectionReference collection = db.Collection("a"); yield return AwaitFaults(collection.AddAsync(42)); } [Test] public void CollectionReference_Document_NullStringPath() { CollectionReference collection = TestCollection(); Assert.Throws<ArgumentNullException>(() => collection.Document(null)); } [Test] public void CollectionReference_Document_EmptyStringPath() { CollectionReference collection = TestCollection(); Assert.Throws<ArgumentException>(() => collection.Document("")); } [Test] public void CollectionReference_Document_EvenNumberOfPathSegments() { CollectionReference collection = TestCollection(); Assert.Throws<ArgumentException>(() => collection.Document("b/c")); } [Test] public void DocumentReference_Collection_NullStringPath() { DocumentReference doc = TestDocument(); Assert.Throws<ArgumentNullException>(() => doc.Collection(null)); } [Test] public void DocumentReference_Collection_EmptyStringPath() { DocumentReference doc = TestDocument(); Assert.Throws<ArgumentException>(() => doc.Collection("")); } [Test] public void DocumentReference_Collection_EvenNumberOfPathSegments() { DocumentReference doc = TestDocument(); Assert.Throws<ArgumentException>(() => doc.Collection("a/b")); } [Test] public void DocumentReference_Listen_1Arg_NullCallback() { DocumentReference doc = TestDocument(); Assert.Throws<ArgumentNullException>(() => doc.Listen(null)); } [Test] public void DocumentReference_Listen_2Args_NullCallback() { DocumentReference doc = TestDocument(); Assert.Throws<ArgumentNullException>(() => doc.Listen(MetadataChanges.Include, null)); } [Test] public void DocumentReference_SetAsync_NullDocumentData() { DocumentReference doc = TestDocument(); Assert.Throws<ArgumentNullException>(() => doc.SetAsync(null, null)); } [UnityTest] public IEnumerator DocumentReference_SetAsync_DocumentDataWithEmptyKey() { DocumentReference doc = TestDocument(); yield return AwaitFaults(doc.SetAsync(new Dictionary<string, object> { { "", 42 } }, null)); } [UnityTest] public IEnumerator DocumentReference_SetAsync_InvalidDocumentDataType() { DocumentReference doc = TestDocument(); yield return AwaitFaults(doc.SetAsync(42, null)); } [Test] public void DocumentReference_UpdateAsync_NullStringKeyedDictionary() { DocumentReference doc = TestDocument(); Assert.Throws<ArgumentNullException>(() => doc.UpdateAsync((IDictionary<string, object>)null)); } [UnityTest] public IEnumerator DocumentReference_UpdateAsync_EmptyStringKeyedDictionary() { DocumentReference doc = TestDocument(); yield return AwaitSuccess(doc.SetAsync(TestData(), null)); yield return AwaitSuccess(doc.UpdateAsync(new Dictionary<string, object>())); } [UnityTest] public IEnumerator DocumentReference_UpdateAsync_StringKeyedDictionaryWithEmptyKey() { DocumentReference doc = TestDocument(); yield return AwaitSuccess(doc.SetAsync(TestData(), null)); yield return AwaitFaults(doc.UpdateAsync(new Dictionary<string, object> { { "", 42 } })); } [Test] public void DocumentReference_UpdateAsync_NullStringField() { DocumentReference doc = TestDocument(); Assert.Throws<ArgumentNullException>(() => doc.UpdateAsync(null, 42)); } [UnityTest] public IEnumerator DocumentReference_UpdateAsync_EmptyStringField() { DocumentReference doc = TestDocument(); yield return AwaitSuccess(doc.SetAsync(TestData(), null)); yield return AwaitFaults(doc.UpdateAsync("", 42)); } [Test] public void DocumentReference_UpdateAsync_NullFieldPathKeyedDictionary() { DocumentReference doc = TestDocument(); Assert.Throws<ArgumentNullException>( () => doc.UpdateAsync((IDictionary<FieldPath, object>)null)); } [UnityTest] public IEnumerator DocumentReference_UpdateAsync_EmptyFieldPathKeyedDictionary() { DocumentReference doc = TestDocument(); yield return AwaitSuccess(doc.SetAsync(TestData(), null)); yield return AwaitSuccess(doc.UpdateAsync(new Dictionary<FieldPath, object>())); } [UnityTest] public IEnumerator DocumentSnapshot_ContainsField_NullStringPath() { var steps = RunWithTestDocumentSnapshot(snapshot => { Assert.Throws<ArgumentNullException>(() => snapshot.ContainsField((string)null)); }); foreach (var step in steps) yield return step; } [UnityTest] public IEnumerator DocumentSnapshot_ContainsField_EmptyStringPath() { var steps = RunWithTestDocumentSnapshot( snapshot => { Assert.Throws<ArgumentException>(() => snapshot.ContainsField("")); }); foreach (var step in steps) yield return step; } [UnityTest] public IEnumerator DocumentSnapshot_ContainsField_NullFieldPath() { var steps = RunWithTestDocumentSnapshot(snapshot => { Assert.Throws<ArgumentNullException>(() => snapshot.ContainsField((FieldPath)null)); }); foreach (var step in steps) yield return step; } [UnityTest] public IEnumerator DocumentSnapshot_GetValue_NullStringPath() { var steps = RunWithTestDocumentSnapshot(snapshot => { Assert.Throws<ArgumentNullException>( () => snapshot.GetValue<object>((string)null, ServerTimestampBehavior.None)); }); foreach (var step in steps) yield return step; } [UnityTest] public IEnumerator DocumentSnapshot_GetValue_EmptyStringPath() { var steps = RunWithTestDocumentSnapshot(snapshot => { Assert.Throws<ArgumentException>( () => snapshot.GetValue<object>("", ServerTimestampBehavior.None)); }); foreach (var step in steps) yield return step; } [UnityTest] public IEnumerator DocumentSnapshot_GetValue_NullFieldPath() { var steps = RunWithTestDocumentSnapshot(snapshot => { Assert.Throws<ArgumentNullException>( () => snapshot.GetValue<object>((FieldPath)null, ServerTimestampBehavior.None)); }); foreach (var step in steps) yield return step; } [UnityTest] public IEnumerator DocumentSnapshot_TryGetValue_NullStringPath() { var steps = RunWithTestDocumentSnapshot(snapshot => { object value = null; Assert.Throws<ArgumentNullException>( () => snapshot.TryGetValue((string)null, out value, ServerTimestampBehavior.None)); }); foreach (var step in steps) yield return step; } [UnityTest] public IEnumerator DocumentSnapshot_TryGetValue_EmptyStringPath() { var steps = RunWithTestDocumentSnapshot(snapshot => { object value = null; Assert.Throws<ArgumentException>( () => snapshot.TryGetValue("", out value, ServerTimestampBehavior.None)); }); foreach (var step in steps) yield return step; } [UnityTest] public IEnumerator DocumentSnapshot_TryGetValue_NullFieldPath() { var steps = RunWithTestDocumentSnapshot(snapshot => { object value = null; Assert.Throws<ArgumentNullException>( () => snapshot.TryGetValue((FieldPath)null, out value, ServerTimestampBehavior.None)); }); foreach (var step in steps) yield return step; } /** * Creates a `DocumentSnapshot` then invokes the given action with it synchronously in the * calling thread. This enables the caller to use standard asserts since any exceptions * they throw will be thrown in the calling thread's context and bubble up to the test runner. */ private IEnumerable RunWithTestDocumentSnapshot(Action<DocumentSnapshot> action) { DocumentReference doc = TestDocument(); doc.SetAsync(TestData()); Task<DocumentSnapshot> task = doc.GetSnapshotAsync(Source.Cache); yield return AwaitSuccess(task); DocumentSnapshot snapshot = task.Result; action(snapshot); } [Test] public void FieldPath_Constructor_NullStringArray() { Assert.Throws<ArgumentNullException>(() => new FieldPath(null)); } [Test] public void FieldPath_Constructor_StringArrayWithNullElement() { Assert.Throws<ArgumentException>(() => new FieldPath(new string[] { null })); } [Test] public void FieldPath_Constructor_EmptyStringArray() { Assert.Throws<ArgumentException>(() => new FieldPath(new string[0])); } [Test] public void FieldPath_Constructor_StringArrayWithEmptyString() { Assert.Throws<ArgumentException>(() => new FieldPath(new string[] { "" })); } [Test] public void FieldValue_ArrayRemove_NullArray() { Assert.Throws<ArgumentNullException>(() => FieldValue.ArrayRemove(null)); } [Test] public void FieldValue_ArrayUnion_NullArray() { Assert.Throws<ArgumentNullException>(() => FieldValue.ArrayUnion(null)); } [Test] public void FirebaseFirestore_GetInstance_Null() { Assert.Throws<ArgumentNullException>(() => FirebaseFirestore.GetInstance(null)); } [Test] public void FirebaseFirestore_GetInstance_DisposedApp() { FirebaseApp disposedApp = FirebaseApp.Create(db.App.Options, "test-getinstance-disposedapp"); disposedApp.Dispose(); Assert.Throws<ArgumentException>(() => FirebaseFirestore.GetInstance(disposedApp)); } [Test] public void FirebaseFirestore_Collection_NullStringPath() { Assert.Throws<ArgumentNullException>(() => db.Collection(null)); } [Test] public void FirebaseFirestore_Collection_EmptyStringPath() { Assert.Throws<ArgumentException>(() => db.Collection("")); } [Test] public void FirebaseFirestore_Collection_EvenNumberOfPathSegments() { Assert.Throws<ArgumentException>(() => db.Collection("a/b")); } [Test] public void FirebaseFirestore_CollectionGroup_NullCollectionId() { Assert.Throws<ArgumentNullException>(() => db.CollectionGroup(null)); } [Test] public void FirebaseFirestore_CollectionGroup_EmptyCollectionId() { Assert.Throws<ArgumentException>(() => db.CollectionGroup("")); } [Test] public void FirebaseFirestore_CollectionGroup_CollectionIdContainsSlash() { Assert.Throws<ArgumentException>(() => db.CollectionGroup("a/b")); } [Test] public void FirebaseFirestore_Document_NullStringPath() { Assert.Throws<ArgumentNullException>(() => db.Document(null)); } [Test] public void FirebaseFirestore_Document_EmptyStringPath() { Assert.Throws<ArgumentException>(() => db.Document("")); } [Test] public void FirebaseFirestore_Document_OddNumberOfPathSegments() { Assert.Throws<ArgumentException>(() => db.Document("a/b/c")); } [Test] public void FirebaseFirestore_ListenForSnapshotsInSync_NullCallback() { Assert.Throws<ArgumentNullException>(() => db.ListenForSnapshotsInSync(null)); } [Test] public void FirebaseFirestore_RunTransactionAsync_WithoutTypeParameter_NullCallback() { Assert.Throws<ArgumentNullException>(() => db.RunTransactionAsync(null)); } [Test] public void FirebaseFirestore_RunTransactionAsync_WithTypeParameter_NullCallback() { Assert.Throws<ArgumentNullException>(() => db.RunTransactionAsync<object>(null)); } [Test] public void FirebaseFirestoreSettings_Host_Null() { FirebaseFirestoreSettings settings = db.Settings; Assert.Throws<ArgumentNullException>(() => settings.Host = null); } [Test] public void FirebaseFirestoreSettings_Host_EmptyString() { FirebaseFirestoreSettings settings = db.Settings; Assert.Throws<ArgumentException>(() => settings.Host = ""); } [Test] public void Query_EndAt_NullDocumentSnapshot() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.EndAt((DocumentSnapshot)null)); } [Test] public void Query_EndAt_NullArray() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.EndAt((object[])null)); } [Test] public void Query_EndAt_ArrayWithNullElement() { Query query = TestCollection(); Assert.Throws<ArgumentException>(() => query.EndAt(new object[] { null })); } [Test] public void Query_EndBefore_NullDocumentSnapshot() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.EndBefore((DocumentSnapshot)null)); } [Test] public void Query_EndBefore_NullArray() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.EndBefore((object[])null)); } [Test] public void Query_Limit_0() { Query query = TestCollection(); Assert.Throws<ArgumentException>(() => query.Limit(0)); } [Test] public void Query_Limit_Negative1() { Query query = TestCollection(); Assert.Throws<ArgumentException>(() => query.Limit(-1)); } [Test] public void Query_LimitToLast_0() { Query query = TestCollection(); Assert.Throws<ArgumentException>(() => query.LimitToLast(0)); } [Test] public void Query_LimitToLast_Negative1() { Query query = TestCollection(); Assert.Throws<ArgumentException>(() => query.LimitToLast(-1)); } [Test] public void Query_OrderBy_NullPathString() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.OrderBy((string)null)); } [Test] public void Query_OrderBy_EmptyPathString() { Query query = TestCollection(); Assert.Throws<ArgumentException>(() => query.OrderBy("")); } [Test] public void Query_OrderBy_NullFieldPath() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.OrderBy((FieldPath)null)); } [Test] public void Query_OrderByDescending_NullPathString() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.OrderByDescending((string)null)); } [Test] public void Query_OrderByDescending_EmptyPathString() { Query query = TestCollection(); Assert.Throws<ArgumentException>(() => query.OrderByDescending("")); } [Test] public void Query_OrderByDescending_NullFieldPath() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.OrderByDescending((FieldPath)null)); } [Test] public void Query_StartAfter_NullDocumentSnapshot() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.StartAfter((DocumentSnapshot)null)); } [Test] public void Query_StartAfter_NullArray() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.StartAfter((object[])null)); } [Test] public void Query_StartAt_NullDocumentSnapshot() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.StartAt((DocumentSnapshot)null)); } [Test] public void Query_StartAt_NullArray() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.StartAt((object[])null)); } [Test] public void Query_StartAt_ArrayWithNullElement() { Query query = TestCollection(); Assert.Throws<ArgumentException>(() => query.StartAt(new object[] { null })); } [Test] public void Query_WhereArrayContains_NullFieldPath() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.WhereArrayContains((FieldPath)null, "")); } [Test] public void Query_WhereArrayContains_NullPathString() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.WhereArrayContains((string)null, "")); } [Test] public void Query_WhereArrayContains_EmptyPathString() { Query query = TestCollection(); Assert.Throws<ArgumentException>(() => query.WhereArrayContains("", 42)); } [Test] public void Query_WhereArrayContainsAny_NullFieldPath() { Query query = TestCollection(); List<object> values = new List<object> { "" }; Assert.Throws<ArgumentNullException>( () => query.WhereArrayContainsAny((FieldPath)null, values)); } [Test] public void Query_WhereArrayContainsAny_NonNullFieldPath_NullValues() { Query query = TestCollection(); FieldPath fieldPath = new FieldPath(new string[] { "a", "b" }); Assert.Throws<ArgumentNullException>(() => query.WhereArrayContainsAny(fieldPath, null)); } [Test] public void Query_WhereArrayContainsAny_NullPathString() { Query query = TestCollection(); List<object> values = new List<object> { "" }; Assert.Throws<ArgumentNullException>(() => query.WhereArrayContainsAny((string)null, values)); } [Test] public void Query_WhereArrayContainsAny_EmptyPathString() { Query query = TestCollection(); List<object> values = new List<object> { "" }; Assert.Throws<ArgumentException>(() => query.WhereArrayContainsAny("", values)); } [Test] public void Query_WhereArrayContainsAny_NonNullPathString_NullValues() { Query query = TestCollection(); string pathString = "a/b"; Assert.Throws<ArgumentNullException>(() => query.WhereArrayContainsAny(pathString, null)); } [Test] public void Query_WhereEqualTo_NullPathString() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.WhereEqualTo((string)null, 42)); } [Test] public void Query_WhereEqualTo_EmptyPathString() { Query query = TestCollection(); Assert.Throws<ArgumentException>(() => query.WhereEqualTo("", 42)); } [Test] public void Query_WhereEqualTo_NullFieldPath() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.WhereEqualTo((FieldPath)null, 42)); } [Test] public void Query_WhereGreaterThan_NullPathString() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.WhereGreaterThan((string)null, 42)); } [Test] public void Query_WhereGreaterThan_EmptyPathString() { Query query = TestCollection(); Assert.Throws<ArgumentException>(() => query.WhereGreaterThan("", 42)); } [Test] public void Query_WhereGreaterThan_NullFieldPath() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.WhereGreaterThan((FieldPath)null, 42)); } [Test] public void Query_WhereGreaterThanOrEqualTo_NullPathString() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.WhereGreaterThanOrEqualTo((string)null, 42)); } [Test] public void Query_WhereGreaterThanOrEqualTo_EmptyPathString() { Query query = TestCollection(); Assert.Throws<ArgumentException>(() => query.WhereGreaterThanOrEqualTo("", 42)); } [Test] public void Query_WhereGreaterThanOrEqualTo_NullFieldPath() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>( () => query.WhereGreaterThanOrEqualTo((FieldPath)null, 42)); } [Test] public void Query_WhereIn_NullFieldPath() { Query query = TestCollection(); List<object> values = new List<object> { 42 }; Assert.Throws<ArgumentNullException>(() => query.WhereIn((FieldPath)null, values)); } [Test] public void Query_WhereIn_NonNullFieldPath_NullValues() { Query query = TestCollection(); FieldPath fieldPath = new FieldPath(new string[] { "a", "b" }); Assert.Throws<ArgumentNullException>(() => query.WhereIn(fieldPath, null)); } [Test] public void Query_WhereIn_NullPathString() { Query query = TestCollection(); List<object> values = new List<object> { 42 }; Assert.Throws<ArgumentNullException>(() => query.WhereIn((string)null, values)); } [Test] public void Query_WhereIn_EmptyPathString() { Query query = TestCollection(); List<object> values = new List<object> { 42 }; Assert.Throws<ArgumentException>(() => query.WhereIn("", values)); } [Test] public void Query_WhereIn_NonNullPathString_NullValues() { Query query = TestCollection(); string fieldPath = "a/b"; Assert.Throws<ArgumentNullException>(() => query.WhereIn(fieldPath, null)); } [Test] public void Query_WhereLessThan_NullPathString() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.WhereLessThan((string)null, 42)); } [Test] public void Query_WhereLessThan_EmptyPathString() { Query query = TestCollection(); Assert.Throws<ArgumentException>(() => query.WhereLessThan("", 42)); } [Test] public void Query_WhereLessThan_NullFieldPath() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.WhereLessThan((FieldPath)null, 42)); } [Test] public void Query_WhereLessThanOrEqualTo_NullPathString() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.WhereLessThanOrEqualTo((string)null, 42)); } [Test] public void Query_WhereLessThanOrEqualTo_EmptyPathString() { Query query = TestCollection(); Assert.Throws<ArgumentException>(() => query.WhereLessThanOrEqualTo("", 42)); } [Test] public void Query_WhereLessThanOrEqualTo_NullFieldPath() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.WhereLessThanOrEqualTo((FieldPath)null, 42)); } [Test] public void Query_WhereNotEqualTo_NullPathString() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.WhereNotEqualTo((string)null, 42)); } [Test] public void Query_WhereNotEqualTo_EmptyPathString() { Query query = TestCollection(); Assert.Throws<ArgumentException>(() => query.WhereNotEqualTo("", 42)); } [Test] public void Query_WhereNotEqualTo_NullFieldPath() { Query query = TestCollection(); Assert.Throws<ArgumentNullException>(() => query.WhereNotEqualTo((FieldPath)null, 42)); } [Test] public void Query_WhereNotIn_NullFieldPath() { Query query = TestCollection(); List<object> values = new List<object> { 42 }; Assert.Throws<ArgumentNullException>(() => query.WhereNotIn((FieldPath)null, values)); } [Test] public void Query_WhereNotIn_NonNullFieldPath_NullValues() { Query query = TestCollection(); FieldPath fieldPath = new FieldPath(new string[] { "a", "b" }); Assert.Throws<ArgumentNullException>(() => query.WhereNotIn(fieldPath, null)); } [Test] public void Query_WhereNotIn_NullPathString() { Query query = TestCollection(); List<object> values = new List<object> { 42 }; Assert.Throws<ArgumentNullException>(() => query.WhereNotIn((string)null, values)); } [Test] public void Query_WhereNotIn_EmptyPathString() { Query query = TestCollection(); List<object> values = new List<object> { 42 }; Assert.Throws<ArgumentException>(() => query.WhereNotIn("", values)); } [Test] public void Query_WhereNotIn_NonNullPathString_NullValues() { Query query = TestCollection(); string fieldPath = "a/b"; Assert.Throws<ArgumentNullException>(() => query.WhereNotIn(fieldPath, null)); } [UnityTest] public IEnumerator Transaction_Delete_NullDocumentReference() { IEnumerable steps = RunWithTransaction( transaction => { Assert.Throws<ArgumentNullException>(() => transaction.Delete(null)); }); foreach (var step in steps) yield return step; } [UnityTest] public IEnumerator Transaction_GetSnapshotAsync_NullDocumentReference() { IEnumerable steps = RunWithTransaction(transaction => { Assert.Throws<ArgumentNullException>(() => transaction.GetSnapshotAsync(null)); }); foreach (var step in steps) yield return step; } [UnityTest] public IEnumerator Transaction_Set_NullDocumentReference() { object documentData = TestData(); IEnumerable steps = RunWithTransaction(transaction => { Assert.Throws<ArgumentNullException>(() => transaction.Set(null, documentData, null)); }); foreach (var step in steps) yield return step; } [UnityTest] public IEnumerator Transaction_Set_NullDocumentData() { DocumentReference doc = TestDocument(); IEnumerable steps = RunWithTransaction(transaction => { Assert.Throws<ArgumentNullException>(() => transaction.Set(doc, null, null)); }); foreach (var step in steps) yield return step; } [UnityTest] public IEnumerator Transaction_Set_DocumentDataWithEmptyKey() { DocumentReference doc = TestDocument(); IEnumerable steps = RunWithTransaction(transaction => { Assert.Throws<ArgumentException>( () => transaction.Set(doc, new Dictionary<string, object> { { "", 42 } }, null)); }); foreach (var step in steps) yield return step; } [UnityTest] public IEnumerator Transaction_Set_InvalidDocumentDataType() { DocumentReference doc = TestDocument(); IEnumerable steps = RunWithTransaction(transaction => { Assert.Throws<ArgumentException>(() => transaction.Set(doc, 42, null)); }); foreach (var step in steps) yield return step; } [UnityTest] public IEnumerator Transaction_Update_NullDocumentReference_NonNullStringKeyDictionary() { IEnumerable steps = RunWithTransaction(transaction => { Assert.Throws<ArgumentNullException>( () => transaction.Update(null, new Dictionary<string, object> { { "key", 42 } })); }); foreach (var step in steps) yield return step; } [UnityTest] public IEnumerator Transaction_Update_NonNullDocumentReference_NullStringKeyDictionary() { DocumentReference doc = TestDocument(); IEnumerable steps = RunWithTransaction(transaction => { Assert.Throws<ArgumentNullException>( () => transaction.Update(doc, (IDictionary<string, object>)null)); }); foreach (var step in steps) yield return step; } [UnityTest] public IEnumerator Transaction_Update_NonNullDocumentReference_EmptyStringKeyDictionary() { DocumentReference doc = TestDocument(); yield return AwaitSuccess(doc.SetAsync(TestData(), null)); yield return AwaitSuccess(db.RunTransactionAsync(transaction => { return transaction.GetSnapshotAsync(doc).ContinueWith( snapshot => { transaction.Update(doc, new Dictionary<string, object>()); }); })); } [UnityTest] public IEnumerator Transaction_Update_NonNullDocumentReference_StringKeyDictionaryWithEmptyKey() { DocumentReference doc = TestDocument(); IEnumerable steps = RunWithTransaction(transaction => { Assert.Throws<ArgumentException>( () => transaction.Update(doc, new Dictionary<string, object> { { "", 42 } })); }); foreach (var step in steps) yield return step; } [UnityTest] public IEnumerator Transaction_Update_NullDocumentReference_NonNullFieldString() { IEnumerable steps = RunWithTransaction(transaction => { Assert.Throws<ArgumentNullException>(() => transaction.Update(null, "fieldName", 42)); }); foreach (var step in steps) yield return step; } [UnityTest] public IEnumerator Transaction_Update_NonNullDocumentReference_NullFieldString() { DocumentReference doc = TestDocument(); IEnumerable steps = RunWithTransaction(transaction => { Assert.Throws<ArgumentNullException>(() => transaction.Update(doc, (string)null, 42)); }); foreach (var step in steps) yield return step; } [UnityTest] public IEnumerator Transaction_Update_NullDocumentReference_NonNullFieldPathKeyDictionary() { var nonNullFieldPathKeyDictionary = new Dictionary<FieldPath, object> { { new FieldPath(new string[] { "a", "b" }), 42 } }; IEnumerable steps = RunWithTransaction(transaction => { Assert.Throws<ArgumentNullException>( () => transaction.Update(null, nonNullFieldPathKeyDictionary)); }); foreach (var step in steps) yield return step; } [UnityTest] public IEnumerator Transaction_Update_NonNullDocumentReference_NullFieldPathKeyDictionary() { DocumentReference doc = TestDocument(); IEnumerable steps = RunWithTransaction(transaction => { Assert.Throws<ArgumentNullException>( () => transaction.Update(doc, (IDictionary<FieldPath, object>)null)); }); foreach (var step in steps) yield return step; } [UnityTest] public IEnumerator Transaction_Update_NonNullDocumentReference_EmptyFieldPathKeyDictionary() { DocumentReference doc = TestDocument(); yield return AwaitSuccess(doc.SetAsync(TestData(), null)); yield return AwaitSuccess(db.RunTransactionAsync(transaction => { return transaction.GetSnapshotAsync(doc).ContinueWith( snapshot => { transaction.Update(doc, new Dictionary<FieldPath, object>()); }); })); } /** * Starts a transaction and invokes the given action with the `Transaction` object synchronously * in the calling thread. This enables the caller to use standard asserts since any exceptions * they throw will be thrown in the calling thread's context and bubble up to the test runner. */ private IEnumerable RunWithTransaction(Action<Transaction> action) { DocumentReference doc = TestDocument(); var taskCompletionSource = new TaskCompletionSource<object>(); Transaction capturedTransaction = null; Task transactionTask = db.RunTransactionAsync(lambdaTransaction => { Interlocked.Exchange(ref capturedTransaction, lambdaTransaction); return taskCompletionSource.Task; }); try { Transaction transaction = null; while (true) { transaction = Interlocked.Exchange(ref capturedTransaction, null); if (transaction != null) { break; } yield return null; } action(transaction); } finally { taskCompletionSource.SetResult(null); } yield return AwaitSuccess(transactionTask); } [Test] public void WriteBatch_Delete_NullDocumentReference() { WriteBatch writeBatch = db.StartBatch(); Assert.Throws<ArgumentNullException>(() => writeBatch.Delete(null)); } [Test] public void WriteBatch_Set_NullDocumentReference() { WriteBatch writeBatch = db.StartBatch(); var nonNullDocumentData = TestData(); Assert.Throws<ArgumentNullException>(() => writeBatch.Set(null, nonNullDocumentData, null)); } [Test] public void WriteBatch_Set_NullDocumentData() { WriteBatch writeBatch = db.StartBatch(); DocumentReference doc = TestDocument(); Assert.Throws<ArgumentNullException>(() => writeBatch.Set(doc, null, null)); } [Test] public void WriteBatch_Set_DocumentDataWithEmptyKey() { WriteBatch writeBatch = db.StartBatch(); DocumentReference doc = TestDocument(); Assert.Throws<ArgumentException>( () => writeBatch.Set(doc, new Dictionary<string, object> { { "", 42 } }, null)); } [Test] public void WriteBatch_Set_InvalidDocumentDataType() { WriteBatch writeBatch = db.StartBatch(); DocumentReference doc = TestDocument(); Assert.Throws<ArgumentException>(() => writeBatch.Set(doc, 42, null)); } [Test] public void WriteBatch_Update_NullDocumentReference_NonNullStringKeyDictionary() { WriteBatch writeBatch = db.StartBatch(); Assert.Throws<ArgumentNullException>( () => writeBatch.Update(null, new Dictionary<string, object> { { "key", 42 } })); } [Test] public void WriteBatch_Update_NonNullDocumentReference_NullStringKeyDictionary() { WriteBatch writeBatch = db.StartBatch(); DocumentReference doc = TestDocument(); Assert.Throws<ArgumentNullException>( () => writeBatch.Update(doc, (IDictionary<string, object>)null)); } [UnityTest] public IEnumerator WriteBatch_Update_NonNullDocumentReference_EmptyStringKeyDictionary() { WriteBatch writeBatch = db.StartBatch(); DocumentReference doc = TestDocument(); yield return AwaitSuccess(doc.SetAsync(TestData(), null)); writeBatch.Update(doc, new Dictionary<string, object>()); yield return AwaitSuccess(writeBatch.CommitAsync()); } [Test] public void WriteBatch_Update_NonNullDocumentReference_StringKeyDictionaryWithEmptyKey() { WriteBatch writeBatch = db.StartBatch(); DocumentReference doc = TestDocument(); Assert.Throws<ArgumentException>( () => writeBatch.Update(doc, new Dictionary<string, object> { { "", 42 } })); } [Test] public void WriteBatch_Update_NullDocumentReference_NonNullFieldString() { WriteBatch writeBatch = db.StartBatch(); Assert.Throws<ArgumentNullException>(() => writeBatch.Update(null, "fieldName", 42)); } [Test] public void WriteBatch_Update_NonNullDocumentReference_NullFieldString() { WriteBatch writeBatch = db.StartBatch(); DocumentReference doc = TestDocument(); Assert.Throws<ArgumentNullException>(() => writeBatch.Update(doc, (string)null, 42)); } [Test] public void WriteBatch_Update_NullDocumentReference_NonNullFieldPathKeyDictionary() { WriteBatch writeBatch = db.StartBatch(); var nonNullFieldPathKeyDictionary = new Dictionary<FieldPath, object> { { new FieldPath(new string[] { "a", "b" }), 42 } }; Assert.Throws<ArgumentNullException>( () => writeBatch.Update(null, nonNullFieldPathKeyDictionary)); } [Test] public void WriteBatch_Update_NonNullDocumentReference_NullFieldPathKeyDictionary() { WriteBatch writeBatch = db.StartBatch(); DocumentReference doc = TestDocument(); Assert.Throws<ArgumentNullException>( () => writeBatch.Update(doc, (IDictionary<FieldPath, object>)null)); } [UnityTest] public IEnumerator WriteBatch_Update_NonNullDocumentReference_EmptyFieldPathKeyDictionary() { WriteBatch writeBatch = db.StartBatch(); DocumentReference doc = TestDocument(); yield return AwaitSuccess(doc.SetAsync(TestData(), null)); writeBatch.Update(doc, new Dictionary<FieldPath, object>()); yield return AwaitSuccess(writeBatch.CommitAsync()); } [Test] public void FirebaseFirestore_LoadBundleAsync_NullBundle() { Assert.Throws<ArgumentNullException>(() => db.LoadBundleAsync(null as string)); Assert.Throws<ArgumentNullException>( () => db.LoadBundleAsync(null as string, (sender, progress) => {})); Assert.Throws<ArgumentNullException>(() => db.LoadBundleAsync(null as byte[])); Assert.Throws<ArgumentNullException>( () => db.LoadBundleAsync(null as byte[], (sender, progress) => {})); } [Test] public void FirebaseFirestore_LoadBundleAsync_NonNullBundle_NullHandler() { Assert.Throws<ArgumentNullException>(() => db.LoadBundleAsync("", null)); Assert.Throws<ArgumentNullException>(() => db.LoadBundleAsync(new byte[] {}, null)); } [Test] public void FirebaseFirestore_GetNamedQueryAsync_NullQueryName() { Assert.Throws<ArgumentNullException>(() => db.GetNamedQueryAsync(null)); } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using Nini.Config; using OpenMetaverse; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; namespace Aurora.Modules.Sound { public class SoundModule : INonSharedRegionModule, ISoundModule { //private static readonly ILog MainConsole.Instance = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly Dictionary<UUID, ConeOfSilence> Cones = new Dictionary<UUID, ConeOfSilence>(); protected IScene m_scene; public bool IsSharedModule { get { return false; } } #region INonSharedRegionModule Members public void Initialise(IConfigSource source) { } public void AddRegion(IScene scene) { m_scene = scene; m_scene.EventManager.OnNewClient += OnNewClient; m_scene.EventManager.OnClosingClient += OnClosingClient; m_scene.RegisterModuleInterface<ISoundModule>(this); } public void RemoveRegion(IScene scene) { m_scene.EventManager.OnNewClient -= OnNewClient; m_scene.EventManager.OnClosingClient -= OnClosingClient; m_scene.UnregisterModuleInterface<ISoundModule>(this); } public void RegionLoaded(IScene scene) { } public Type ReplaceableInterface { get { return null; } } public void Close() { } public string Name { get { return "Sound Module"; } } #endregion #region ISoundModule Members public virtual void PlayAttachedSound( UUID soundID, UUID ownerID, UUID objectID, double gain, Vector3 position, byte flags, float radius) { ISceneChildEntity part = m_scene.GetSceneObjectPart(objectID); if (part == null) return; bool LocalOnly = false; ILandObject ILO = null; IParcelManagementModule parcelManagement = m_scene.RequestModuleInterface<IParcelManagementModule>(); if (parcelManagement != null) { ILO = parcelManagement.GetLandObject(position.X, position.Y); if (ILO != null) LocalOnly = (ILO.LandData.Flags & (uint) ParcelFlags.SoundLocal) == (uint) ParcelFlags.SoundLocal; } m_scene.ForEachScenePresence(delegate(IScenePresence sp) { if (Cones.Count != 0) { foreach (ConeOfSilence CS in Cones.Values) { if (Util.GetDistanceTo(sp.AbsolutePosition, CS.Position) > CS.Radius) { // Presence is outside of the Cone of silence if (Util.GetDistanceTo(CS.Position, position) < CS.Radius) { //Sound was triggered inside the cone, but avatar is outside continue; } } else { // Avatar is inside the cone of silence if (Util.GetDistanceTo(CS.Position, position) > CS.Radius) { //Sound was triggered outside of the cone, but avatar is inside of the cone. continue; } } } } if (sp.IsChildAgent) return; double dis = Util.GetDistanceTo(sp.AbsolutePosition, position); if (dis > 100.0) // Max audio distance return; /*if (grp.IsAttachment) { if (grp.GetAttachmentPoint() > 30) // HUD { if (sp.ControllingClient.AgentId != grp.OwnerID) return; } if (sp.ControllingClient.AgentId == grp.OwnerID) dis = 0; }*/ //Check to see if the person is local and the av is in the same parcel if (LocalOnly && sp.CurrentParcelUUID != ILO.LandData.GlobalID) return; if ((sp.CurrentParcelUUID != ILO.LandData.GlobalID && (sp.CurrentParcel.LandData.Private || ILO.LandData.Private))) return; //If one of them is in a private parcel, and the other isn't in the same parcel, don't send the chat message // Scale by distance if (radius == 0) gain = (float) (gain*((100.0 - dis)/100.0)); else gain = (float) (gain*((radius - dis)/radius)); if (sp.Scene.GetSceneObjectPart(objectID).UseSoundQueue == 1) flags += (int) SoundFlags.Queue; sp.ControllingClient.SendPlayAttachedSound(soundID, objectID, ownerID, (float) gain, flags); }); } public virtual void AddConeOfSilence(UUID objectID, Vector3 position, double Radius) { //Must have parcel owner permissions, too many places for abuse in this ISceneEntity group = m_scene.GetSceneObjectPart(objectID).ParentEntity; IParcelManagementModule parcelManagement = m_scene.RequestModuleInterface<IParcelManagementModule>(); if (parcelManagement != null) { ILandObject land = parcelManagement.GetLandObject((int) position.X, (int) position.Y); if (!m_scene.Permissions.CanEditParcel(group.OwnerID, land)) return; } ConeOfSilence CS = new ConeOfSilence {Position = position, Radius = Radius}; Cones.Add(objectID, CS); } public virtual void RemoveConeOfSilence(UUID objectID) { Cones.Remove(objectID); } public virtual void TriggerSound( UUID soundId, UUID ownerID, UUID objectID, UUID parentID, double gain, Vector3 position, UInt64 handle, float radius) { bool LocalOnly = false; ILandObject ILO = null; IParcelManagementModule parcelManagement = m_scene.RequestModuleInterface<IParcelManagementModule>(); if (parcelManagement != null) { ILO = parcelManagement.GetLandObject(position.X, position.Y); if (ILO != null) //Check only if null, otherwise this breaks megaregions LocalOnly = (ILO.LandData.Flags & (uint) ParcelFlags.SoundLocal) == (uint) ParcelFlags.SoundLocal; } ISceneChildEntity part = m_scene.GetSceneObjectPart(objectID); if (part == null) { IScenePresence sp; if (!m_scene.TryGetScenePresence(objectID, out sp)) return; } else { ISceneEntity grp = part.ParentEntity; if (grp.IsAttachment && grp.GetAttachmentPoint() > 30) { objectID = ownerID; parentID = ownerID; } } m_scene.ForEachScenePresence(delegate(IScenePresence sp) { if (Cones.Count != 0) { foreach (ConeOfSilence CS in Cones.Values) { if (Util.GetDistanceTo(sp.AbsolutePosition, CS.Position) > CS.Radius) { // Presence is outside of the Cone of silence if (Util.GetDistanceTo(CS.Position, position) < CS.Radius) { //Sound was triggered inside the cone, but avatar is outside continue; } } else { // Avatar is inside the cone of silence if (Util.GetDistanceTo(CS.Position, position) > CS.Radius) { //Sound was triggered outside of the cone, but avatar is inside of the cone. continue; } } } } if (sp.IsChildAgent) return; double dis = Util.GetDistanceTo(sp.AbsolutePosition, position); if (dis > 100.0) // Max audio distance return; //Check to see if the person is local and the av is in the same parcel if (LocalOnly && sp.CurrentParcelUUID != ILO.LandData.GlobalID) return; // Scale by distance if (radius == 0) gain = (float) (gain*((100.0 - dis)/100.0)); else gain = (float) (gain*((radius - dis)/radius)); sp.ControllingClient.SendTriggeredSound( soundId, ownerID, objectID, parentID, handle, position, (float) gain); }); } #endregion public void PostInitialise() { } private void OnNewClient(IClientAPI client) { client.OnSoundTrigger += TriggerSound; } private void OnClosingClient(IClientAPI client) { client.OnSoundTrigger -= TriggerSound; } #region Nested type: ConeOfSilence private class ConeOfSilence { public Vector3 Position; public double Radius; } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Nimrod.Events.Api.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.IO.MemoryMappedFiles; using System.Collections.Generic; using Xunit; using System.Runtime.InteropServices; public class MMVS_ReadWrite : TestBase { [Fact] public static void ReadWriteTestCases() { bool bResult = false; MMVS_ReadWrite test = new MMVS_ReadWrite(); try { bResult = test.runTest(); } catch (Exception exc_main) { bResult = false; Console.WriteLine("Fail! Error Err_9999zzz! Uncaught Exception in main(), exc_main==" + exc_main.ToString()); } Assert.True(bResult, "One or more test cases failed."); } public bool runTest() { uint pageSize = SystemInfoHelpers.GetPageSize(); Byte[] byteArray1 = new Byte[] { 194, 58, 217, 150, 114, 62, 81, 203, 251, 39, 83, 124, 0, 0, 14, 128 }; Byte[] byteArray2 = new Byte[] { 0x35, 0x4C, 0x4A, 0x79, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 1, 0x4A, 0xCE, 0x96, 0x0C, 0, 0, 0 }; Byte[] byteArray3 = new Byte[] { 0x35, 0x4C, 0x4A, 0x79, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0 }; Byte[] byteArray3b = new Byte[] { 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; Byte[] byteArray4 = new Byte[] { 1 }; Byte[] byteArray5 = new Byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 1, 0xBB, 0x68, 0x01, 0x00, 0, 0, 0 }; Decimal dec = 20349.12309m; DateTime date = DateTime.Now; try { if (File.Exists("file1.dat")) File.Delete("file1.dat"); using (FileStream fileStream = new FileStream("file1.dat", FileMode.Create, FileAccess.ReadWrite)) { using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fileStream, "MMVS_ReadWrite0", pageSize * 10, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false)) { // Default ViewStream size - whole MMF using (MemoryMappedViewStream view = mmf.CreateViewStream()) { BinaryReader reader = new BinaryReader(view); BinaryWriter writer = new BinaryWriter(view); // nothing written - read zeros VerifyRead("Loc001", view, new Byte[24], 0, 24, new Byte[24], 24); VerifyReadBoolean("Loc002", reader, false); VerifyReadUInt16("Loc003", reader, 0); VerifyReadInt32("Loc004", reader, 0); VerifyReadDouble("Loc005", reader, 0d); VerifyReadDecimal("Loc006", reader, 0m); // Write to ViewStream view.Seek(0, SeekOrigin.Begin); view.Write(byteArray1, 0, 16); view.Seek(0, SeekOrigin.Begin); VerifyRead("Loc011", view, new Byte[16], 0, 16, byteArray1, 16); reader.BaseStream.Seek(0, SeekOrigin.Begin); VerifyReadBoolean("Loc012", reader, true); VerifyReadUInt16("Loc013", reader, 55610); VerifyReadInt32("Loc014", reader, 1363047062); VerifyReadDouble("Loc015", reader, BitConverter.ToDouble(byteArray1, 7)); reader.BaseStream.Seek(0, SeekOrigin.Begin); VerifyReadDecimal("Loc016", reader, new Decimal(new Int32[] { BitConverter.ToInt32(byteArray1, 0), BitConverter.ToInt32(byteArray1, 4), BitConverter.ToInt32(byteArray1, 8), BitConverter.ToInt32(byteArray1, 12) })); // Write to BinaryWriter writer.BaseStream.Seek(2161, SeekOrigin.Begin); writer.Write(dec); writer.Write(true); writer.Write(211209802); view.Seek(2161, SeekOrigin.Begin); VerifyRead("Loc021", view, new Byte[24], 0, 24, byteArray2, 24); reader.BaseStream.Seek(2161, SeekOrigin.Begin); VerifyReadDecimal("Loc022", reader, dec); VerifyReadBoolean("Loc023", reader, true); VerifyReadInt32("Loc024", reader, 211209802); // Write to end of stream view.Seek(-16, SeekOrigin.End); view.Write(byteArray2, 0, 16); // now at end of stream VerifyRead("Loc031", view, new Byte[16], 0, 16, new Byte[16], 0); view.Seek(-16, SeekOrigin.End); VerifyRead("Loc032", view, new Byte[16], 0, 16, byteArray3, 16); view.Seek(-8, SeekOrigin.End); VerifyRead("Loc033", view, new Byte[16], 0, 16, byteArray3b, 8); // read partial array // BinaryReader reader.BaseStream.Seek(-16, SeekOrigin.End); VerifyReadDecimal("Loc034", reader, dec); // now at end of stream VerifyReadDecimalException<IOException>("Loc035", reader); reader.BaseStream.Seek(-8, SeekOrigin.End); VerifyRead("Loc036", reader, new Byte[16], 0, 16, byteArray3b, 8); // read partial array // Write to end of stream as calculated from viewstream capacity view.Seek(view.Capacity - 1, SeekOrigin.Begin); view.Write(byteArray2, 16, 1); // now at end of stream VerifyRead("Loc041", view, new Byte[16], 0, 16, new Byte[16], 0); view.Seek(view.Capacity - 1, SeekOrigin.Begin); VerifyRead("Loc042", view, new Byte[1], 0, 1, byteArray4, 1); reader.BaseStream.Seek(view.Capacity - 1, SeekOrigin.Begin); VerifyReadBoolean("Loc043", reader, true); // now at end of stream VerifyReadBooleanException<EndOfStreamException>("Loc044", reader); // Write past end of stream view.Seek(0, SeekOrigin.End); VerifyWriteException<NotSupportedException>("Loc051", view, new Byte[16], 0, 16); writer.Seek(0, SeekOrigin.End); VerifyWriteException<NotSupportedException>("Loc052", writer, Byte.MaxValue); // Seek past end view.Seek(1, SeekOrigin.End); VerifyRead("Loc061", view, new Byte[1], 0, 1, new Byte[1], 0); view.Seek((int)(view.Capacity + 1), SeekOrigin.Begin); VerifyRead("Loc062", view, new Byte[1], 0, 1, new Byte[1], 0); // Seek before beginning VerifySeekException<IOException>("Loc065", view, -1, SeekOrigin.Begin); VerifySeekException<IOException>("Loc066", view, (int)(-view.Capacity - 1), SeekOrigin.End); VerifySeekException<IOException>("Loc067", reader.BaseStream, -1, SeekOrigin.Begin); VerifySeekException<IOException>("Loc068", reader.BaseStream, (int)(-view.Capacity - 1), SeekOrigin.End); view.Flush(); // Verify file state BinaryReader reader2 = new BinaryReader(fileStream); reader2.BaseStream.Seek(0, SeekOrigin.Begin); VerifyReadBoolean("Loc071", reader2, true); VerifyReadUInt16("Loc072", reader2, 55610); VerifyReadInt32("Loc073", reader2, 1363047062); VerifyReadDouble("Loc074", reader2, BitConverter.ToDouble(byteArray1, 7)); reader2.BaseStream.Seek(0, SeekOrigin.Begin); VerifyReadDecimal("Loc075", reader2, new Decimal(new Int32[] { BitConverter.ToInt32(byteArray1, 0), BitConverter.ToInt32(byteArray1, 4), BitConverter.ToInt32(byteArray1, 8), BitConverter.ToInt32(byteArray1, 12) })); reader2.BaseStream.Seek(2161, SeekOrigin.Begin); VerifyReadDecimal("Loc076", reader2, dec); VerifyReadBoolean("Loc077", reader2, true); VerifyReadInt32("Loc078", reader2, 211209802); reader2.BaseStream.Seek(-1, SeekOrigin.End); VerifyReadBoolean("Loc079", reader2, true); } // ViewStream starts at nonzero offset, spans remainder of MMF using (MemoryMappedViewStream view = mmf.CreateViewStream(1000, 0)) { BinaryReader reader = new BinaryReader(view); BinaryWriter writer = new BinaryWriter(view); // nothing written - read zeros VerifyRead("Loc101", view, new Byte[24], 0, 24, new Byte[24], 24); VerifyReadBoolean("Loc102", reader, false); VerifyReadUInt16("Loc103", reader, 0); VerifyReadInt32("Loc104", reader, 0); VerifyReadDouble("Loc105", reader, 0d); VerifyReadDecimal("Loc106", reader, 0m); // Write to ViewStream view.Seek(0, SeekOrigin.Begin); view.Write(byteArray1, 0, 16); view.Seek(0, SeekOrigin.Begin); VerifyRead("Loc111", view, new Byte[16], 0, 16, byteArray1, 16); reader.BaseStream.Seek(0, SeekOrigin.Begin); VerifyReadBoolean("Loc112", reader, true); VerifyReadUInt16("Loc113", reader, 55610); VerifyReadInt32("Loc114", reader, 1363047062); VerifyReadDouble("Loc115", reader, BitConverter.ToDouble(byteArray1, 7)); reader.BaseStream.Seek(0, SeekOrigin.Begin); VerifyReadDecimal("Loc116", reader, new Decimal(new Int32[] { BitConverter.ToInt32(byteArray1, 0), BitConverter.ToInt32(byteArray1, 4), BitConverter.ToInt32(byteArray1, 8), BitConverter.ToInt32(byteArray1, 12) })); // Read existing values view.Seek(1161, SeekOrigin.Begin); VerifyRead("Loc117", view, new Byte[24], 0, 24, byteArray2, 24); reader.BaseStream.Seek(1161, SeekOrigin.Begin); VerifyReadDecimal("Loc118", reader, dec); VerifyReadBoolean("Loc119", reader, true); VerifyReadInt32("Loc120", reader, 211209802); // Write to BinaryWriter writer.BaseStream.Seek(3000, SeekOrigin.Begin); writer.Write(Decimal.MaxValue); writer.Write(true); writer.Write(92347); view.Seek(3000, SeekOrigin.Begin); VerifyRead("Loc121", view, new Byte[24], 0, 24, byteArray5, 24); reader.BaseStream.Seek(3000, SeekOrigin.Begin); VerifyReadDecimal("Loc122", reader, Decimal.MaxValue); VerifyReadBoolean("Loc123", reader, true); VerifyReadInt32("Loc124", reader, 92347); // Write to end of stream view.Seek(-16, SeekOrigin.End); view.Write(byteArray2, 0, 16); // now at end of stream VerifyRead("Loc131", view, new Byte[16], 0, 16, new Byte[16], 0); view.Seek(-16, SeekOrigin.End); VerifyRead("Loc132", view, new Byte[16], 0, 16, byteArray3, 16); view.Seek(-8, SeekOrigin.End); VerifyRead("Loc133", view, new Byte[16], 0, 16, byteArray3b, 8); // read partial array // BinaryReader reader.BaseStream.Seek(-16, SeekOrigin.End); VerifyReadDecimal("Loc134", reader, dec); // now at end of stream VerifyReadDecimalException<IOException>("Loc135", reader); reader.BaseStream.Seek(-8, SeekOrigin.End); VerifyRead("Loc136", reader, new Byte[16], 0, 16, byteArray3b, 8); // read partial array // Write to end of stream as calculated from viewstream capacity view.Seek(view.Capacity - 1, SeekOrigin.Begin); view.Write(byteArray2, 16, 1); // now at end of stream VerifyRead("Loc141", view, new Byte[16], 0, 16, new Byte[16], 0); view.Seek(view.Capacity - 1, SeekOrigin.Begin); VerifyRead("Loc142", view, new Byte[1], 0, 1, byteArray4, 1); reader.BaseStream.Seek(view.Capacity - 1, SeekOrigin.Begin); VerifyReadBoolean("Loc143", reader, true); // now at end of stream VerifyReadBooleanException<IOException>("Loc144", reader); // Write past end of stream view.Seek(-8, SeekOrigin.End); VerifyWriteException<NotSupportedException>("Loc151", view, new Byte[16], 0, 16); writer.Seek(-8, SeekOrigin.End); VerifyWriteException<NotSupportedException>("Loc152", writer, Decimal.MaxValue); // Seek past end view.Seek(1, SeekOrigin.End); VerifyRead("Loc161", view, new Byte[1], 0, 1, new Byte[1], 0); view.Seek((int)(view.Capacity + 1), SeekOrigin.Begin); VerifyRead("Loc162", view, new Byte[1], 0, 1, new Byte[1], 0); // Seek before beginning VerifySeekException<IOException>("Loc165", view, -1, SeekOrigin.Begin); VerifySeekException<IOException>("Loc166", view, (int)(-view.Capacity - 1), SeekOrigin.End); VerifySeekException<IOException>("Loc167", reader.BaseStream, -1, SeekOrigin.Begin); VerifySeekException<IOException>("Loc168", reader.BaseStream, (int)(-view.Capacity - 1), SeekOrigin.End); } // ViewStream starts at nonzero offset, with size shorter than MMF using (MemoryMappedViewStream view = mmf.CreateViewStream(2000, 10000)) { BinaryReader reader = new BinaryReader(view); BinaryWriter writer = new BinaryWriter(view); // nothing written - read zeros VerifyRead("Loc201", view, new Byte[24], 0, 24, new Byte[24], 24); VerifyReadBoolean("Loc202", reader, false); VerifyReadUInt16("Loc203", reader, 0); VerifyReadInt32("Loc204", reader, 0); VerifyReadDouble("Loc205", reader, 0d); VerifyReadDecimal("Loc206", reader, 0m); // Write to ViewStream view.Seek(0, SeekOrigin.Begin); view.Write(byteArray1, 0, 16); view.Seek(0, SeekOrigin.Begin); VerifyRead("Loc211", view, new Byte[16], 0, 16, byteArray1, 16); reader.BaseStream.Seek(0, SeekOrigin.Begin); VerifyReadBoolean("Loc212", reader, true); VerifyReadUInt16("Loc213", reader, 55610); VerifyReadInt32("Loc214", reader, 1363047062); VerifyReadDouble("Loc215", reader, BitConverter.ToDouble(byteArray1, 7)); reader.BaseStream.Seek(0, SeekOrigin.Begin); VerifyReadDecimal("Loc216", reader, new Decimal(new Int32[] { BitConverter.ToInt32(byteArray1, 0), BitConverter.ToInt32(byteArray1, 4), BitConverter.ToInt32(byteArray1, 8), BitConverter.ToInt32(byteArray1, 12) })); // Read existing values view.Seek(161, SeekOrigin.Begin); VerifyRead("Loc217", view, new Byte[24], 0, 24, byteArray2, 24); reader.BaseStream.Seek(161, SeekOrigin.Begin); VerifyReadDecimal("Loc218", reader, dec); VerifyReadBoolean("Loc219", reader, true); VerifyReadInt32("Loc220", reader, 211209802); // Write to BinaryWriter writer.BaseStream.Seek(3000, SeekOrigin.Begin); writer.Write(Decimal.MaxValue); writer.Write(true); writer.Write(92347); view.Seek(3000, SeekOrigin.Begin); VerifyRead("Loc221", view, new Byte[24], 0, 24, byteArray5, 24); reader.BaseStream.Seek(3000, SeekOrigin.Begin); VerifyReadDecimal("Loc222", reader, Decimal.MaxValue); VerifyReadBoolean("Loc223", reader, true); VerifyReadInt32("Loc224", reader, 92347); // Write to end of stream view.Seek(-16, SeekOrigin.End); view.Write(byteArray2, 0, 16); // now at end of stream VerifyRead("Loc231", view, new Byte[16], 0, 16, new Byte[16], 0); view.Seek(-16, SeekOrigin.End); VerifyRead("Loc232", view, new Byte[16], 0, 16, byteArray3, 16); view.Seek(-8, SeekOrigin.End); VerifyRead("Loc233", view, new Byte[16], 0, 16, byteArray3b, 8); // read partial array // BinaryReader reader.BaseStream.Seek(-16, SeekOrigin.End); VerifyReadDecimal("Loc234", reader, dec); // now at end of stream VerifyReadDecimalException<IOException>("Loc235", reader); reader.BaseStream.Seek(-8, SeekOrigin.End); VerifyRead("Loc236", reader, new Byte[16], 0, 16, byteArray3b, 8); // read partial array // Write to end of stream as calculated from viewstream capacity view.Seek(view.Capacity - 1, SeekOrigin.Begin); view.Write(byteArray2, 16, 1); // now at end of stream VerifyRead("Loc241", view, new Byte[16], 0, 16, new Byte[16], 0); view.Seek(view.Capacity - 1, SeekOrigin.Begin); VerifyRead("Loc242", view, new Byte[1], 0, 1, byteArray4, 1); reader.BaseStream.Seek(view.Capacity - 1, SeekOrigin.Begin); VerifyReadBoolean("Loc243", reader, true); // now at end of stream VerifyReadBooleanException<IOException>("Loc244", reader); // Write past end of stream view.Seek(-1, SeekOrigin.End); VerifyWriteException<NotSupportedException>("Loc251", view, new Byte[16], 0, 2); writer.Seek(-1, SeekOrigin.End); VerifyWriteException<NotSupportedException>("Loc252", writer, Char.MaxValue); // Seek past end view.Seek(1, SeekOrigin.End); VerifyRead("Loc261", view, new Byte[1], 0, 1, new Byte[1], 0); view.Seek((int)(view.Capacity + 1), SeekOrigin.Begin); VerifyRead("Loc262", view, new Byte[1], 0, 1, new Byte[1], 0); // Seek before beginning VerifySeekException<IOException>("Loc265", view, -1, SeekOrigin.Begin); VerifySeekException<IOException>("Loc266", view, (int)(-view.Capacity - 1), SeekOrigin.End); VerifySeekException<IOException>("Loc267", reader.BaseStream, -1, SeekOrigin.Begin); VerifySeekException<IOException>("Loc268", reader.BaseStream, (int)(-view.Capacity - 1), SeekOrigin.End); } } } // Use a pagefile backed MMF instead of file backed using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("MMVS_ReadWrite1", pageSize * 10)) { using (MemoryMappedViewStream view = mmf.CreateViewStream()) { BinaryReader reader = new BinaryReader(view); BinaryWriter writer = new BinaryWriter(view); // nothing written - read zeros VerifyRead("Loc401", view, new Byte[24], 0, 24, new Byte[24], 24); VerifyReadBoolean("Loc402", reader, false); VerifyReadUInt16("Loc403", reader, 0); VerifyReadInt32("Loc404", reader, 0); VerifyReadDouble("Loc405", reader, 0d); VerifyReadDecimal("Loc406", reader, 0m); // Write to ViewStream view.Seek(0, SeekOrigin.Begin); view.Write(byteArray1, 0, 16); view.Seek(0, SeekOrigin.Begin); VerifyRead("Loc411", view, new Byte[16], 0, 16, byteArray1, 16); reader.BaseStream.Seek(0, SeekOrigin.Begin); VerifyReadBoolean("Loc412", reader, true); VerifyReadUInt16("Loc413", reader, 55610); VerifyReadInt32("Loc414", reader, 1363047062); VerifyReadDouble("Loc415", reader, BitConverter.ToDouble(byteArray1, 7)); reader.BaseStream.Seek(0, SeekOrigin.Begin); VerifyReadDecimal("Loc416", reader, new Decimal(new Int32[] { BitConverter.ToInt32(byteArray1, 0), BitConverter.ToInt32(byteArray1, 4), BitConverter.ToInt32(byteArray1, 8), BitConverter.ToInt32(byteArray1, 12) })); // Write to BinaryWriter writer.BaseStream.Seek(2161, SeekOrigin.Begin); writer.Write(dec); writer.Write(true); writer.Write(211209802); view.Seek(2161, SeekOrigin.Begin); VerifyRead("Loc421", view, new Byte[24], 0, 24, byteArray2, 24); reader.BaseStream.Seek(2161, SeekOrigin.Begin); VerifyReadDecimal("Loc422", reader, dec); VerifyReadBoolean("Loc423", reader, true); VerifyReadInt32("Loc424", reader, 211209802); // Write to end of stream view.Seek(-16, SeekOrigin.End); view.Write(byteArray2, 0, 16); // now at end of stream VerifyRead("Loc431", view, new Byte[16], 0, 16, new Byte[16], 0); view.Seek(-16, SeekOrigin.End); VerifyRead("Loc432", view, new Byte[16], 0, 16, byteArray3, 16); view.Seek(-8, SeekOrigin.End); VerifyRead("Loc433", view, new Byte[16], 0, 16, byteArray3b, 8); // read partial array // BinaryReader reader.BaseStream.Seek(-16, SeekOrigin.End); VerifyReadDecimal("Loc434", reader, dec); // now at end of stream VerifyReadDecimalException<IOException>("Loc435", reader); reader.BaseStream.Seek(-8, SeekOrigin.End); VerifyRead("Loc436", reader, new Byte[16], 0, 16, byteArray3b, 8); // read partial array // Write to end of stream as calculated from viewstream capacity view.Seek(view.Capacity - 1, SeekOrigin.Begin); view.Write(byteArray2, 16, 1); // now at end of stream VerifyRead("Loc441", view, new Byte[16], 0, 16, new Byte[16], 0); view.Seek(view.Capacity - 1, SeekOrigin.Begin); VerifyRead("Loc442", view, new Byte[1], 0, 1, byteArray4, 1); reader.BaseStream.Seek(view.Capacity - 1, SeekOrigin.Begin); VerifyReadBoolean("Loc443", reader, true); // now at end of stream VerifyReadBooleanException<IOException>("Loc444", reader); // Write past end of stream view.Seek(0, SeekOrigin.End); VerifyWriteException<NotSupportedException>("Loc451", view, new Byte[16], 0, 16); writer.Seek(0, SeekOrigin.End); VerifyWriteException<NotSupportedException>("Loc452", writer, Byte.MaxValue); // Seek past end view.Seek(1, SeekOrigin.End); VerifyRead("Loc461", view, new Byte[1], 0, 1, new Byte[1], 0); view.Seek((int)(view.Capacity + 1), SeekOrigin.Begin); VerifyRead("Loc462", view, new Byte[1], 0, 1, new Byte[1], 0); // Seek before beginning VerifySeekException<IOException>("Loc465", view, -1, SeekOrigin.Begin); VerifySeekException<IOException>("Loc466", view, (int)(-view.Capacity - 1), SeekOrigin.End); VerifySeekException<IOException>("Loc467", reader.BaseStream, -1, SeekOrigin.Begin); VerifySeekException<IOException>("Loc468", reader.BaseStream, (int)(-view.Capacity - 1), SeekOrigin.End); } using (MemoryMappedViewStream view = mmf.CreateViewStream(0, 10000, MemoryMappedFileAccess.CopyOnWrite)) { BinaryReader reader = new BinaryReader(view); BinaryWriter writer = new BinaryWriter(view); // Read existing values view.Seek(2161, SeekOrigin.Begin); VerifyRead("Loc501", view, new Byte[24], 0, 24, byteArray2, 24); reader.BaseStream.Seek(2161, SeekOrigin.Begin); VerifyReadDecimal("Loc502", reader, dec); VerifyReadBoolean("Loc503", reader, true); VerifyReadInt32("Loc504", reader, 211209802); // Write to ViewStream view.Seek(4000, SeekOrigin.Begin); view.Write(byteArray1, 0, 16); view.Seek(4000, SeekOrigin.Begin); VerifyRead("Loc511", view, new Byte[16], 0, 16, byteArray1, 16); reader.BaseStream.Seek(4000, SeekOrigin.Begin); VerifyReadBoolean("Loc512", reader, true); VerifyReadUInt16("Loc513", reader, 55610); VerifyReadInt32("Loc514", reader, 1363047062); VerifyReadDouble("Loc515", reader, BitConverter.ToDouble(byteArray1, 7)); reader.BaseStream.Seek(4000, SeekOrigin.Begin); VerifyReadDecimal("Loc516", reader, new Decimal(new Int32[] { BitConverter.ToInt32(byteArray1, 0), BitConverter.ToInt32(byteArray1, 4), BitConverter.ToInt32(byteArray1, 8), BitConverter.ToInt32(byteArray1, 12) })); } using (MemoryMappedViewStream view = mmf.CreateViewStream(0, 10000, MemoryMappedFileAccess.Read)) { BinaryReader reader = new BinaryReader(view); // Read existing values view.Seek(2161, SeekOrigin.Begin); VerifyRead("Loc601", view, new Byte[24], 0, 24, byteArray2, 24); reader.BaseStream.Seek(2161, SeekOrigin.Begin); VerifyReadDecimal("Loc602", reader, dec); VerifyReadBoolean("Loc603", reader, true); VerifyReadInt32("Loc604", reader, 211209802); // Values from CopyOnWrite ViewStream were not preserved view.Seek(4000, SeekOrigin.Begin); VerifyRead("Loc611", view, new Byte[16], 0, 16, new Byte[16], 16); reader.BaseStream.Seek(4000, SeekOrigin.Begin); VerifyReadBoolean("Loc612", reader, false); VerifyReadUInt16("Loc613", reader, 0); VerifyReadInt32("Loc614", reader, 0); VerifyReadDouble("Loc615", reader, 0d); reader.BaseStream.Seek(4000, SeekOrigin.Begin); VerifyReadDecimal("Loc616", reader, 0m); } } /// END TEST CASES if (iCountErrors == 0) { return true; } else { Console.WriteLine("Fail! iCountErrors==" + iCountErrors); return false; } } catch (Exception ex) { Console.WriteLine("ERR999: Unexpected exception in runTest, {0}", ex); return false; } } /// START HELPER FUNCTIONS public void VerifyRead(String strLoc, MemoryMappedViewStream view, Byte[] array, int offset, int count, Byte[] expected, int expectedReturn) { iCountTestcases++; try { int ret = view.Read(array, offset, count); Eval(expectedReturn, ret, "ERROR, {0}: Return value was wrong.", strLoc); if (!Eval(array.Length, expected.Length, "TEST ERROR, {0}: expected array size was wrong.", strLoc)) return; for (int i = 0; i < expected.Length; i++) if (!Eval(expected[i], array[i], "ERROR, {0}: Array value at position {1} was wrong.", strLoc, i)) { Console.WriteLine("LOC_abc, Only reporting one error for this array. Comment 'break' to see more"); break; } } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyRead(String strLoc, BinaryReader reader, Byte[] array, int offset, int count, Byte[] expected, int expectedReturn) { iCountTestcases++; try { int ret = reader.Read(array, offset, count); Eval(expectedReturn, ret, "ERROR, {0}: Return value was wrong.", strLoc); if (!Eval(array.Length, expected.Length, "TEST ERROR, {0}: expected array size was wrong.", strLoc)) return; for (int i = 0; i < expected.Length; i++) if (!Eval(expected[i], array[i], "ERROR, {0}: Array value at position {1} was wrong.", strLoc, i)) { Console.WriteLine("LOC_def, Only reporting one error for this array. Comment 'break' to see more"); break; } } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyReadBoolean(String strLoc, BinaryReader reader, Boolean expected) { iCountTestcases++; try { Boolean ret = reader.ReadBoolean(); Eval(expected, ret, "ERROR, {0}: Returned value was wrong.", strLoc); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyReadUInt16(String strLoc, BinaryReader reader, UInt16 expected) { iCountTestcases++; try { UInt16 ret = reader.ReadUInt16(); Eval(expected, ret, "ERROR, {0}: Returned value was wrong.", strLoc); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyReadInt32(String strLoc, BinaryReader reader, Int32 expected) { iCountTestcases++; try { Int32 ret = reader.ReadInt32(); Eval(expected, ret, "ERROR, {0}: Returned value was wrong.", strLoc); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyReadDouble(String strLoc, BinaryReader reader, Double expected) { iCountTestcases++; try { Double ret = reader.ReadDouble(); Eval(expected, ret, "ERROR, {0}: Returned value was wrong.", strLoc); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyReadDecimal(String strLoc, BinaryReader reader, Decimal expected) { iCountTestcases++; try { Decimal ret = reader.ReadDecimal(); Eval(expected, ret, "ERROR, {0}: Returned value was wrong.", strLoc); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyReadException<EXCTYPE>(String strLoc, MemoryMappedViewStream view, Byte[] array, int offset, int count) where EXCTYPE : Exception { iCountTestcases++; try { view.Read(array, offset, count); iCountErrors++; Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE)); } catch (EXCTYPE) { //Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyReadException<EXCTYPE>(String strLoc, BinaryReader reader, Byte[] array, int offset, int count) where EXCTYPE : Exception { iCountTestcases++; try { reader.Read(array, offset, count); iCountErrors++; Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE)); } catch (EXCTYPE) { //Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyWriteException<EXCTYPE>(String strLoc, MemoryMappedViewStream view, Byte[] array, int offset, int count) where EXCTYPE : Exception { iCountTestcases++; try { view.Write(array, offset, count); iCountErrors++; Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE)); } catch (EXCTYPE) { //Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyWriteException<EXCTYPE>(String strLoc, BinaryWriter writer, Byte value) where EXCTYPE : Exception { iCountTestcases++; try { writer.Write(value); iCountErrors++; Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE)); } catch (EXCTYPE) { //Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyWriteException<EXCTYPE>(String strLoc, BinaryWriter writer, Char value) where EXCTYPE : Exception { iCountTestcases++; try { writer.Write(value); iCountErrors++; Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE)); } catch (EXCTYPE) { //Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyWriteException<EXCTYPE>(String strLoc, BinaryWriter writer, Decimal value) where EXCTYPE : Exception { iCountTestcases++; try { writer.Write(value); iCountErrors++; Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE)); } catch (EXCTYPE) { //Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyReadBooleanException<EXCTYPE>(String strLoc, BinaryReader reader) where EXCTYPE : Exception { iCountTestcases++; try { Boolean ret = reader.ReadBoolean(); iCountErrors++; Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}, got {2}", strLoc, typeof(EXCTYPE), ret); } catch (EXCTYPE) { //Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifyReadDecimalException<EXCTYPE>(String strLoc, BinaryReader reader) where EXCTYPE : Exception { iCountTestcases++; try { Decimal ret = reader.ReadDecimal(); iCountErrors++; Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}, got {2}", strLoc, typeof(EXCTYPE), ret); } catch (EXCTYPE) { //Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifySeekException<EXCTYPE>(String strLoc, MemoryMappedViewStream view, int offset, SeekOrigin origin) where EXCTYPE : Exception { iCountTestcases++; try { long ret = view.Seek(offset, origin); iCountErrors++; Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}, got {2}", strLoc, typeof(EXCTYPE), ret); } catch (EXCTYPE) { //Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } public void VerifySeekException<EXCTYPE>(String strLoc, Stream stream, int offset, SeekOrigin origin) where EXCTYPE : Exception { iCountTestcases++; try { long ret = stream.Seek(offset, origin); iCountErrors++; Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}, got {2}", strLoc, typeof(EXCTYPE), ret); } catch (EXCTYPE) { //Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message); } catch (Exception ex) { iCountErrors++; Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex); } } }
using System.Net; using System.Text.Json; using FluentAssertions; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Serialization.Objects; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.ReadWrite.Creating; public sealed class CreateResourceWithToOneRelationshipTests : IClassFixture<IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext>> { private readonly IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> _testContext; private readonly ReadWriteFakers _fakers = new(); public CreateResourceWithToOneRelationshipTests(IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> testContext) { _testContext = testContext; testContext.UseController<WorkItemGroupsController>(); testContext.UseController<WorkItemsController>(); testContext.UseController<RgbColorsController>(); var options = (JsonApiOptions)testContext.Factory.Services.GetRequiredService<IJsonApiOptions>(); options.AllowClientGeneratedIds = true; } [Fact] public async Task Can_create_OneToOne_relationship_from_principal_side() { // Arrange WorkItemGroup existingGroup = _fakers.WorkItemGroup.Generate(); existingGroup.Color = _fakers.RgbColor.Generate(); string newGroupName = _fakers.WorkItemGroup.Generate().Name; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Groups.Add(existingGroup); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItemGroups", attributes = new { name = newGroupName }, relationships = new { color = new { data = new { type = "rgbColors", id = existingGroup.Color.StringId } } } } }; const string route = "/workItemGroups"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Data.SingleValue.ShouldNotBeNull(); responseDocument.Data.SingleValue.Attributes.ShouldNotBeEmpty(); responseDocument.Data.SingleValue.Relationships.ShouldNotBeEmpty(); string newGroupId = responseDocument.Data.SingleValue.Id.ShouldNotBeNull(); await _testContext.RunOnDatabaseAsync(async dbContext => { List<WorkItemGroup> groupsInDatabase = await dbContext.Groups.Include(group => group.Color).ToListAsync(); WorkItemGroup newGroupInDatabase = groupsInDatabase.Single(group => group.StringId == newGroupId); newGroupInDatabase.Name.Should().Be(newGroupName); newGroupInDatabase.Color.ShouldNotBeNull(); newGroupInDatabase.Color.Id.Should().Be(existingGroup.Color.Id); WorkItemGroup existingGroupInDatabase = groupsInDatabase.Single(group => group.Id == existingGroup.Id); existingGroupInDatabase.Color.Should().BeNull(); }); } [Fact] public async Task Can_create_OneToOne_relationship_from_dependent_side() { // Arrange RgbColor existingColor = _fakers.RgbColor.Generate(); existingColor.Group = _fakers.WorkItemGroup.Generate(); const string newColorId = "0A0B0C"; string newDisplayName = _fakers.RgbColor.Generate().DisplayName; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.RgbColors.Add(existingColor); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "rgbColors", id = newColorId, attributes = new { displayName = newDisplayName }, relationships = new { group = new { data = new { type = "workItemGroups", id = existingColor.Group.StringId } } } } }; const string route = "/rgbColors"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { List<RgbColor> colorsInDatabase = await dbContext.RgbColors.Include(rgbColor => rgbColor.Group).ToListAsync(); RgbColor newColorInDatabase = colorsInDatabase.Single(color => color.Id == newColorId); newColorInDatabase.DisplayName.Should().Be(newDisplayName); newColorInDatabase.Group.ShouldNotBeNull(); newColorInDatabase.Group.Id.Should().Be(existingColor.Group.Id); RgbColor? existingColorInDatabase = colorsInDatabase.SingleOrDefault(color => color.Id == existingColor.Id); existingColorInDatabase.ShouldNotBeNull(); existingColorInDatabase.Group.Should().BeNull(); }); } [Fact] public async Task Can_create_relationship_with_include() { // Arrange UserAccount existingUserAccount = _fakers.UserAccount.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.UserAccounts.Add(existingUserAccount); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", relationships = new { assignee = new { data = new { type = "userAccounts", id = existingUserAccount.StringId } } } } }; const string route = "/workItems?include=assignee"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Data.SingleValue.ShouldNotBeNull(); responseDocument.Data.SingleValue.Attributes.ShouldNotBeEmpty(); responseDocument.Data.SingleValue.Relationships.ShouldNotBeEmpty(); responseDocument.Included.ShouldHaveCount(1); responseDocument.Included[0].Type.Should().Be("userAccounts"); responseDocument.Included[0].Id.Should().Be(existingUserAccount.StringId); responseDocument.Included[0].Attributes.ShouldContainKey("firstName").With(value => value.Should().Be(existingUserAccount.FirstName)); responseDocument.Included[0].Attributes.ShouldContainKey("lastName").With(value => value.Should().Be(existingUserAccount.LastName)); responseDocument.Included[0].Relationships.ShouldNotBeEmpty(); int newWorkItemId = int.Parse(responseDocument.Data.SingleValue.Id.ShouldNotBeNull()); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Assignee).FirstWithIdAsync(newWorkItemId); workItemInDatabase.Assignee.ShouldNotBeNull(); workItemInDatabase.Assignee.Id.Should().Be(existingUserAccount.Id); }); } [Fact] public async Task Can_create_relationship_with_include_and_primary_fieldset() { // Arrange UserAccount existingUserAccount = _fakers.UserAccount.Generate(); WorkItem newWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.UserAccounts.Add(existingUserAccount); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", attributes = new { description = newWorkItem.Description, priority = newWorkItem.Priority }, relationships = new { assignee = new { data = new { type = "userAccounts", id = existingUserAccount.StringId } } } } }; const string route = "/workItems?fields[workItems]=description,assignee&include=assignee"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Data.SingleValue.ShouldNotBeNull(); responseDocument.Data.SingleValue.Attributes.ShouldHaveCount(1); responseDocument.Data.SingleValue.Attributes.ShouldContainKey("description").With(value => value.Should().Be(newWorkItem.Description)); responseDocument.Data.SingleValue.Relationships.ShouldHaveCount(1); responseDocument.Data.SingleValue.Relationships.ShouldContainKey("assignee").With(value => { value.ShouldNotBeNull(); value.Data.SingleValue.ShouldNotBeNull(); value.Data.SingleValue.Id.Should().Be(existingUserAccount.StringId); }); responseDocument.Included.ShouldHaveCount(1); responseDocument.Included[0].Type.Should().Be("userAccounts"); responseDocument.Included[0].Id.Should().Be(existingUserAccount.StringId); responseDocument.Included[0].Attributes.ShouldContainKey("firstName").With(value => value.Should().Be(existingUserAccount.FirstName)); responseDocument.Included[0].Attributes.ShouldContainKey("lastName").With(value => value.Should().Be(existingUserAccount.LastName)); responseDocument.Included[0].Relationships.ShouldNotBeEmpty(); int newWorkItemId = int.Parse(responseDocument.Data.SingleValue.Id.ShouldNotBeNull()); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Assignee).FirstWithIdAsync(newWorkItemId); workItemInDatabase.Description.Should().Be(newWorkItem.Description); workItemInDatabase.Priority.Should().Be(newWorkItem.Priority); workItemInDatabase.Assignee.ShouldNotBeNull(); workItemInDatabase.Assignee.Id.Should().Be(existingUserAccount.Id); }); } [Fact] public async Task Cannot_create_with_null_relationship() { // Arrange UserAccount existingUserAccount = _fakers.UserAccount.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.UserAccounts.Add(existingUserAccount); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", relationships = new { assignee = (object?)null } } }; const string route = "/workItems"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Expected an object, instead of 'null'."); error.Detail.Should().BeNull(); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/data/relationships/assignee"); error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty()); } [Fact] public async Task Cannot_create_with_missing_data_in_relationship() { // Arrange UserAccount existingUserAccount = _fakers.UserAccount.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.UserAccounts.Add(existingUserAccount); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", relationships = new { assignee = new { } } } }; const string route = "/workItems"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: The 'data' element is required."); error.Detail.Should().BeNull(); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/data/relationships/assignee"); error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty()); } [Fact] public async Task Cannot_create_with_array_data_in_relationship() { // Arrange UserAccount existingUserAccount = _fakers.UserAccount.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.UserAccounts.Add(existingUserAccount); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", relationships = new { assignee = new { data = new[] { new { type = "userAccounts", id = existingUserAccount.StringId } } } } } }; const string route = "/workItems"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Expected an object or 'null', instead of an array."); error.Detail.Should().BeNull(); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/data/relationships/assignee/data"); error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty()); } [Fact] public async Task Cannot_create_for_missing_relationship_type() { // Arrange var requestBody = new { data = new { type = "workItems", relationships = new { assignee = new { data = new { id = Unknown.StringId.For<UserAccount, long>() } } } } }; const string route = "/workItems"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: The 'type' element is required."); error.Detail.Should().BeNull(); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/data/relationships/assignee/data"); error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty()); } [Fact] public async Task Cannot_create_for_unknown_relationship_type() { // Arrange var requestBody = new { data = new { type = "workItems", relationships = new { assignee = new { data = new { type = Unknown.ResourceType, id = Unknown.StringId.For<UserAccount, long>() } } } } }; const string route = "/workItems"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Unknown resource type found."); error.Detail.Should().Be($"Resource type '{Unknown.ResourceType}' does not exist."); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/data/relationships/assignee/data/type"); error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty()); } [Fact] public async Task Cannot_create_for_missing_relationship_ID() { // Arrange var requestBody = new { data = new { type = "workItems", relationships = new { assignee = new { data = new { type = "userAccounts" } } } } }; const string route = "/workItems"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: The 'id' element is required."); error.Detail.Should().BeNull(); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/data/relationships/assignee/data"); error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty()); } [Fact] public async Task Cannot_create_with_unknown_relationship_ID() { // Arrange string userAccountId = Unknown.StringId.For<UserAccount, long>(); var requestBody = new { data = new { type = "workItems", relationships = new { assignee = new { data = new { type = "userAccounts", id = userAccountId } } } } }; const string route = "/workItems"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("A related resource does not exist."); error.Detail.Should().Be($"Related resource of type 'userAccounts' with ID '{userAccountId}' in relationship 'assignee' does not exist."); error.Source.Should().BeNull(); error.Meta.Should().NotContainKey("requestBody"); } [Fact] public async Task Cannot_create_on_relationship_type_mismatch() { // Arrange var requestBody = new { data = new { type = "workItems", relationships = new { assignee = new { data = new { type = "rgbColors", id = "0A0B0C" } } } } }; const string route = "/workItems"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Conflict); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.Conflict); error.Title.Should().Be("Failed to deserialize request body: Incompatible resource type found."); error.Detail.Should().Be("Type 'rgbColors' is incompatible with type 'userAccounts' of relationship 'assignee'."); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/data/relationships/assignee/data/type"); error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty()); } [Fact] public async Task Can_create_resource_with_duplicate_relationship() { // Arrange List<UserAccount> existingUserAccounts = _fakers.UserAccount.Generate(2); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.UserAccounts.AddRange(existingUserAccounts); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", relationships = new { assignee = new { data = new { type = "userAccounts", id = existingUserAccounts[0].StringId } }, assignee_duplicate = new { data = new { type = "userAccounts", id = existingUserAccounts[1].StringId } } } } }; string requestBodyText = JsonSerializer.Serialize(requestBody).Replace("assignee_duplicate", "assignee"); const string route = "/workItems?include=assignee"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBodyText); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Data.SingleValue.ShouldNotBeNull(); responseDocument.Data.SingleValue.Attributes.ShouldNotBeEmpty(); responseDocument.Data.SingleValue.Relationships.ShouldNotBeEmpty(); responseDocument.Included.ShouldHaveCount(1); responseDocument.Included[0].Type.Should().Be("userAccounts"); responseDocument.Included[0].Id.Should().Be(existingUserAccounts[1].StringId); responseDocument.Included[0].Attributes.ShouldContainKey("firstName").With(value => value.Should().Be(existingUserAccounts[1].FirstName)); responseDocument.Included[0].Attributes.ShouldContainKey("lastName").With(value => value.Should().Be(existingUserAccounts[1].LastName)); responseDocument.Included[0].Relationships.ShouldNotBeEmpty(); int newWorkItemId = int.Parse(responseDocument.Data.SingleValue.Id.ShouldNotBeNull()); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Assignee).FirstWithIdAsync(newWorkItemId); workItemInDatabase.Assignee.ShouldNotBeNull(); workItemInDatabase.Assignee.Id.Should().Be(existingUserAccounts[1].Id); }); } [Fact] public async Task Cannot_create_resource_with_local_ID() { // Arrange const string workItemLocalId = "wo-1"; var requestBody = new { data = new { type = "workItems", lid = workItemLocalId, relationships = new { parent = new { data = new { type = "workItems", lid = workItemLocalId } } } } }; const string route = "/workItems"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: The 'lid' element is not supported at this endpoint."); error.Detail.Should().BeNull(); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/data/lid"); error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty()); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; using System.Net.Http.WinHttpHandlerUnitTests; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; internal static partial class Interop { internal static partial class Crypt32 { public static bool CertFreeCertificateContext(IntPtr certContext) { return true; } public static bool CertVerifyCertificateChainPolicy( IntPtr pszPolicyOID, SafeX509ChainHandle pChainContext, ref CERT_CHAIN_POLICY_PARA pPolicyPara, ref CERT_CHAIN_POLICY_STATUS pPolicyStatus) { return true; } } internal static partial class mincore { public static string GetMessage(IntPtr moduleName, int error) { string messageFormat = "Fake error message, error code: {0}"; return string.Format(messageFormat, error); } public static IntPtr GetModuleHandle(string moduleName) { return IntPtr.Zero; } } internal static partial class WinHttp { public static SafeWinHttpHandle WinHttpOpen( IntPtr userAgent, uint accessType, string proxyName, string proxyBypass, uint flags) { if (TestControl.WinHttpOpen.ErrorWithApiCall) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INVALID_HANDLE; return new FakeSafeWinHttpHandle(false); } if (accessType == Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY && !TestControl.WinHttpAutomaticProxySupport) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INVALID_PARAMETER; return new FakeSafeWinHttpHandle(false); } APICallHistory.ProxyInfo proxyInfo; proxyInfo.AccessType = accessType; proxyInfo.Proxy = proxyName; proxyInfo.ProxyBypass = proxyBypass; APICallHistory.SessionProxySettings = proxyInfo; return new FakeSafeWinHttpHandle(true); } public static bool WinHttpCloseHandle(IntPtr sessionHandle) { Marshal.FreeHGlobal(sessionHandle); return true; } public static SafeWinHttpHandle WinHttpConnect( SafeWinHttpHandle sessionHandle, string serverName, ushort serverPort, uint reserved) { return new FakeSafeWinHttpHandle(true); } public static bool WinHttpAddRequestHeaders( SafeWinHttpHandle requestHandle, StringBuilder headers, uint headersLength, uint modifiers) { return true; } public static bool WinHttpAddRequestHeaders( SafeWinHttpHandle requestHandle, string headers, uint headersLength, uint modifiers) { return true; } public static SafeWinHttpHandle WinHttpOpenRequest( SafeWinHttpHandle connectHandle, string verb, string objectName, string version, string referrer, string acceptTypes, uint flags) { return new FakeSafeWinHttpHandle(true); } public static bool WinHttpSendRequest( SafeWinHttpHandle requestHandle, StringBuilder headers, uint headersLength, IntPtr optional, uint optionalLength, uint totalLength, IntPtr context) { Task.Run(() => { var fakeHandle = (FakeSafeWinHttpHandle)requestHandle; fakeHandle.Context = context; fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE, IntPtr.Zero, 0); }); return true; } public static bool WinHttpReceiveResponse(SafeWinHttpHandle requestHandle, IntPtr reserved) { Task.Run(() => { var fakeHandle = (FakeSafeWinHttpHandle)requestHandle; bool aborted = !fakeHandle.DelayOperation(TestControl.WinHttpReceiveResponse.Delay); if (aborted || TestControl.WinHttpReadData.ErrorOnCompletion) { Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult; asyncResult.dwResult = new IntPtr((int)Interop.WinHttp.API_RECEIVE_RESPONSE); asyncResult.dwError = aborted ? Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED : Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR; TestControl.WinHttpReadData.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, asyncResult); } else { TestControl.WinHttpReceiveResponse.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE, IntPtr.Zero, 0); } }); return true; } public static bool WinHttpQueryDataAvailable(SafeWinHttpHandle requestHandle, out uint bytesAvailable) { bytesAvailable = 0; return true; } public static bool WinHttpReadData( SafeWinHttpHandle requestHandle, IntPtr buffer, uint bufferSize, IntPtr bytesReadShouldBeNullForAsync) { if (bytesReadShouldBeNullForAsync != IntPtr.Zero) { return false; } if (TestControl.WinHttpReadData.ErrorWithApiCall) { return false; } uint bytesRead; TestServer.ReadFromResponseBody(buffer, bufferSize, out bytesRead); Task.Run(() => { var fakeHandle = (FakeSafeWinHttpHandle)requestHandle; bool aborted = !fakeHandle.DelayOperation(TestControl.WinHttpReadData.Delay); if (aborted || TestControl.WinHttpReadData.ErrorOnCompletion) { Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult; asyncResult.dwResult = new IntPtr((int)Interop.WinHttp.API_READ_DATA); asyncResult.dwError = aborted ? Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED : Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR; TestControl.WinHttpReadData.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, asyncResult); } else { TestControl.WinHttpReadData.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_READ_COMPLETE, buffer, bytesRead); } }); return true; } public static bool WinHttpQueryHeaders( SafeWinHttpHandle requestHandle, uint infoLevel, string name, StringBuilder buffer, ref uint bufferLength, IntPtr index) { string httpVersion = "HTTP/1.1"; string statusText = "OK"; if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_VERSION) { if (buffer == null) { bufferLength = ((uint)httpVersion.Length + 1) * 2; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER; return false; } buffer.Append(httpVersion); return true; } if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_STATUS_TEXT) { if (buffer == null) { bufferLength = ((uint)statusText.Length + 1) * 2; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER; return false; } buffer.Append(statusText); return true; } if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_CONTENT_ENCODING) { string compression = null; if (TestServer.ResponseHeaders.Contains("Content-Encoding: deflate")) { compression = "deflate"; } else if (TestServer.ResponseHeaders.Contains("Content-Encoding: gzip")) { compression = "gzip"; } if (compression == null) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND; return false; } if (buffer == null) { bufferLength = ((uint)compression.Length + 1) * 2; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER; return false; } buffer.Append(compression); return true; } if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_RAW_HEADERS_CRLF) { if (buffer == null) { bufferLength = ((uint)TestServer.ResponseHeaders.Length + 1) * 2; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER; return false; } buffer.Append(TestServer.ResponseHeaders); return true; } return false; } public static bool WinHttpQueryHeaders( SafeWinHttpHandle requestHandle, uint infoLevel, string name, ref uint number, ref uint bufferLength, IntPtr index) { infoLevel &= ~Interop.WinHttp.WINHTTP_QUERY_FLAG_NUMBER; if (infoLevel == Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE) { number = (uint)HttpStatusCode.OK; return true; } return false; } public static bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, StringBuilder buffer, ref uint bufferSize) { string uri = "http://www.contoso.com/"; if (option == Interop.WinHttp.WINHTTP_OPTION_URL) { if (buffer == null) { bufferSize = ((uint)uri.Length + 1) * 2; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER; return false; } buffer.Append(uri); return true; } return false; } public static bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, ref IntPtr buffer, ref uint bufferSize) { return true; } public static bool WinHttpQueryOption( SafeWinHttpHandle handle, uint option, IntPtr buffer, ref uint bufferSize) { return true; } public static bool WinHttpWriteData( SafeWinHttpHandle requestHandle, IntPtr buffer, uint bufferSize, IntPtr bytesWrittenShouldBeNullForAsync) { if (bytesWrittenShouldBeNullForAsync != IntPtr.Zero) { return false; } if (TestControl.WinHttpWriteData.ErrorWithApiCall) { return false; } uint bytesWritten; TestServer.WriteToRequestBody(buffer, bufferSize); bytesWritten = bufferSize; Task.Run(() => { var fakeHandle = (FakeSafeWinHttpHandle)requestHandle; bool aborted = !fakeHandle.DelayOperation(TestControl.WinHttpWriteData.Delay); if (aborted || TestControl.WinHttpWriteData.ErrorOnCompletion) { Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult; asyncResult.dwResult = new IntPtr((int)Interop.WinHttp.API_WRITE_DATA); asyncResult.dwError = Interop.WinHttp.ERROR_WINHTTP_CONNECTION_ERROR; TestControl.WinHttpWriteData.Wait(); fakeHandle.InvokeCallback(aborted ? Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED : Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, asyncResult); } else { TestControl.WinHttpWriteData.Wait(); fakeHandle.InvokeCallback(Interop.WinHttp.WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE, IntPtr.Zero, 0); } }); return true; } public static bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, ref uint optionData, uint optionLength = sizeof(uint)) { if (option == Interop.WinHttp.WINHTTP_OPTION_DECOMPRESSION & !TestControl.WinHttpDecompressionSupport) { TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION; return false; } if (option == Interop.WinHttp.WINHTTP_OPTION_DISABLE_FEATURE && optionData == Interop.WinHttp.WINHTTP_DISABLE_COOKIES) { APICallHistory.WinHttpOptionDisableCookies = true; } else if (option == Interop.WinHttp.WINHTTP_OPTION_ENABLE_FEATURE && optionData == Interop.WinHttp.WINHTTP_ENABLE_SSL_REVOCATION) { APICallHistory.WinHttpOptionEnableSslRevocation = true; } else if (option == Interop.WinHttp.WINHTTP_OPTION_SECURE_PROTOCOLS) { APICallHistory.WinHttpOptionSecureProtocols = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_SECURITY_FLAGS) { APICallHistory.WinHttpOptionSecurityFlags = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS) { APICallHistory.WinHttpOptionMaxHttpAutomaticRedirects = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY) { APICallHistory.WinHttpOptionRedirectPolicy = optionData; } return true; } public static bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, string optionData, uint optionLength) { if (option == Interop.WinHttp.WINHTTP_OPTION_PROXY_USERNAME) { APICallHistory.ProxyUsernameWithDomain = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_PROXY_PASSWORD) { APICallHistory.ProxyPassword = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_USERNAME) { APICallHistory.ServerUsernameWithDomain = optionData; } else if (option == Interop.WinHttp.WINHTTP_OPTION_PASSWORD) { APICallHistory.ServerPassword = optionData; } return true; } public static bool WinHttpSetOption( SafeWinHttpHandle handle, uint option, IntPtr optionData, uint optionLength) { if (option == Interop.WinHttp.WINHTTP_OPTION_PROXY) { var proxyInfo = Marshal.PtrToStructure<Interop.WinHttp.WINHTTP_PROXY_INFO>(optionData); var proxyInfoHistory = new APICallHistory.ProxyInfo(); proxyInfoHistory.AccessType = proxyInfo.AccessType; proxyInfoHistory.Proxy = Marshal.PtrToStringUni(proxyInfo.Proxy); proxyInfoHistory.ProxyBypass = Marshal.PtrToStringUni(proxyInfo.ProxyBypass); APICallHistory.RequestProxySettings = proxyInfoHistory; } else if (option == Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT) { APICallHistory.WinHttpOptionClientCertContext.Add(optionData); } return true; } public static bool WinHttpSetCredentials( SafeWinHttpHandle requestHandle, uint authTargets, uint authScheme, string userName, string password, IntPtr reserved) { return true; } public static bool WinHttpQueryAuthSchemes( SafeWinHttpHandle requestHandle, out uint supportedSchemes, out uint firstScheme, out uint authTarget) { supportedSchemes = 0; firstScheme = 0; authTarget = 0; return true; } public static bool WinHttpSetTimeouts( SafeWinHttpHandle handle, int resolveTimeout, int connectTimeout, int sendTimeout, int receiveTimeout) { return true; } public static bool WinHttpGetIEProxyConfigForCurrentUser( out Interop.WinHttp.WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxyConfig) { if (FakeRegistry.WinInetProxySettings.RegistryKeyMissing) { proxyConfig.AutoDetect = false; proxyConfig.AutoConfigUrl = IntPtr.Zero; proxyConfig.Proxy = IntPtr.Zero; proxyConfig.ProxyBypass = IntPtr.Zero; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_FILE_NOT_FOUND; return false; } proxyConfig.AutoDetect = FakeRegistry.WinInetProxySettings.AutoDetect; proxyConfig.AutoConfigUrl = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.AutoConfigUrl); proxyConfig.Proxy = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.Proxy); proxyConfig.ProxyBypass = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.ProxyBypass); return true; } public static bool WinHttpGetProxyForUrl( SafeWinHttpHandle sessionHandle, string url, ref Interop.WinHttp.WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions, out Interop.WinHttp.WINHTTP_PROXY_INFO proxyInfo) { if (TestControl.PACFileNotDetectedOnNetwork) { proxyInfo.AccessType = WINHTTP_ACCESS_TYPE_NO_PROXY; proxyInfo.Proxy = IntPtr.Zero; proxyInfo.ProxyBypass = IntPtr.Zero; TestControl.LastWin32Error = (int)Interop.WinHttp.ERROR_WINHTTP_AUTODETECTION_FAILED; return false; } proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY; proxyInfo.Proxy = Marshal.StringToHGlobalUni(FakeRegistry.WinInetProxySettings.Proxy); proxyInfo.ProxyBypass = IntPtr.Zero; return true; } public static IntPtr WinHttpSetStatusCallback( SafeWinHttpHandle handle, Interop.WinHttp.WINHTTP_STATUS_CALLBACK callback, uint notificationFlags, IntPtr reserved) { if (handle == null) { throw new ArgumentNullException("handle"); } var fakeHandle = (FakeSafeWinHttpHandle)handle; fakeHandle.Callback = callback; return IntPtr.Zero; } } }
/* * * (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. * */ #region usings using System; using System.Collections; using System.Globalization; using System.Runtime.Serialization; using System.Text; #endregion namespace ASC.Notify.Cron { [Serializable] public class CronExpression : ICloneable, IDeserializationCallback { protected const int Second = 0; protected const int Minute = 1; protected const int Hour = 2; protected const int DayOfMonth = 3; protected const int Month = 4; protected const int DayOfWeek = 5; protected const int Year = 6; protected const int AllSpecInt = 99; protected const int NoSpecInt = 98; protected const int AllSpec = AllSpecInt; protected const int NoSpec = NoSpecInt; private static readonly Hashtable monthMap = new Hashtable(20); private static readonly Hashtable dayMap = new Hashtable(60); private readonly string cronExpressionString; [NonSerialized] protected bool calendardayOfMonth; [NonSerialized] protected bool calendardayOfWeek; [NonSerialized] protected TreeSet daysOfMonth; [NonSerialized] protected TreeSet daysOfWeek; [NonSerialized] protected bool expressionParsed; [NonSerialized] protected TreeSet hours; [NonSerialized] protected bool lastdayOfMonth; [NonSerialized] protected bool lastdayOfWeek; [NonSerialized] protected TreeSet minutes; [NonSerialized] protected TreeSet months; [NonSerialized] protected bool nearestWeekday; [NonSerialized] protected int nthdayOfWeek; [NonSerialized] protected TreeSet seconds; private TimeZoneInfo timeZone; [NonSerialized] protected TreeSet years; static CronExpression() { monthMap.Add("JAN", 0); monthMap.Add("FEB", 1); monthMap.Add("MAR", 2); monthMap.Add("APR", 3); monthMap.Add("MAY", 4); monthMap.Add("JUN", 5); monthMap.Add("JUL", 6); monthMap.Add("AUG", 7); monthMap.Add("SEP", 8); monthMap.Add("OCT", 9); monthMap.Add("NOV", 10); monthMap.Add("DEC", 11); dayMap.Add("SUN", 1); dayMap.Add("MON", 2); dayMap.Add("TUE", 3); dayMap.Add("WED", 4); dayMap.Add("THU", 5); dayMap.Add("FRI", 6); dayMap.Add("SAT", 7); } public CronExpression(string cronExpression) { if (cronExpression == null) { throw new ArgumentException("cronExpression cannot be null"); } cronExpressionString = cronExpression.ToUpper(CultureInfo.InvariantCulture); BuildExpression(cronExpression); } public virtual TimeZoneInfo TimeZone { set { timeZone = value; } get { if (timeZone == null) { timeZone = TimeZoneInfo.Utc; } return timeZone; } } public string CronExpressionString { get { return cronExpressionString; } } public TimeSpan? Period() { var date = new DateTime(2014, 1, 1); DateTime.SpecifyKind(date, DateTimeKind.Utc); var after = GetTimeAfter(date); if (!after.HasValue) return null; return after.Value.Subtract(date); } #region ICloneable Members public object Clone() { CronExpression copy; try { copy = new CronExpression(CronExpressionString); copy.TimeZone = TimeZone; } catch (FormatException) { throw new Exception("Not Cloneable."); } return copy; } #endregion #region IDeserializationCallback Members public void OnDeserialization(object sender) { BuildExpression(cronExpressionString); } #endregion public virtual bool IsSatisfiedBy(DateTime dateUtc) { DateTime test = new DateTime(dateUtc.Year, dateUtc.Month, dateUtc.Day, dateUtc.Hour, dateUtc.Minute, dateUtc.Second). AddSeconds(-1); DateTime? timeAfter = GetTimeAfter(test); if (timeAfter.HasValue && timeAfter.Value.Equals(dateUtc)) { return true; } else { return false; } } public virtual DateTime? GetNextValidTimeAfter(DateTime date) { return GetTimeAfter(date); } public virtual DateTime? GetNextInvalidTimeAfter(DateTime date) { long difference = 1000; DateTime lastDate = new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second).AddSeconds(-1); while (difference == 1000) { DateTime newDate = GetTimeAfter(lastDate).Value; difference = (long)(newDate - lastDate).TotalMilliseconds; if (difference == 1000) { lastDate = newDate; } } return lastDate.AddSeconds(1); } public override string ToString() { return cronExpressionString; } public static bool IsValidExpression(string cronExpression) { try { new CronExpression(cronExpression); } catch (FormatException) { return false; } return true; } protected void BuildExpression(string expression) { expressionParsed = true; try { if (seconds == null) { seconds = new TreeSet(); } if (minutes == null) { minutes = new TreeSet(); } if (hours == null) { hours = new TreeSet(); } if (daysOfMonth == null) { daysOfMonth = new TreeSet(); } if (months == null) { months = new TreeSet(); } if (daysOfWeek == null) { daysOfWeek = new TreeSet(); } if (years == null) { years = new TreeSet(); } int exprOn = Second; #if NET_20 string[] exprsTok = expression.Trim().Split(new char[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); #else string[] exprsTok = expression.Trim().Split(new[] { ' ', '\t', '\r', '\n' }); #endif foreach (string exprTok in exprsTok) { string expr = exprTok.Trim(); if (expr.Length == 0) { continue; } if (exprOn > Year) { break; } if (exprOn == DayOfMonth && expr.IndexOf('L') != -1 && expr.Length > 1 && expr.IndexOf(",") >= 0) { throw new FormatException( "Support for specifying 'L' and 'LW' with other days of the month is not implemented"); } if (exprOn == DayOfWeek && expr.IndexOf('L') != -1 && expr.Length > 1 && expr.IndexOf(",") >= 0) { throw new FormatException( "Support for specifying 'L' with other days of the week is not implemented"); } string[] vTok = expr.Split(','); foreach (string v in vTok) { StoreExpressionVals(0, v, exprOn); } exprOn++; } if (exprOn <= DayOfWeek) { throw new FormatException("Unexpected end of expression."); } if (exprOn <= Year) { StoreExpressionVals(0, "*", Year); } TreeSet dow = GetSet(DayOfWeek); TreeSet dom = GetSet(DayOfMonth); bool dayOfMSpec = !dom.Contains(NoSpec); bool dayOfWSpec = !dow.Contains(NoSpec); if (dayOfMSpec && !dayOfWSpec) { } else if (dayOfWSpec && !dayOfMSpec) { } else { throw new FormatException( "Support for specifying both a day-of-week AND a day-of-month parameter is not implemented."); } } catch (FormatException) { throw; } catch (Exception e) { throw new FormatException(string.Format(CultureInfo.InvariantCulture, "Illegal cron expression format ({0})", e)); } } protected virtual int StoreExpressionVals(int pos, string s, int type) { int incr = 0; int i = SkipWhiteSpace(pos, s); if (i >= s.Length) { return i; } char c = s[i]; if ((c >= 'A') && (c <= 'Z') && (!s.Equals("L")) && (!s.Equals("LW"))) { String sub = s.Substring(i, 3); int sval; int eval = -1; if (type == Month) { sval = GetMonthNumber(sub) + 1; if (sval <= 0) { throw new FormatException(string.Format(CultureInfo.InvariantCulture, "Invalid Month value: '{0}'", sub)); } if (s.Length > i + 3) { c = s[i + 3]; if (c == '-') { i += 4; sub = s.Substring(i, 3); eval = GetMonthNumber(sub) + 1; if (eval <= 0) { throw new FormatException( string.Format(CultureInfo.InvariantCulture, "Invalid Month value: '{0}'", sub)); } } } } else if (type == DayOfWeek) { sval = GetDayOfWeekNumber(sub); if (sval < 0) { throw new FormatException(string.Format(CultureInfo.InvariantCulture, "Invalid Day-of-Week value: '{0}'", sub)); } if (s.Length > i + 3) { c = s[i + 3]; if (c == '-') { i += 4; sub = s.Substring(i, 3); eval = GetDayOfWeekNumber(sub); if (eval < 0) { throw new FormatException( string.Format(CultureInfo.InvariantCulture, "Invalid Day-of-Week value: '{0}'", sub)); } } else if (c == '#') { try { i += 4; nthdayOfWeek = Convert.ToInt32(s.Substring(i), CultureInfo.InvariantCulture); if (nthdayOfWeek < 1 || nthdayOfWeek > 5) { throw new Exception(); } } catch (Exception) { throw new FormatException( "A numeric value between 1 and 5 must follow the '#' option"); } } else if (c == 'L') { lastdayOfWeek = true; i++; } } } else { throw new FormatException( string.Format(CultureInfo.InvariantCulture, "Illegal characters for this position: '{0}'", sub)); } if (eval != -1) { incr = 1; } AddToSet(sval, eval, incr, type); return (i + 3); } if (c == '?') { i++; if ((i + 1) < s.Length && (s[i] != ' ' && s[i + 1] != '\t')) { throw new FormatException("Illegal character after '?': " + s[i]); } if (type != DayOfWeek && type != DayOfMonth) { throw new FormatException( "'?' can only be specified for Day-of-Month or Day-of-Week."); } if (type == DayOfWeek && !lastdayOfMonth) { var val = (int)daysOfMonth[daysOfMonth.Count - 1]; if (val == NoSpecInt) { throw new FormatException( "'?' can only be specified for Day-of-Month -OR- Day-of-Week."); } } AddToSet(NoSpecInt, -1, 0, type); return i; } if (c == '*' || c == '/') { if (c == '*' && (i + 1) >= s.Length) { AddToSet(AllSpecInt, -1, incr, type); return i + 1; } else if (c == '/' && ((i + 1) >= s.Length || s[i + 1] == ' ' || s[i + 1] == '\t')) { throw new FormatException("'/' must be followed by an integer."); } else if (c == '*') { i++; } c = s[i]; if (c == '/') { i++; if (i >= s.Length) { throw new FormatException("Unexpected end of string."); } incr = GetNumericValue(s, i); i++; if (incr > 10) { i++; } if (incr > 59 && (type == Second || type == Minute)) { throw new FormatException( string.Format(CultureInfo.InvariantCulture, "Increment > 60 : {0}", incr)); } else if (incr > 23 && (type == Hour)) { throw new FormatException( string.Format(CultureInfo.InvariantCulture, "Increment > 24 : {0}", incr)); } else if (incr > 31 && (type == DayOfMonth)) { throw new FormatException( string.Format(CultureInfo.InvariantCulture, "Increment > 31 : {0}", incr)); } else if (incr > 7 && (type == DayOfWeek)) { throw new FormatException( string.Format(CultureInfo.InvariantCulture, "Increment > 7 : {0}", incr)); } else if (incr > 12 && (type == Month)) { throw new FormatException(string.Format(CultureInfo.InvariantCulture, "Increment > 12 : {0}", incr)); } } else { incr = 1; } AddToSet(AllSpecInt, -1, incr, type); return i; } else if (c == 'L') { i++; if (type == DayOfMonth) { lastdayOfMonth = true; } if (type == DayOfWeek) { AddToSet(7, 7, 0, type); } if (type == DayOfMonth && s.Length > i) { c = s[i]; if (c == 'W') { nearestWeekday = true; i++; } } return i; } else if (c >= '0' && c <= '9') { int val = Convert.ToInt32(c.ToString(), CultureInfo.InvariantCulture); i++; if (i >= s.Length) { AddToSet(val, -1, -1, type); } else { c = s[i]; if (c >= '0' && c <= '9') { ValueSet vs = GetValue(val, s, i); val = vs.theValue; i = vs.pos; } i = CheckNext(i, s, val, type); return i; } } else { throw new FormatException(string.Format(CultureInfo.InvariantCulture, "Unexpected character: {0}", c)); } return i; } protected virtual int CheckNext(int pos, string s, int val, int type) { int end = -1; int i = pos; if (i >= s.Length) { AddToSet(val, end, -1, type); return i; } char c = s[pos]; if (c == 'L') { if (type == DayOfWeek) { lastdayOfWeek = true; } else { throw new FormatException(string.Format(CultureInfo.InvariantCulture, "'L' option is not valid here. (pos={0})", i)); } TreeSet data = GetSet(type); data.Add(val); i++; return i; } if (c == 'W') { if (type == DayOfMonth) { nearestWeekday = true; } else { throw new FormatException(string.Format(CultureInfo.InvariantCulture, "'W' option is not valid here. (pos={0})", i)); } TreeSet data = GetSet(type); data.Add(val); i++; return i; } if (c == '#') { if (type != DayOfWeek) { throw new FormatException( string.Format(CultureInfo.InvariantCulture, "'#' option is not valid here. (pos={0})", i)); } i++; try { nthdayOfWeek = Convert.ToInt32(s.Substring(i), CultureInfo.InvariantCulture); if (nthdayOfWeek < 1 || nthdayOfWeek > 5) { throw new Exception(); } } catch (Exception) { throw new FormatException( "A numeric value between 1 and 5 must follow the '#' option"); } TreeSet data = GetSet(type); data.Add(val); i++; return i; } if (c == 'C') { if (type == DayOfWeek) { calendardayOfWeek = true; } else if (type == DayOfMonth) { calendardayOfMonth = true; } else { throw new FormatException(string.Format(CultureInfo.InvariantCulture, "'C' option is not valid here. (pos={0})", i)); } TreeSet data = GetSet(type); data.Add(val); i++; return i; } if (c == '-') { i++; c = s[i]; int v = Convert.ToInt32(c.ToString(), CultureInfo.InvariantCulture); end = v; i++; if (i >= s.Length) { AddToSet(val, end, 1, type); return i; } c = s[i]; if (c >= '0' && c <= '9') { ValueSet vs = GetValue(v, s, i); int v1 = vs.theValue; end = v1; i = vs.pos; } if (i < s.Length && ((c = s[i]) == '/')) { i++; c = s[i]; int v2 = Convert.ToInt32(c.ToString(), CultureInfo.InvariantCulture); i++; if (i >= s.Length) { AddToSet(val, end, v2, type); return i; } c = s[i]; if (c >= '0' && c <= '9') { ValueSet vs = GetValue(v2, s, i); int v3 = vs.theValue; AddToSet(val, end, v3, type); i = vs.pos; return i; } else { AddToSet(val, end, v2, type); return i; } } else { AddToSet(val, end, 1, type); return i; } } if (c == '/') { i++; c = s[i]; int v2 = Convert.ToInt32(c.ToString(), CultureInfo.InvariantCulture); i++; if (i >= s.Length) { AddToSet(val, end, v2, type); return i; } c = s[i]; if (c >= '0' && c <= '9') { ValueSet vs = GetValue(v2, s, i); int v3 = vs.theValue; AddToSet(val, end, v3, type); i = vs.pos; return i; } else { throw new FormatException(string.Format(CultureInfo.InvariantCulture, "Unexpected character '{0}' after '/'", c)); } } AddToSet(val, end, 0, type); i++; return i; } public virtual string GetExpressionSummary() { var buf = new StringBuilder(); buf.Append("seconds: "); buf.Append(GetExpressionSetSummary(seconds)); buf.Append("\n"); buf.Append("minutes: "); buf.Append(GetExpressionSetSummary(minutes)); buf.Append("\n"); buf.Append("hours: "); buf.Append(GetExpressionSetSummary(hours)); buf.Append("\n"); buf.Append("daysOfMonth: "); buf.Append(GetExpressionSetSummary(daysOfMonth)); buf.Append("\n"); buf.Append("months: "); buf.Append(GetExpressionSetSummary(months)); buf.Append("\n"); buf.Append("daysOfWeek: "); buf.Append(GetExpressionSetSummary(daysOfWeek)); buf.Append("\n"); buf.Append("lastdayOfWeek: "); buf.Append(lastdayOfWeek); buf.Append("\n"); buf.Append("nearestWeekday: "); buf.Append(nearestWeekday); buf.Append("\n"); buf.Append("NthDayOfWeek: "); buf.Append(nthdayOfWeek); buf.Append("\n"); buf.Append("lastdayOfMonth: "); buf.Append(lastdayOfMonth); buf.Append("\n"); buf.Append("calendardayOfWeek: "); buf.Append(calendardayOfWeek); buf.Append("\n"); buf.Append("calendardayOfMonth: "); buf.Append(calendardayOfMonth); buf.Append("\n"); buf.Append("years: "); buf.Append(GetExpressionSetSummary(years)); buf.Append("\n"); return buf.ToString(); } protected virtual string GetExpressionSetSummary(ISet data) { if (data.Contains(NoSpec)) { return "?"; } if (data.Contains(AllSpec)) { return "*"; } var buf = new StringBuilder(); bool first = true; foreach (int iVal in data) { string val = iVal.ToString(CultureInfo.InvariantCulture); if (!first) { buf.Append(","); } buf.Append(val); first = false; } return buf.ToString(); } protected virtual int SkipWhiteSpace(int i, string s) { for (; i < s.Length && (s[i] == ' ' || s[i] == '\t'); i++) { ; } return i; } protected virtual int FindNextWhiteSpace(int i, string s) { for (; i < s.Length && (s[i] != ' ' || s[i] != '\t'); i++) { ; } return i; } protected virtual void AddToSet(int val, int end, int incr, int type) { TreeSet data = GetSet(type); if (type == Second || type == Minute) { if ((val < 0 || val > 59 || end > 59) && (val != AllSpecInt)) { throw new FormatException( "Minute and Second values must be between 0 and 59"); } } else if (type == Hour) { if ((val < 0 || val > 23 || end > 23) && (val != AllSpecInt)) { throw new FormatException( "Hour values must be between 0 and 23"); } } else if (type == DayOfMonth) { if ((val < 1 || val > 31 || end > 31) && (val != AllSpecInt) && (val != NoSpecInt)) { throw new FormatException( "Day of month values must be between 1 and 31"); } } else if (type == Month) { if ((val < 1 || val > 12 || end > 12) && (val != AllSpecInt)) { throw new FormatException( "Month values must be between 1 and 12"); } } else if (type == DayOfWeek) { if ((val == 0 || val > 7 || end > 7) && (val != AllSpecInt) && (val != NoSpecInt)) { throw new FormatException( "Day-of-Week values must be between 1 and 7"); } } if ((incr == 0 || incr == -1) && val != AllSpecInt) { if (val != -1) { data.Add(val); } else { data.Add(NoSpec); } return; } int startAt = val; int stopAt = end; if (val == AllSpecInt && incr <= 0) { incr = 1; data.Add(AllSpec); } if (type == Second || type == Minute) { if (stopAt == -1) { stopAt = 59; } if (startAt == -1 || startAt == AllSpecInt) { startAt = 0; } } else if (type == Hour) { if (stopAt == -1) { stopAt = 23; } if (startAt == -1 || startAt == AllSpecInt) { startAt = 0; } } else if (type == DayOfMonth) { if (stopAt == -1) { stopAt = 31; } if (startAt == -1 || startAt == AllSpecInt) { startAt = 1; } } else if (type == Month) { if (stopAt == -1) { stopAt = 12; } if (startAt == -1 || startAt == AllSpecInt) { startAt = 1; } } else if (type == DayOfWeek) { if (stopAt == -1) { stopAt = 7; } if (startAt == -1 || startAt == AllSpecInt) { startAt = 1; } } else if (type == Year) { if (stopAt == -1) { stopAt = 2099; } if (startAt == -1 || startAt == AllSpecInt) { startAt = 1970; } } int max = -1; if (stopAt < startAt) { switch (type) { case Second: max = 60; break; case Minute: max = 60; break; case Hour: max = 24; break; case Month: max = 12; break; case DayOfWeek: max = 7; break; case DayOfMonth: max = 31; break; case Year: throw new ArgumentException("Start year must be less than stop year"); default: throw new ArgumentException("Unexpected type encountered"); } stopAt += max; } for (int i = startAt; i <= stopAt; i += incr) { if (max == -1) { data.Add(i); } else { int i2 = i % max; if (i2 == 0 && (type == Month || type == DayOfWeek || type == DayOfMonth)) { i2 = max; } data.Add(i2); } } } protected virtual TreeSet GetSet(int type) { switch (type) { case Second: return seconds; case Minute: return minutes; case Hour: return hours; case DayOfMonth: return daysOfMonth; case Month: return months; case DayOfWeek: return daysOfWeek; case Year: return years; default: return null; } } protected virtual ValueSet GetValue(int v, string s, int i) { char c = s[i]; string s1 = v.ToString(CultureInfo.InvariantCulture); while (c >= '0' && c <= '9') { s1 += c; i++; if (i >= s.Length) { break; } c = s[i]; } var val = new ValueSet(); if (i < s.Length) { val.pos = i; } else { val.pos = i + 1; } val.theValue = Convert.ToInt32(s1, CultureInfo.InvariantCulture); return val; } protected virtual int GetNumericValue(string s, int i) { int endOfVal = FindNextWhiteSpace(i, s); string val = s.Substring(i, endOfVal - i); return Convert.ToInt32(val, CultureInfo.InvariantCulture); } protected virtual int GetMonthNumber(string s) { if (monthMap.ContainsKey(s)) { return (int)monthMap[s]; } else { return -1; } } protected virtual int GetDayOfWeekNumber(string s) { if (dayMap.ContainsKey(s)) { return (int)dayMap[s]; } else { return -1; } } protected virtual DateTime? GetTime(int sc, int mn, int hr, int dayofmn, int mon) { try { if (sc == -1) { sc = 0; } if (mn == -1) { mn = 0; } if (hr == -1) { hr = 0; } if (dayofmn == -1) { dayofmn = 0; } if (mon == -1) { mon = 0; } return new DateTime(DateTime.UtcNow.Year, mon, dayofmn, hr, mn, sc); } catch (Exception) { return null; } } public virtual DateTime? GetTimeAfter(DateTime afterTimeUtc) { if (afterTimeUtc == DateTime.MaxValue) return null; afterTimeUtc = afterTimeUtc.AddSeconds(1); DateTime d = CreateDateTimeWithoutMillis(afterTimeUtc); d = TimeZoneInfo.ConvertTimeFromUtc(d, TimeZone); bool gotOne = false; while (!gotOne) { ISortedSet st; int t; int sec = d.Second; st = seconds.TailSet(sec); if (st != null && st.Count != 0) { sec = (int)st.First(); } else { sec = ((int)seconds.First()); d = d.AddMinutes(1); } d = new DateTime(d.Year, d.Month, d.Day, d.Hour, d.Minute, sec, d.Millisecond); int min = d.Minute; int hr = d.Hour; t = -1; st = minutes.TailSet(min); if (st != null && st.Count != 0) { t = min; min = ((int)st.First()); } else { min = (int)minutes.First(); hr++; } if (min != t) { d = new DateTime(d.Year, d.Month, d.Day, d.Hour, min, 0, d.Millisecond); d = SetCalendarHour(d, hr); continue; } d = new DateTime(d.Year, d.Month, d.Day, d.Hour, min, d.Second, d.Millisecond); hr = d.Hour; int day = d.Day; t = -1; st = hours.TailSet(hr); if (st != null && st.Count != 0) { t = hr; hr = (int)st.First(); } else { hr = (int)hours.First(); day++; } if (hr != t) { int daysInMonth = DateTime.DaysInMonth(d.Year, d.Month); if (day > daysInMonth) { d = new DateTime(d.Year, d.Month, daysInMonth, d.Hour, 0, 0, d.Millisecond).AddDays(day - daysInMonth); } else { d = new DateTime(d.Year, d.Month, day, d.Hour, 0, 0, d.Millisecond); } d = SetCalendarHour(d, hr); continue; } d = new DateTime(d.Year, d.Month, d.Day, hr, d.Minute, d.Second, d.Millisecond); day = d.Day; int mon = d.Month; t = -1; int tmon = mon; bool dayOfMSpec = !daysOfMonth.Contains(NoSpec); bool dayOfWSpec = !daysOfWeek.Contains(NoSpec); if (dayOfMSpec && !dayOfWSpec) { st = daysOfMonth.TailSet(day); if (lastdayOfMonth) { if (!nearestWeekday) { t = day; day = GetLastDayOfMonth(mon, d.Year); } else { t = day; day = GetLastDayOfMonth(mon, d.Year); var tcal = new DateTime(d.Year, mon, day, 0, 0, 0); int ldom = GetLastDayOfMonth(mon, d.Year); DayOfWeek dow = tcal.DayOfWeek; if (dow == System.DayOfWeek.Saturday && day == 1) { day += 2; } else if (dow == System.DayOfWeek.Saturday) { day -= 1; } else if (dow == System.DayOfWeek.Sunday && day == ldom) { day -= 2; } else if (dow == System.DayOfWeek.Sunday) { day += 1; } var nTime = new DateTime(tcal.Year, mon, day, hr, min, sec, d.Millisecond); if (nTime.ToUniversalTime() < afterTimeUtc) { day = 1; mon++; } } } else if (nearestWeekday) { t = day; day = (int)daysOfMonth.First(); var tcal = new DateTime(d.Year, mon, day, 0, 0, 0); int ldom = GetLastDayOfMonth(mon, d.Year); DayOfWeek dow = tcal.DayOfWeek; if (dow == System.DayOfWeek.Saturday && day == 1) { day += 2; } else if (dow == System.DayOfWeek.Saturday) { day -= 1; } else if (dow == System.DayOfWeek.Sunday && day == ldom) { day -= 2; } else if (dow == System.DayOfWeek.Sunday) { day += 1; } tcal = new DateTime(tcal.Year, mon, day, hr, min, sec); if (tcal.ToUniversalTime() < afterTimeUtc) { day = ((int)daysOfMonth.First()); mon++; } } else if (st != null && st.Count != 0) { t = day; day = (int)st.First(); int lastDay = GetLastDayOfMonth(mon, d.Year); if (day > lastDay) { day = (int)daysOfMonth.First(); mon++; } } else { day = ((int)daysOfMonth.First()); mon++; } if (day != t || mon != tmon) { if (mon > 12) { d = new DateTime(d.Year, 12, day, 0, 0, 0).AddMonths(mon - 12); } else { int lDay = DateTime.DaysInMonth(d.Year, mon); if (day <= lDay) { d = new DateTime(d.Year, mon, day, 0, 0, 0); } else { d = new DateTime(d.Year, mon, lDay, 0, 0, 0).AddDays(day - lDay); } } continue; } } else if (dayOfWSpec && !dayOfMSpec) { if (lastdayOfWeek) { var dow = ((int)daysOfWeek.First()); int cDow = ((int)d.DayOfWeek); int daysToAdd = 0; if (cDow < dow) { daysToAdd = dow - cDow; } if (cDow > dow) { daysToAdd = dow + (7 - cDow); } int lDay = GetLastDayOfMonth(mon, d.Year); if (day + daysToAdd > lDay) { if (mon == 12) { if (d.Year == DateTime.MaxValue.Year) return null; d = new DateTime(d.Year, mon - 11, 1, 0, 0, 0).AddYears(1); } else { d = new DateTime(d.Year, mon + 1, 1, 0, 0, 0); } continue; } while ((day + daysToAdd + 7) <= lDay) { daysToAdd += 7; } day += daysToAdd; if (daysToAdd > 0) { d = new DateTime(d.Year, mon, day, 0, 0, 0); continue; } } else if (nthdayOfWeek != 0) { var dow = ((int)daysOfWeek.First()); int cDow = ((int)d.DayOfWeek); int daysToAdd = 0; if (cDow < dow) { daysToAdd = dow - cDow; } else if (cDow > dow) { daysToAdd = dow + (7 - cDow); } bool dayShifted = false; if (daysToAdd > 0) { dayShifted = true; } day += daysToAdd; int weekOfMonth = day / 7; if (day % 7 > 0) { weekOfMonth++; } daysToAdd = (nthdayOfWeek - weekOfMonth) * 7; day += daysToAdd; if (daysToAdd < 0 || day > GetLastDayOfMonth(mon, d.Year)) { if (mon == 12) { if (d.Year == DateTime.MaxValue.Year) return null; d = new DateTime(d.Year, mon - 11, 1, 0, 0, 0).AddYears(1); } else { d = new DateTime(d.Year, mon + 1, 1, 0, 0, 0); } continue; } else if (daysToAdd > 0 || dayShifted) { d = new DateTime(d.Year, mon, day, 0, 0, 0); continue; } } else { int cDow = ((int)d.DayOfWeek) + 1; var dow = ((int)daysOfWeek.First()); st = daysOfWeek.TailSet(cDow); if (st != null && st.Count > 0) { dow = ((int)st.First()); } int daysToAdd = 0; if (cDow < dow) { daysToAdd = dow - cDow; } if (cDow > dow) { daysToAdd = dow + (7 - cDow); } int lDay = GetLastDayOfMonth(mon, d.Year); if (day + daysToAdd > lDay) { if (mon == 12) { if (d.Year == DateTime.MaxValue.Year) return null; d = new DateTime(d.Year, mon - 11, 1, 0, 0, 0).AddYears(1); } else { d = new DateTime(d.Year, mon + 1, 1, 0, 0, 0); } continue; } else if (daysToAdd > 0) { d = new DateTime(d.Year, mon, day + daysToAdd, 0, 0, 0); continue; } } } else { throw new Exception( "Support for specifying both a day-of-week AND a day-of-month parameter is not implemented."); } d = new DateTime(d.Year, d.Month, day, d.Hour, d.Minute, d.Second); mon = d.Month; int year = d.Year; t = -1; if (year > 2099) { return null; } st = months.TailSet((mon)); if (st != null && st.Count != 0) { t = mon; mon = ((int)st.First()); } else { mon = ((int)months.First()); year++; } if (mon != t) { d = new DateTime(year, mon, 1, 0, 0, 0); continue; } d = new DateTime(d.Year, mon, d.Day, d.Hour, d.Minute, d.Second); year = d.Year; t = -1; st = years.TailSet((year)); if (st != null && st.Count != 0) { t = year; year = ((int)st.First()); } else { return null; } if (year != t) { d = new DateTime(year, 1, 1, 0, 0, 0); continue; } d = new DateTime(year, d.Month, d.Day, d.Hour, d.Minute, d.Second); gotOne = true; } return TimeZoneInfo.ConvertTimeToUtc(d, TimeZone); } protected static DateTime CreateDateTimeWithoutMillis(DateTime time) { return new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute, time.Second); } protected static DateTime SetCalendarHour(DateTime date, int hour) { int hourToSet = hour; if (hourToSet == 24) { hourToSet = 0; } var d = new DateTime(date.Year, date.Month, date.Day, hourToSet, date.Minute, date.Second, date.Millisecond); if (hour == 24) { d = d.AddDays(1); } return d; } public virtual DateTime? GetTimeBefore(DateTime? endTime) { return null; } public virtual DateTime? GetFinalFireTime() { return null; } protected virtual bool IsLeapYear(int year) { return DateTime.IsLeapYear(year); } protected virtual int GetLastDayOfMonth(int monthNum, int year) { return DateTime.DaysInMonth(year, monthNum); } } public class ValueSet { public int pos; public int theValue; } }
#region File Description //----------------------------------------------------------------------------- // GameplayScreen.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Threading; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; #endregion namespace VectorRumble { /// <summary> /// This screen implements the actual game logic. It is just a /// placeholder to get the idea across: you'll probably want to /// put some more interesting gameplay in here! /// </summary> /// <remarks> /// This class is somewhat similar to one of the same name in the /// GameStateManagement sample. /// </remarks> class GameplayScreen : GameScreen { #region Fields BloomComponent bloomComponent; ContentManager content; LineBatch lineBatch; SpriteBatch spriteBatch; SpriteFont spriteFont; Texture2D starTexture; World world; AudioManager audio; bool gameOver; #endregion #region Initialization /// <summary> /// Constructor. /// </summary> public GameplayScreen() { TransitionOnTime = TimeSpan.FromSeconds(1.0); TransitionOffTime = TimeSpan.FromSeconds(1.0); } /// <summary> /// Initialize the game, after the ScreenManager is set, but not every time /// the graphics are reloaded. /// </summary> public void Initialize() { // create and add the bloom effect bloomComponent = new BloomComponent(ScreenManager.Game); ScreenManager.Game.Components.Add(bloomComponent); // do not automatically draw the bloom component bloomComponent.Visible = false; // create the world world = new World(new Vector2(ScreenManager.GraphicsDevice.Viewport.Width, ScreenManager.GraphicsDevice.Viewport.Height)); // retrieve the audio manager audio = (AudioManager)ScreenManager.Game.Services.GetService( typeof(AudioManager)); world.AudioManager = audio; // start up the music audio.PlayMusic("gameMusic"); // start up the game world.StartNewGame(); gameOver = false; } /// <summary> /// Load graphics content for the game. /// </summary> public override void LoadContent() { if (content == null) { content = new ContentManager(ScreenManager.Game.Services, "Content"); } spriteBatch = new SpriteBatch(ScreenManager.GraphicsDevice); lineBatch = new LineBatch(ScreenManager.GraphicsDevice); spriteFont = content.Load<SpriteFont>("Fonts/retroSmall"); starTexture = content.Load<Texture2D>("Textures/blank"); // update the projection in the line-batch lineBatch.SetProjection(Matrix.CreateOrthographicOffCenter(0.0f, ScreenManager.GraphicsDevice.Viewport.Width, ScreenManager.GraphicsDevice.Viewport.Height, 0.0f, 0.0f, 1.0f)); } /// <summary> /// Unload graphics content used by the game. /// </summary> public override void UnloadContent() { if (spriteBatch != null) { spriteBatch.Dispose(); spriteBatch = null; } if (lineBatch != null) { lineBatch.Dispose(); lineBatch = null; } content.Unload(); } #endregion #region Update and Draw /// <summary> /// Updates the state of the game. This method checks the GameScreen.IsActive /// property, so the game will stop updating when the pause menu is active, /// or if you tab away to a different application. /// </summary> public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); // if this screen is leaving, then stop the music if (IsExiting) { audio.StopMusic(); } else if ((otherScreenHasFocus == true) || (coveredByOtherScreen == true)) { // make sure nobody's controller is vibrating for (int i = 0; i < 4; i++) { GamePad.SetVibration((PlayerIndex)i, 0f, 0f); } if (gameOver == false) { for (int i = 0; i < world.Ships.Length; i++) { world.Ships[i].ProcessInput(gameTime.TotalGameTime.Seconds, true); } } } else { // check for a winner if (gameOver == false) { for (int i = 0; i < world.Ships.Length; i++) { if (world.Ships[i].Score >= WorldRules.ScoreLimit) { ScreenManager.AddScreen(new GameOverScreen("Player " + (i + 1).ToString() + " wins the game!")); gameOver = true; break; } } } // update the world if (gameOver == false) { world.Update((float)gameTime.ElapsedGameTime.TotalSeconds); } } } /// <summary> /// Lets the game respond to player input. Unlike the Update method, /// this will only be called when the gameplay screen is active. /// </summary> public override void HandleInput(InputState input) { if (input == null) throw new ArgumentNullException("input"); if (input.PauseGame) { // If they pressed pause, bring up the pause menu screen. ScreenManager.AddScreen(new PauseMenuScreen()); } } /// <summary> /// Draws the gameplay screen. /// </summary> public override void Draw(GameTime gameTime) { float elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds; lineBatch.Begin(); // draw all actors foreach (Actor actor in world.Actors) { if (actor.Dead == false) { actor.Draw(elapsedTime, lineBatch); } } // draw all particle systems foreach (ParticleSystem particleSystem in world.ParticleSystems) { if (particleSystem.IsActive) { particleSystem.Draw(lineBatch); } } // draw the walls world.DrawWalls(lineBatch); lineBatch.End(); // draw the stars spriteBatch.Begin(); world.Starfield.Draw(spriteBatch, starTexture); spriteBatch.End(); if (WorldRules.NeonEffect) { bloomComponent.Draw(gameTime); } DrawHud(elapsedTime); // If the game is transitioning on or off, fade it out to black. if (TransitionPosition > 0) ScreenManager.FadeBackBufferToBlack(255 - TransitionAlpha); } /// <summary> /// Draw the user interface elements of the game (scores, etc.). /// </summary> /// <param name="elapsedTime">The amount of elapsed time, in seconds.</param> private void DrawHud(float elapsedTime) { spriteBatch.Begin(); Vector2 position = new Vector2(128, 64); int offset = (1280) / 5; for (int i = 0; i < world.Ships.Length; ++i) { string message; if (world.Ships[i].Playing) { message = "Player " + (i + 1).ToString() + ": " + world.Ships[i].Score.ToString(); } else { message = "Hold A to Join"; } float scale = 1.0f; Vector2 size = spriteFont.MeasureString(message) * scale; position.X = (i + 1) * offset - size.X / 2; spriteBatch.DrawString(spriteFont, message, position, world.Ships[i].Color, 0.0f, Vector2.Zero, scale, SpriteEffects.None, 1.0f); } spriteBatch.End(); } #endregion } }
#region MIT. // // Gorgon. // Copyright (C) 2011 Michael Winsor // // 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 // 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. // // Created: Friday, June 24, 2011 10:05:35 AM // #endregion using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using Gorgon.Input.Properties; using Gorgon.Math; namespace Gorgon.Input { /// <summary> /// Provides state for gaming device data from a physical gaming device. /// </summary> /// <remarks> /// <para> /// Gaming devices (such as a joystick or game pad) and provided via a driver system using the <see cref="GorgonGamingDeviceDriver"/> object. These drivers may be loaded via a plug in interface through the /// <see cref="GorgonGamingDeviceDriverFactory"/> object. Once a driver is loaded, it can be used to create an object of this type. /// </para> /// <para> /// The gaming devices can support a variable number of axes, and this is reflected within the <see cref="Axis"/> property to make available only those axes which are supported by the device. For example, /// if the device supports a single horizontal axis and that axis is mapped to the secondary axis (<see cref="GamingDeviceAxis.XAxis2"/>), then the <see cref="Axis"/> collection will only contain a member /// for the <see cref="GamingDeviceAxis.XAxis2"/> value. Likewise, if it supports many axes, then all of those axes will be made available. To determine which axes are supported, use the <see cref="GorgonGamingDeviceAxisList{T}.Contains"/> /// method on the <see cref="Info"/>.<see cref="IGorgonGamingDeviceInfo.AxisInfo"/> property or the on the <see cref="Axis"/> property. /// </para> /// <para> /// <see cref="GorgonGamingDevice"/> objects require that the device be polled via a call to the <see cref="Poll"/> method. This will capture the latest state from the physical device and store it within /// this type for use by an application. /// </para> /// <para> /// Some gaming devices (such as XInput controllers) offer special functionality like vibration. This object supports sending data to the physical device to activate the special functionality. If the device /// does not support the functionality, an exception is typically thrown. Use the <see cref="IGorgonGamingDeviceInfo.Capabilities"/> property to determine if these special functions are supported by the /// device before calling. /// </para> /// <para> /// Implementors of a <see cref="GorgonGamingDeviceDriver"/> plug in must inherit this type in order to expose functionality from a native provider (e.g. XInput). /// </para> /// </remarks> public abstract class GorgonGamingDevice : IGorgonGamingDevice { #region Variables. // The POV of view control directions. private readonly POVDirection[] _povDirections; // Flag to indicate whether the gaming device has been acquired or not. private bool _isAcquired; #endregion #region Properties. /// <summary> /// Property to return the current direction for the point-of-view hat. /// </summary> /// <remarks> /// If the gaming device does not support a point-of-view axis, then this value will always return <see cref="POVDirection.Center"/>. /// </remarks> public IReadOnlyList<POVDirection> POVDirection => _povDirections; /// <summary> /// Property to return information about the gaming device. /// </summary> public IGorgonGamingDeviceInfo Info { get; } /// <summary> /// Property to return the list of axes available to this gaming device. /// </summary> /// <remarks> /// <para> /// This property is used to return the current position and dead zone for a given axis. /// </para> /// <para> /// <see cref="GorgonGamingDeviceDriver"/> plug in implementors must set this value when device data is retrieved. /// </para> /// </remarks> /// <example> /// This example shows how to use this property to get the current gaming device X axis position: /// <code language="csharp"> /// <![CDATA[ /// IGorgonGamingDevice _device; /// int _currentXPosition; /// /// void SetupDevices() /// { /// // Do set up in here to retrieve a value for _device. /// } /// /// void UpdateJoystickPosition() /// { /// _device.Poll(); /// /// _currentXPosition = _device.Axis[GamingDeviceAxis.XAxis].Value; /// } /// ]]> /// </code> /// </example> public GorgonGamingDeviceAxisList<IGorgonGamingDeviceAxis> Axis { get; } /// <summary> /// Property to return the point of view value for discrete or continuous bearings. /// </summary> /// <remarks> /// <para> /// This will return a <see cref="float"/> value of -1.0f for center, or 0 to 359.9999f to indicate the direction, in degrees, of the POV hat. /// </para> /// <para> /// <see cref="GorgonGamingDeviceDriver"/> plug in implementors must set this value when device data is retrieved. /// </para> /// </remarks> public float[] POV { get; } /// <summary> /// Property to return a list of button states. /// </summary> /// <remarks> /// <para> /// This will return a list of the available buttons on the gaming device and their corresponding state represented by a <see cref="GamingDeviceButtonState"/> enumeration. /// </para> /// <para> /// <see cref="GorgonGamingDeviceDriver"/> plug in implementors must set this value when device data is retrieved. /// </para> /// </remarks> public GamingDeviceButtonState[] Button { get; } /// <summary> /// Property to return whether the gaming device is connected or not. /// </summary> /// <remarks> /// <para> /// Gaming devices may be registered with the system, and appear in the enumeration list provided by <see cref="GorgonGamingDeviceDriver.EnumerateGamingDevices"/>, but they may not be physically connected /// to the system at the time of enumeration. Thus, we have this property to ensure that we know when a gaming device is connected to the system or not. /// </para> /// <para> /// <see cref="GorgonGamingDeviceDriver"/> plug in implementors must ensure that this property will update itself when a gaming device is connected or disconnected. /// </para> /// </remarks> public abstract bool IsConnected { get; } /// <summary> /// Property to set or return whether the device is acquired or not. /// </summary> /// <remarks> /// <para> /// Set this value to <b>true</b> to acquire the device for the application, or <b>false</b> to unacquire it. /// </para> /// <para> /// Some input providers, like Direct Input, have the concept of device acquisition. When a device is created it may not be usable until it has been acquired by the application. When a device is /// acquired, it will be made available for use by the application. However, in some circumstances, another application may have exclusive control over the device, and as such, acquisition is not /// possible. /// </para> /// <para> /// A device may lose acquisition when the application goes into the background, and as such, the application will no longer receive information from the device. When this is the case, the /// application should immediately set this value to <b>false</b> during deactivation (during the WinForms <see cref="Form.Deactivate"/>, or WPF <see cref="E:System.Windows.Window.Deactivated"/> events). /// When the application is activated (during the WinForms <see cref="Form.Activated"/>, or WPF <see cref="E:System.Windows.Window.Activated"/> events), it should set this value to <b>true</b> in order to /// start capturing data again. /// </para> /// <para> /// Note that some devices from other input providers (like XInput) will always be in an acquired state. Regardless, it is best to update this flag when the application becomes active or inactive. /// </para> /// </remarks> public bool IsAcquired { get => _isAcquired; set { if (_isAcquired == value) { return; } _isAcquired = OnAcquire(value); } } #endregion #region Methods. /// <summary> /// Function to update the direction flag for the POV. /// </summary> /// <param name="povIndex">The index of the point of view control to use.</param> private void UpdatePOVDirection(int povIndex) { if ((Info.Capabilities & GamingDeviceCapabilityFlags.SupportsPOV) != GamingDeviceCapabilityFlags.SupportsPOV) { return; } int pov = (int)((POV[povIndex] * 100.0f).Max(-1.0f)); // Wrap POV if it's higher than 359.99 degrees. if (pov > 35999) { pov = -1; } // Get POV direction. if (pov != -1) { if (pov is < 18000 and > 9000) { _povDirections[povIndex] = Input.POVDirection.Down | Input.POVDirection.Right; } if (pov is > 18000 and < 27000) { _povDirections[povIndex] = Input.POVDirection.Down | Input.POVDirection.Left; } if (pov is > 27000 and < 36000) { _povDirections[povIndex] = Input.POVDirection.Up | Input.POVDirection.Left; } if (pov is > 0 and < 9000) { _povDirections[povIndex] = Input.POVDirection.Up | Input.POVDirection.Right; } } switch (pov) { case 18000: _povDirections[povIndex] = Input.POVDirection.Down; break; case 0: _povDirections[povIndex] = Input.POVDirection.Up; break; case 9000: _povDirections[povIndex] = Input.POVDirection.Right; break; case 27000: _povDirections[povIndex] = Input.POVDirection.Left; break; case -1: _povDirections[povIndex] = Input.POVDirection.Center; break; } } /// <summary> /// Function to acquire a gaming device. /// </summary> /// <param name="acquireState"><b>true</b> to acquire the device, <b>false</b> to unacquire it.</param> /// <returns><b>true</b> if the device was acquired successfully, <b>false</b> if not.</returns> /// <remarks> /// <para> /// Implementors of a <see cref="GorgonGamingDeviceDriver"/> should implement this on the concrete <see cref="GorgonGamingDevice"/>, even if the device does not use acquisition (in such a case, /// always return <b>true</b> from this method). /// </para> /// <para> /// Some input providers, like Direct Input, have the concept of device acquisition. When a device is created it may not be usable until it has been acquired by the application. When a device is /// acquired, it will be made available for use by the application. However, in some circumstances, another application may have exclusive control over the device, and as such, acquisition is not /// possible. /// </para> /// <para> /// A device may lose acquisition when the application goes into the background, and as such, the application will no longer receive information from the device. When this is the case, the /// application should immediately check after it regains foreground focus to see whether the device is acquired or not. For a winforms application this can be achieved with the <see cref="Form.Activated"/> /// event. When that happens, set this property to <b>true</b>. /// </para> /// <para> /// Note that some devices from other input providers (like XInput) will always be in an acquired state. Regardless, it is best to check this flag when the application becomes active. /// </para> /// </remarks> protected abstract bool OnAcquire(bool acquireState); /// <summary> /// Function to perform vibration on the gaming device, if supported. /// </summary> /// <param name="motorIndex">The index of the motor to start or stop.</param> /// <param name="value">The speed of the motor.</param> /// <remarks> /// <para> /// This will activate the vibration motor(s) in the gaming device. The <paramref name="motorIndex"/> should be within the <see cref="IGorgonGamingDeviceInfo.VibrationMotorRanges"/> count, or else /// an exception will be thrown. /// </para> /// <para> /// To determine if the device supports vibration, check the <see cref="IGorgonGamingDeviceInfo.Capabilities"/> property for the <see cref="GamingDeviceCapabilityFlags.SupportsVibration"/> flag. /// </para> /// <para> /// Implementors of a <see cref="GorgonGamingDeviceDriver"/> plug in should ensure that devices that support vibration implement this method. Otherwise, if the device does not support the functionality /// then this method can be left alone. /// </para> /// </remarks> protected virtual void OnVibrate(int motorIndex, int value) { } /// <summary> /// Function to retrieve data from the provider of the physical device. /// </summary> /// <remarks> /// Implementors of a <see cref="GorgonGamingDeviceDriver"/> plug in must implement this and format their data to populate the values of this object with correct state information. /// </remarks> protected abstract void OnGetData(); /// <summary> /// Function to reset the various gaming device axis, button and POV states to default values. /// </summary> public virtual void Reset() { for (int i = 0; i < _povDirections.Length; ++i) { POV[i] = -1.0f; _povDirections[i] = Input.POVDirection.Center; } foreach (GamingDeviceAxisProperties axis in Axis) { axis.Value = Info.AxisInfo[axis.Axis].DefaultValue; } for (int i = 0; i < Button.Length; ++i) { Button[i] = GamingDeviceButtonState.Up; } } /// <summary> /// Function to perform vibration on the gaming device, if supported. /// </summary> /// <param name="motorIndex">The index of the motor to start or stop.</param> /// <param name="value">The speed of the motor.</param> /// <remarks> /// <para> /// This will activate the vibration motor(s) in the gaming device. The <paramref name="motorIndex"/> should be within the <see cref="IGorgonGamingDeviceInfo.VibrationMotorRanges"/> count, or else /// an exception will be thrown. /// </para> /// <para> /// To determine if the device supports vibration, check the <see cref="IGorgonGamingDeviceInfo.Capabilities"/> property for the <see cref="GamingDeviceCapabilityFlags.SupportsVibration"/> flag. /// </para> /// </remarks> public void Vibrate(int motorIndex, int value) { if (((Info.Capabilities & GamingDeviceCapabilityFlags.SupportsVibration) != GamingDeviceCapabilityFlags.SupportsVibration) || (motorIndex < 0) || (motorIndex >= Info.VibrationMotorRanges.Count)) { throw new ArgumentOutOfRangeException(nameof(motorIndex), string.Format(Resources.GORINP_ERR_JOYSTICK_MOTOR_NOT_FOUND, motorIndex)); } if (Info.VibrationMotorRanges[motorIndex].Contains(value)) { OnVibrate(motorIndex, value); } } /// <summary> /// Function to read the gaming device state. /// </summary> /// <remarks> /// <para> /// This method is used to capture the current state of the gaming device. When the state is captured, its data is propagated to the properties for this object. /// </para> /// <para> /// If this method is not called before checking state, that state will be invalid and/or out of date. Ensure that this method is called frequently to capture the most current state of the physical /// device. /// </para> /// </remarks> public void Poll() { if (!IsConnected) { return; } OnGetData(); for (int i = 0; i < POV.Length; ++i) { UpdatePOVDirection(i); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <remarks> /// <para> /// Some gaming devices use native resources to communicate with the physical device. Because of this, it is necessary to call this method to ensure those resources are freed. /// </para> /// <para> /// For implementors of a <see cref="GorgonGamingDeviceDriver"/>, this method should be overridden to free up any native resources required by the device. If the device does /// not use any native resources, then it is safe to leave this method alone. /// </para> /// </remarks> public virtual void Dispose() => GC.SuppressFinalize(this); #endregion #region Constructor/Destructor. /// <summary> /// Initializes a new instance of the <see cref="GorgonGamingDevice"/> class. /// </summary> /// <param name="deviceInfo">Information about the specific gaming device to use.</param> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="deviceInfo"/> parameter is <b>null</b>.</exception> protected GorgonGamingDevice(IGorgonGamingDeviceInfo deviceInfo) { if (deviceInfo is null) { throw new ArgumentNullException(nameof(deviceInfo)); } _povDirections = new POVDirection[((deviceInfo.Capabilities & GamingDeviceCapabilityFlags.SupportsPOV) == GamingDeviceCapabilityFlags.SupportsPOV) ? deviceInfo.POVCount : 0]; POV = new float[_povDirections.Length]; Button = new GamingDeviceButtonState[deviceInfo.ButtonCount]; Info = deviceInfo; Axis = new GorgonGamingDeviceAxisList<IGorgonGamingDeviceAxis>(deviceInfo.AxisInfo.Select(item => new GamingDeviceAxisProperties(item.Value))); } #endregion } }
// Copyright 2007-2008 The Apache Software Foundation. // // 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 MassTransit.Configuration { using System; using System.Collections.Generic; using Exceptions; using Internal; using log4net; using Pipeline.Configuration; public class ServiceBusConfigurator : ServiceBusConfiguratorDefaults, IServiceBusConfigurator { private static readonly ILog _log = LogManager.GetLogger(typeof (ServiceBusConfigurator)); private static readonly ServiceBusConfiguratorDefaults _defaults = new ServiceBusConfiguratorDefaults(); private readonly List<Action<IServiceBus, IObjectBuilder, Action<Type, IBusService>>> _services; private Uri _receiveFromUri; private Action _beforeConsume; private Action _afterConsume; protected ServiceBusConfigurator() { _services = new List<Action<IServiceBus, IObjectBuilder, Action<Type, IBusService>>>(); _defaults.ApplyTo(this); } protected IControlBus ControlBus { get; set; } public void ReceiveFrom(string uriString) { try { _receiveFromUri = new Uri(uriString); } catch (UriFormatException ex) { throw new ConfigurationException("The Uri for the receive endpoint is invalid: " + uriString, ex); } } public void ReceiveFrom(Uri uri) { _receiveFromUri = uri; } public void ConfigureService<TServiceConfigurator>(Action<TServiceConfigurator> configure) where TServiceConfigurator : IServiceConfigurator, new() { _services.Add((bus, builder, add) => { TServiceConfigurator configurator = new TServiceConfigurator(); configure(configurator); var service = configurator.Create(bus, builder); add(configurator.ServiceType, service); }); } public void AddService<TService>(Func<TService> getService) where TService : IBusService { _services.Add((bus, builder, add) => { var service = getService(); add(typeof (TService), service); }); } public void AddService<TService>() where TService : IBusService { _services.Add((bus, builder, add) => { DefaultBusServiceConfigurator<TService> configurator = new DefaultBusServiceConfigurator<TService>(); var service = configurator.Create(bus, builder); add(configurator.ServiceType, service); }); } public void UseControlBus(IControlBus bus) { ControlBus = bus; } public void BeforeConsumingMessage(Action beforeConsume) { if (_beforeConsume == null) _beforeConsume = beforeConsume; else _beforeConsume += beforeConsume; } public void AfterConsumingMessage(Action afterConsume) { if (_afterConsume == null) _afterConsume = afterConsume; else _afterConsume += afterConsume; } internal IControlBus Create() { ServiceBus bus = CreateServiceBus(); ConfigurePoisonEndpoint(bus); ConfigureThreadLimits(bus); if (AutoSubscribe) { // get all the types and subscribe them to the bus } ConfigureMessageInterceptors(bus); ConfigureControlBus(bus); ConfigureBusServices(bus); if (AutoStart) { bus.Start(); } return bus; } private void ConfigureMessageInterceptors(IServiceBus bus) { if(_beforeConsume != null || _afterConsume != null) { MessageInterceptorConfigurator.For(bus.InboundPipeline).Create(_beforeConsume, _afterConsume); } } private void ConfigureControlBus(ServiceBus bus) { if (ControlBus == null) return; if(_log.IsDebugEnabled) _log.DebugFormat("Associating control bus ({0}) with service bus ({1})", ControlBus.Endpoint.Uri, bus.Endpoint.Uri); bus.ControlBus = ControlBus; } private void ConfigurePoisonEndpoint(ServiceBus bus) { if (ErrorUri != null) { bus.PoisonEndpoint = bus.EndpointFactory.GetEndpoint(ErrorUri); } } private ServiceBus CreateServiceBus() { var endpointFactory = ObjectBuilder.GetInstance<IEndpointFactory>(); var endpoint = endpointFactory.GetEndpoint(_receiveFromUri); return new ServiceBus(endpoint, ObjectBuilder, endpointFactory); } private void ConfigureThreadLimits(ServiceBus bus) { if (ConcurrentConsumerLimit > 0) bus.MaximumConsumerThreads = ConcurrentConsumerLimit; if (ConcurrentReceiverLimit > 0) bus.ConcurrentReceiveThreads = ConcurrentReceiverLimit; bus.ReceiveTimeout = ReceiveTimeout; } private void ConfigureBusServices(ServiceBus bus) { foreach (var serviceConfigurator in _services) { serviceConfigurator(bus, ObjectBuilder, bus.AddService); } } public static IServiceBus New(Action<IServiceBusConfigurator> action) { var configurator = new ServiceBusConfigurator(); action(configurator); return configurator.Create(); } public static void Defaults(Action<IServiceBusConfiguratorDefaults> action) { action(_defaults); } } public class ControlBusConfigurator : ServiceBusConfigurator { public new static IControlBus New(Action<IServiceBusConfigurator> action) { var configurator = new ControlBusConfigurator(); configurator.SetConcurrentConsumerLimit(1); action(configurator); return configurator.Create(); } } }
/* * 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. * */ /* * This package is based on the work done by Keiron Liddle, Aftex Software * <[email protected]> to whom the Ant project is very grateful for his * great code. */ using System; using java.io; using java.lang; using java.net; using java.nio; using java.text; using java.util; using RSUtilities.Collections; using RSUtilities.Compression.BZip2; namespace RSUtilities.Compression.BZip2 { /// <summary> /// An input stream that decompresses from the BZip2 format (without the file /// header chars) to be read as any other stream. /// <p> /// The decompression requires large amounts of memory. Thus you /// should call the <seealso cref="#close() close()" /> method as soon as /// possible, to force <tt>CBZip2InputStream</tt> to release the /// allocated memory. See {@link CBZip2OutputStream /// CBZip2OutputStream} for information about memory usage. /// </p> /// <p> /// <tt>CBZip2InputStream</tt> reads bytes from the compressed /// source stream via the single byte {@link java.io.InputStream#read() /// read()} method exclusively. Thus you should consider to use a /// buffered source stream. /// </p> /// <p>Instances of this class are not threadsafe.</p> /// </summary> public class CBZip2InputStream : InputStream, BZip2Constants { private const int EOF = 0; private const int START_BLOCK_STATE = 1; private const int RAND_PART_A_STATE = 2; private const int RAND_PART_B_STATE = 3; private const int RAND_PART_C_STATE = 4; private const int NO_RAND_PART_A_STATE = 5; private const int NO_RAND_PART_B_STATE = 6; private const int NO_RAND_PART_C_STATE = 7; private readonly CRC crc = new CRC(); private bool blockRandomised; /// <summary> /// always: in the range 0 .. 9. /// The current block size is 100000 * this number. /// </summary> private int blockSize100k; private int bsBuff; private int bsLive; private int computedBlockCRC, computedCombinedCRC; private int currentChar = -1; private int currentState = START_BLOCK_STATE; /// <summary> /// All memory intensive stuff. /// This field is initialized by initBlock(). /// </summary> private Data data; private InputStream @in; /// <summary> /// Index of the last char in the block, so the block size == last + 1. /// </summary> private int last; private int nInUse; /// <summary> /// Index in zptr[] of original string after sorting. /// </summary> private int origPtr; private int storedBlockCRC, storedCombinedCRC; private int su_ch2; private int su_chPrev; private int su_count; private int su_i2; private int su_j2; private int su_rNToGo; private int su_rTPos; private int su_tPos; private char su_z; /// <summary> /// Constructs a new CBZip2InputStream which decompresses bytes read from /// the specified stream. /// <p> /// Although BZip2 headers are marked with the magic /// <tt>"Bz"</tt> this constructor expects the next byte in the /// stream to be the first one after the magic. Thus callers have /// to skip the first two bytes. Otherwise this constructor will /// throw an exception. /// </p> /// </summary> /// <exception cref="IOException"> /// if the stream content is malformed or an I/O error occurs. /// </exception> /// <exception cref="NullPointerException"> /// if <tt>in == null</tt> /// </exception> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not allowed in .NET: public CBZip2InputStream(InputStream @in) { this.@in = @in; Init(); } private static void ReportCRCError() { // The clean way would be to throw an exception. throw new IOException("crc error"); // Just print a message, like the previous versions of this class did //System.err.println("BZip2 CRC error"); } private void MakeMaps() { var inUse = data.inUse; var seqToUnseq = data.seqToUnseq; var nInUseShadow = 0; for (var i = 0; i < 256; i++) { if (inUse[i]) { seqToUnseq[nInUseShadow++] = (byte) i; } } nInUse = nInUseShadow; } public virtual int Read() { if (@in != null) { return Read0(); } throw new IOException("stream closed"); } //JAVA TO C# CONVERTER WARNING: 'final' parameters are not allowed in .NET: public virtual int Read(byte[] dest, int offs, int len) { if (offs < 0) { throw new IndexOutOfRangeException("offs(" + offs + ") < 0."); } if (len < 0) { throw new IndexOutOfRangeException("len(" + len + ") < 0."); } if (offs + len > dest.Length) { throw new IndexOutOfRangeException("offs(" + offs + ") + len(" + len + ") > dest.length(" + dest.Length + ")."); } if (@in == null) { throw new IOException("stream closed"); } var hi = offs + len; var destOffs = offs; for (int b; (destOffs < hi) && ((b = Read0()) >= 0);) { dest[destOffs++] = (byte) b; } return (destOffs == offs) ? - 1 : (destOffs - offs); } private int Read0() { var retChar = currentChar; switch (currentState) { case EOF: return -1; case START_BLOCK_STATE: throw new IllegalStateException(); case RAND_PART_A_STATE: throw new IllegalStateException(); case RAND_PART_B_STATE: SetupRandPartB(); break; case RAND_PART_C_STATE: SetupRandPartC(); break; case NO_RAND_PART_A_STATE: throw new IllegalStateException(); case NO_RAND_PART_B_STATE: SetupNoRandPartB(); break; case NO_RAND_PART_C_STATE: SetupNoRandPartC(); break; default: throw new IllegalStateException(); } return retChar; } private void Init() { if (null == @in) { throw new IOException("No InputStream"); } if (@in.available() == 0) { throw new IOException("Empty InputStream"); } var magic2 = @in.read(); if (magic2 != 'h') { throw new IOException("Stream is not BZip2 formatted: expected 'h'" + " as first byte but got '" + (char) magic2 + "'"); } var blockSize = @in.read(); if ((blockSize < '1') || (blockSize > '9')) { throw new IOException("Stream is not BZip2 formatted: illegal " + "blocksize " + (char) blockSize); } blockSize100k = blockSize - '0'; InitBlock(); SetupBlock(); } private void InitBlock() { var magic0 = BsGetUByte(); var magic1 = BsGetUByte(); var magic2 = BsGetUByte(); var magic3 = BsGetUByte(); var magic4 = BsGetUByte(); var magic5 = BsGetUByte(); if (magic0 == 0x17 && magic1 == 0x72 && magic2 == 0x45 && magic3 == 0x38 && magic4 == 0x50 && magic5 == 0x90) { Complete(); // end of file } // '1' else if (magic0 != 0x31 || magic1 != 0x41 || magic2 != 0x59 || magic3 != 0x26 || magic4 != 0x53 || magic5 != 0x59) // 'Y' - 'S' - '&' - 'Y' - ')' { currentState = EOF; throw new IOException("bad block header"); } else { storedBlockCRC = BsGetInt(); blockRandomised = BsR(1) == 1; /// <summary> /// Allocate data here instead in constructor, so we do not /// allocate it if the input file is empty. /// </summary> if (data == null) { data = new Data(blockSize100k); } // currBlockNo++; GetAndMoveToFrontDecode(); crc.InitialiseCRC(); currentState = START_BLOCK_STATE; } } private void EndBlock() { computedBlockCRC = crc.GetFinalCRC(); // A bad CRC is considered a fatal error. if (storedBlockCRC != computedBlockCRC) { // make next blocks readable without error // (repair feature, not yet documented, not tested) computedCombinedCRC = (storedCombinedCRC << 1) | ((int) ((uint) storedCombinedCRC >> 31)); computedCombinedCRC ^= storedBlockCRC; ReportCRCError(); } computedCombinedCRC = (computedCombinedCRC << 1) | ((int) ((uint) computedCombinedCRC >> 31)); computedCombinedCRC ^= computedBlockCRC; } private void Complete() { storedCombinedCRC = BsGetInt(); currentState = EOF; data = null; if (storedCombinedCRC != computedCombinedCRC) { ReportCRCError(); } } public virtual void Close() { var inShadow = @in; if (inShadow != null) { try { if (inShadow != java.lang.System.@in) { inShadow.close(); } } finally { data = null; @in = null; } } } //JAVA TO C# CONVERTER WARNING: 'final' parameters are not allowed in .NET: private int BsR(int n) { var bsLiveShadow = bsLive; var bsBuffShadow = bsBuff; if (bsLiveShadow < n) { var inShadow = @in; do { var thech = inShadow.read(); if (thech < 0) { throw new IOException("unexpected end of stream"); } bsBuffShadow = (bsBuffShadow << 8) | thech; bsLiveShadow += 8; } while (bsLiveShadow < n); bsBuff = bsBuffShadow; } bsLive = bsLiveShadow - n; return (bsBuffShadow >> (bsLiveShadow - n)) & ((1 << n) - 1); } private bool BsGetBit() { var bsLiveShadow = bsLive; var bsBuffShadow = bsBuff; if (bsLiveShadow < 1) { var thech = @in.read(); if (thech < 0) { throw new IOException("unexpected end of stream"); } bsBuffShadow = (bsBuffShadow << 8) | thech; bsLiveShadow += 8; bsBuff = bsBuffShadow; } bsLive = bsLiveShadow - 1; return ((bsBuffShadow >> (bsLiveShadow - 1)) & 1) != 0; } private char BsGetUByte() { return (char) BsR(8); } private int BsGetInt() { return (((((BsR(8) << 8) | BsR(8)) << 8) | BsR(8)) << 8) | BsR(8); } /// <summary> /// Called by createHuffmanDecodingTables() exclusively. /// </summary> private static void HbCreateDecodeTables(int[] limit, int[] @base, int[] perm, char[] length, int minLen, int maxLen, int alphaSize) { for (int i = minLen, pp = 0; i <= maxLen; i++) { for (var j = 0; j < alphaSize; j++) { if (length[j] == i) { perm[pp++] = j; } } } for (var i = BZip2Constants_Fields.MAX_CODE_LEN; --i > 0;) { @base[i] = 0; limit[i] = 0; } for (var i = 0; i < alphaSize; i++) { @base[length[i] + 1]++; } for (int i = 1, b = @base[0]; i < BZip2Constants_Fields.MAX_CODE_LEN; i++) { b += @base[i]; @base[i] = b; } for (int i = minLen, vec = 0, b = @base[i]; i <= maxLen; i++) { var nb = @base[i + 1]; vec += nb - b; b = nb; limit[i] = vec - 1; vec <<= 1; } for (var i = minLen + 1; i <= maxLen; i++) { @base[i] = ((limit[i - 1] + 1) << 1) - @base[i]; } } private void RecvDecodingTables() { var dataShadow = data; var inUse = dataShadow.inUse; var pos = dataShadow.recvDecodingTables_pos; var selector = dataShadow.selector; var selectorMtf = dataShadow.selectorMtf; var inUse16 = 0; /* Receive the mapping table */ for (var i = 0; i < 16; i++) { if (BsGetBit()) { inUse16 |= 1 << i; } } for (var i = 256; --i >= 0;) { inUse[i] = false; } for (var i = 0; i < 16; i++) { if ((inUse16 & (1 << i)) != 0) { var i16 = i << 4; for (var j = 0; j < 16; j++) { if (BsGetBit()) { inUse[i16 + j] = true; } } } } MakeMaps(); var alphaSize = nInUse + 2; /* Now the selectors */ var nGroups = BsR(3); var nSelectors = BsR(15); for (var i = 0; i < nSelectors; i++) { var j = 0; while (BsGetBit()) { j++; } selectorMtf[i] = (byte) j; } /* Undo the MTF values for the selectors. */ for (var v = nGroups; --v >= 0;) { pos[v] = (byte) v; } for (var i = 0; i < nSelectors; i++) { var v = selectorMtf[i] & 0xff; var tmp = pos[v]; while (v > 0) { // nearly all times v is zero, 4 in most other cases pos[v] = pos[v - 1]; v--; } pos[0] = tmp; selector[i] = tmp; } var len = dataShadow.temp_charArray2d; /* Now the coding tables */ for (var t = 0; t < nGroups; t++) { var curr = BsR(5); var len_t = len[t]; for (var i = 0; i < alphaSize; i++) { while (BsGetBit()) { curr += BsGetBit() ? - 1 : 1; } len_t[i] = (char) curr; } } // finally create the Huffman tables CreateHuffmanDecodingTables(alphaSize, nGroups); } /// <summary> /// Called by recvDecodingTables() exclusively. /// </summary> private void CreateHuffmanDecodingTables(int alphaSize, int nGroups) { var dataShadow = data; var len = dataShadow.temp_charArray2d; var minLens = dataShadow.minLens; var limit = dataShadow.limit; var @base = dataShadow.@base; var perm = dataShadow.perm; for (var t = 0; t < nGroups; t++) { var minLen = 32; var maxLen = 0; var len_t = len[t]; for (var i = alphaSize; --i >= 0;) { var lent = len_t[i]; if (lent > maxLen) { maxLen = lent; } if (lent < minLen) { minLen = lent; } } HbCreateDecodeTables(limit[t], @base[t], perm[t], len[t], minLen, maxLen, alphaSize); minLens[t] = minLen; } } private void GetAndMoveToFrontDecode() { origPtr = BsR(24); RecvDecodingTables(); var inShadow = @in; var dataShadow = data; var ll8 = dataShadow.ll8; var unzftab = dataShadow.unzftab; var selector = dataShadow.selector; var seqToUnseq = dataShadow.seqToUnseq; var yy = dataShadow.getAndMoveToFrontDecode_yy; var minLens = dataShadow.minLens; var limit = dataShadow.limit; var @base = dataShadow.@base; var perm = dataShadow.perm; var limitLast = blockSize100k * 100000; /* Setting up the unzftab entries here is not strictly necessary, but it does save having to do it later in a separate pass, and so saves a block's worth of cache misses. */ for (var i = 256; --i >= 0;) { yy[i] = (char) i; unzftab[i] = 0; } var groupNo = 0; var groupPos = BZip2Constants_Fields.G_SIZE - 1; var eob = nInUse + 1; var nextSym = GetAndMoveToFrontDecode0(0); var bsBuffShadow = bsBuff; var bsLiveShadow = bsLive; var lastShadow = -1; var zt = selector[groupNo] & 0xff; var base_zt = @base[zt]; var limit_zt = limit[zt]; var perm_zt = perm[zt]; var minLens_zt = minLens[zt]; while (nextSym != eob) { if ((nextSym == BZip2Constants_Fields.RUNA) || (nextSym == BZip2Constants_Fields.RUNB)) { var s = -1; for (var n = 1;; n <<= 1) { if (nextSym == BZip2Constants_Fields.RUNA) { s += n; } else if (nextSym == BZip2Constants_Fields.RUNB) { s += n << 1; } else { break; } if (groupPos == 0) { groupPos = BZip2Constants_Fields.G_SIZE - 1; zt = selector[++groupNo] & 0xff; base_zt = @base[zt]; limit_zt = limit[zt]; perm_zt = perm[zt]; minLens_zt = minLens[zt]; } else { groupPos--; } var zn = minLens_zt; // Inlined: // int zvec = bsR(zn); while (bsLiveShadow < zn) { var thech = inShadow.read(); if (thech >= 0) { bsBuffShadow = (bsBuffShadow << 8) | thech; bsLiveShadow += 8; } throw new IOException("unexpected end of stream"); } var zvec = (bsBuffShadow >> (bsLiveShadow - zn)) & ((1 << zn) - 1); bsLiveShadow -= zn; while (zvec > limit_zt[zn]) { zn++; while (bsLiveShadow < 1) { var thech = inShadow.read(); if (thech >= 0) { bsBuffShadow = (bsBuffShadow << 8) | thech; bsLiveShadow += 8; } throw new IOException("unexpected end of stream"); } bsLiveShadow--; zvec = (zvec << 1) | ((bsBuffShadow >> bsLiveShadow) & 1); } nextSym = perm_zt[zvec - base_zt[zn]]; } var ch = seqToUnseq[yy[0]]; unzftab[ch & 0xff] += s + 1; while (s-- >= 0) { ll8[++lastShadow] = ch; } if (lastShadow >= limitLast) { throw new IOException("block overrun"); } } else { if (++lastShadow >= limitLast) { throw new IOException("block overrun"); } var tmp = yy[nextSym - 1]; unzftab[seqToUnseq[tmp] & 0xff]++; ll8[lastShadow] = seqToUnseq[tmp]; /* This loop is hammered during decompression, hence avoid native method call overhead of System.arraycopy for very small ranges to copy. */ if (nextSym <= 16) { for (var j = nextSym - 1; j > 0;) { yy[j] = yy[--j]; } } else { Array.Copy(yy, 0, yy, 1, nextSym - 1); } yy[0] = tmp; if (groupPos == 0) { groupPos = BZip2Constants_Fields.G_SIZE - 1; zt = selector[++groupNo] & 0xff; base_zt = @base[zt]; limit_zt = limit[zt]; perm_zt = perm[zt]; minLens_zt = minLens[zt]; } else { groupPos--; } var zn = minLens_zt; // Inlined: // int zvec = bsR(zn); while (bsLiveShadow < zn) { var thech = inShadow.read(); if (thech >= 0) { bsBuffShadow = (bsBuffShadow << 8) | thech; bsLiveShadow += 8; } throw new IOException("unexpected end of stream"); } var zvec = (bsBuffShadow >> (bsLiveShadow - zn)) & ((1 << zn) - 1); bsLiveShadow -= zn; while (zvec > limit_zt[zn]) { zn++; while (bsLiveShadow < 1) { var thech = inShadow.read(); if (thech >= 0) { bsBuffShadow = (bsBuffShadow << 8) | thech; bsLiveShadow += 8; } throw new IOException("unexpected end of stream"); } bsLiveShadow--; zvec = (zvec << 1) | ((bsBuffShadow >> bsLiveShadow) & 1); } nextSym = perm_zt[zvec - base_zt[zn]]; } } last = lastShadow; bsLive = bsLiveShadow; bsBuff = bsBuffShadow; } //JAVA TO C# CONVERTER WARNING: 'final' parameters are not allowed in .NET: private int GetAndMoveToFrontDecode0(int groupNo) { var inShadow = @in; var dataShadow = data; var zt = dataShadow.selector[groupNo] & 0xff; var limit_zt = dataShadow.limit[zt]; var zn = dataShadow.minLens[zt]; var zvec = BsR(zn); var bsLiveShadow = bsLive; var bsBuffShadow = bsBuff; while (zvec > limit_zt[zn]) { zn++; while (bsLiveShadow < 1) { var thech = inShadow.read(); if (thech >= 0) { bsBuffShadow = (bsBuffShadow << 8) | thech; bsLiveShadow += 8; } throw new IOException("unexpected end of stream"); } bsLiveShadow--; zvec = (zvec << 1) | ((bsBuffShadow >> bsLiveShadow) & 1); } bsLive = bsLiveShadow; bsBuff = bsBuffShadow; return dataShadow.perm[zt][zvec - dataShadow.@base[zt][zn]]; } private void SetupBlock() { if (data == null) { return; } var cftab = data.cftab; var tt = data.InitTT(last + 1); var ll8 = data.ll8; cftab[0] = 0; Array.Copy(data.unzftab, 0, cftab, 1, 256); for (int i = 1, c = cftab[0]; i <= 256; i++) { c += cftab[i]; cftab[i] = c; } for (int i = 0, lastShadow = last; i <= lastShadow; i++) { tt[cftab[ll8[i] & 0xff]++] = i; } if ((origPtr < 0) || (origPtr >= tt.Length)) { throw new IOException("stream corrupted"); } su_tPos = tt[origPtr]; su_count = 0; su_i2 = 0; su_ch2 = 256; // not a char and not EOF if (blockRandomised) { su_rNToGo = 0; su_rTPos = 0; SetupRandPartA(); } else { SetupNoRandPartA(); } } private void SetupRandPartA() { if (su_i2 <= last) { su_chPrev = su_ch2; var su_ch2Shadow = data.ll8[su_tPos] & 0xff; su_tPos = data.tt[su_tPos]; if (su_rNToGo == 0) { su_rNToGo = BZip2Constants_Fields.rNums[su_rTPos] - 1; if (++su_rTPos == 512) { su_rTPos = 0; } } else { su_rNToGo--; } su_ch2 = su_ch2Shadow ^= (su_rNToGo == 1) ? 1 : 0; su_i2++; currentChar = su_ch2Shadow; currentState = RAND_PART_B_STATE; crc.UpdateCRC(su_ch2Shadow); } else { EndBlock(); InitBlock(); SetupBlock(); } } private void SetupNoRandPartA() { if (su_i2 <= last) { su_chPrev = su_ch2; var su_ch2Shadow = data.ll8[su_tPos] & 0xff; su_ch2 = su_ch2Shadow; su_tPos = data.tt[su_tPos]; su_i2++; currentChar = su_ch2Shadow; currentState = NO_RAND_PART_B_STATE; crc.UpdateCRC(su_ch2Shadow); } else { currentState = NO_RAND_PART_A_STATE; EndBlock(); InitBlock(); SetupBlock(); } } private void SetupRandPartB() { if (su_ch2 != su_chPrev) { currentState = RAND_PART_A_STATE; su_count = 1; SetupRandPartA(); } else if (++su_count >= 4) { su_z = (char) (data.ll8[su_tPos] & 0xff); su_tPos = data.tt[su_tPos]; if (su_rNToGo == 0) { su_rNToGo = BZip2Constants_Fields.rNums[su_rTPos] - 1; if (++su_rTPos == 512) { su_rTPos = 0; } } else { su_rNToGo--; } su_j2 = 0; currentState = RAND_PART_C_STATE; if (su_rNToGo == 1) { su_z ^= (char) 1; } SetupRandPartC(); } else { currentState = RAND_PART_A_STATE; SetupRandPartA(); } } private void SetupRandPartC() { if (su_j2 < su_z) { currentChar = su_ch2; crc.UpdateCRC(su_ch2); su_j2++; } else { currentState = RAND_PART_A_STATE; su_i2++; su_count = 0; SetupRandPartA(); } } private void SetupNoRandPartB() { if (su_ch2 != su_chPrev) { su_count = 1; SetupNoRandPartA(); } else if (++su_count >= 4) { su_z = (char) (data.ll8[su_tPos] & 0xff); su_tPos = data.tt[su_tPos]; su_j2 = 0; SetupNoRandPartC(); } else { SetupNoRandPartA(); } } private void SetupNoRandPartC() { if (su_j2 < su_z) { var su_ch2Shadow = su_ch2; currentChar = su_ch2Shadow; crc.UpdateCRC(su_ch2Shadow); su_j2++; currentState = NO_RAND_PART_C_STATE; } else { su_i2++; su_count = 0; SetupNoRandPartA(); } } public override int read() { return @in.read(); } private sealed class Data : object { // (with blockSize 900k) //JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java: //ORIGINAL LINE: internal readonly int[][] base = new int[BZip2Constants_Fields.N_GROUPS][BZip2Constants_Fields.MAX_ALPHA_SIZE]; // 6192 byte internal readonly int[][] @base = ArrayUtil.ReturnRectangularArray<int>(BZip2Constants_Fields.N_GROUPS, BZip2Constants_Fields.MAX_ALPHA_SIZE); // 6192 byte //JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java: //ORIGINAL LINE: internal readonly int[][] perm = new int[BZip2Constants_Fields.N_GROUPS][BZip2Constants_Fields.MAX_ALPHA_SIZE]; // 6192 byte internal readonly int[] cftab = new int[257]; // 1028 byte internal readonly char[] getAndMoveToFrontDecode_yy = new char[256]; // 512 byte internal readonly bool[] inUse = new bool[256]; // 256 byte internal readonly int[][] limit = ArrayUtil.ReturnRectangularArray<int>(BZip2Constants_Fields.N_GROUPS, BZip2Constants_Fields.MAX_ALPHA_SIZE); // 6192 byte internal readonly int[] minLens = new int[BZip2Constants_Fields.N_GROUPS]; // 24 byte internal readonly int[][] perm = ArrayUtil.ReturnRectangularArray<int>(BZip2Constants_Fields.N_GROUPS, BZip2Constants_Fields.MAX_ALPHA_SIZE); // 6192 byte //JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java: //ORIGINAL LINE: internal readonly char[][] temp_charArray2d = new char[BZip2Constants_Fields.N_GROUPS][BZip2Constants_Fields.MAX_ALPHA_SIZE]; // 3096 byte internal readonly byte[] recvDecodingTables_pos = new byte[BZip2Constants_Fields.N_GROUPS]; // 6 byte internal readonly byte[] selector = new byte[BZip2Constants_Fields.MAX_SELECTORS]; // 18002 byte internal readonly byte[] selectorMtf = new byte[BZip2Constants_Fields.MAX_SELECTORS]; // 18002 byte internal readonly byte[] seqToUnseq = new byte[256]; // 256 byte internal readonly char[][] temp_charArray2d = ArrayUtil.ReturnRectangularArray<char>(BZip2Constants_Fields.N_GROUPS, BZip2Constants_Fields.MAX_ALPHA_SIZE); // 3096 byte /// <summary> /// Freq table collected to save a pass over the data during /// decompression. /// </summary> internal readonly int[] unzftab = new int[256]; // 1024 byte //--------------- // 60798 byte internal byte[] ll8; // 900000 byte internal int[] tt; // 3600000 byte //--------------- // 4560782 byte //=============== internal Data(int blockSize100k) { ll8 = new byte[blockSize100k * BZip2Constants_Fields.baseBlockSize]; } /// <summary> /// Initializes the <seealso cref="#tt" /> array. /// This method is called when the required length of the array /// is known. I don't initialize it at construction time to /// avoid unneccessary memory allocation when compressing small /// files. /// </summary> internal int[] InitTT(int length) { var ttShadow = tt; // tt.length should always be >= length, but theoretically // it can happen, if the compressor mixed small and large // blocks. Normally only the last block will be smaller // than others. if ((ttShadow == null) || (ttShadow.Length < length)) { tt = ttShadow = new int[length]; } return ttShadow; } } } }
using System; using System.Data; using System.Data.OleDb; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; using PCSComUtils.Common; namespace PCSComUtils.Admin.DS { public class Sys_UserDS { public Sys_UserDS() { } private const string THIS = "PCSComUtils.Admin.DS.DS.Sys_UserDS"; //************************************************************************** /// <Description> /// Get the System date from database /// </Description> /// <Inputs> /// Sys_UserVO /// </Inputs> /// <Outputs> /// newly inserted primarkey value /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Thursday, January 06, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public string GetSystemDate() { const string METHOD_NAME = THIS + ".GetSystemDate()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { string strSql = String.Empty; strSql= " SELECT CONVERT(VARCHAR(10),getdate(),101) "; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); return ocmdPCS.ExecuteScalar().ToString(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public DateTime GetDatabaseDate() { const string METHOD_NAME = THIS + ".GetSystemDate()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { string strSql = String.Empty; strSql= " SELECT getdate() "; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); return (DateTime)ocmdPCS.ExecuteScalar(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to add data to Sys_User /// </Description> /// <Inputs> /// Sys_UserVO /// </Inputs> /// <Outputs> /// newly inserted primarkey value /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Thursday, January 06, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { Sys_UserVO objObject = (Sys_UserVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql= "INSERT INTO Sys_User(" + Sys_UserTable.USERNAME_FLD + "," + Sys_UserTable.PWD_FLD + "," + Sys_UserTable.NAME_FLD + "," + Sys_UserTable.CREATEDDATE_FLD + "," + Sys_UserTable.DESCRIPTION_FLD + "," + Sys_UserTable.CCNID_FLD + "," + Sys_UserTable.EMPLOYEEID_FLD + "," + Sys_UserTable.MASTERLOCATIONID_FLD + "," + Sys_UserTable.ACTIVATE_FLD + "," + Sys_UserTable.EXPIREDDATE_FLD + ")" + "VALUES(?,?,?,?,?,?,?,?,?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.USERNAME_FLD, OleDbType.Char)); ocmdPCS.Parameters[Sys_UserTable.USERNAME_FLD].Value = objObject.UserName; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.PWD_FLD, OleDbType.Char)); ocmdPCS.Parameters[Sys_UserTable.PWD_FLD].Value = objObject.Pwd; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.NAME_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[Sys_UserTable.NAME_FLD].Value = objObject.Name; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.CREATEDDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[Sys_UserTable.CREATEDDATE_FLD].Value = objObject.CreatedDate; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.DESCRIPTION_FLD, OleDbType.Char)); ocmdPCS.Parameters[Sys_UserTable.DESCRIPTION_FLD].Value = objObject.Description; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.CCNID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_UserTable.CCNID_FLD].Value = objObject.CCNID; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.EMPLOYEEID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_UserTable.EMPLOYEEID_FLD].Value = objObject.EmployeeID; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.MASTERLOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_UserTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.ACTIVATE_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_UserTable.ACTIVATE_FLD].Value = objObject.Activate; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.EXPIREDDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[Sys_UserTable.EXPIREDDATE_FLD].Value = objObject.ExpiredDate; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE || ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_UNIQUE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to add data to Sys_User /// </Description> /// <Inputs> /// Sys_UserVO /// </Inputs> /// <Outputs> /// newly inserted primarkey value /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Thursday, January 06, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public int AddNewUserAndReturnNewID(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { Sys_UserVO objObject = (Sys_UserVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql= "INSERT INTO Sys_User(" + Sys_UserTable.USERNAME_FLD + "," + Sys_UserTable.PWD_FLD + "," + Sys_UserTable.NAME_FLD + "," + Sys_UserTable.CREATEDDATE_FLD + "," + Sys_UserTable.DESCRIPTION_FLD + "," + Sys_UserTable.CCNID_FLD + "," + Sys_UserTable.EMPLOYEEID_FLD + "," + Sys_UserTable.MASTERLOCATIONID_FLD + "," + Sys_UserTable.ACTIVATE_FLD + "," + Sys_UserTable.EXPIREDDATE_FLD + ")" + "VALUES(?,?,?,?,?,?,?,?,?,?)"; strSql += " ; SELECT @@IDENTITY "; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.USERNAME_FLD, OleDbType.VarChar)); ocmdPCS.Parameters[Sys_UserTable.USERNAME_FLD].Value = objObject.UserName; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.PWD_FLD, OleDbType.VarChar)); ocmdPCS.Parameters[Sys_UserTable.PWD_FLD].Value = objObject.Pwd; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.NAME_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[Sys_UserTable.NAME_FLD].Value = objObject.Name; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.CREATEDDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[Sys_UserTable.CREATEDDATE_FLD].Value = objObject.CreatedDate; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.DESCRIPTION_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[Sys_UserTable.DESCRIPTION_FLD].Value = objObject.Description; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.CCNID_FLD, OleDbType.Integer)); if (objObject.CCNID <= 0) { ocmdPCS.Parameters[Sys_UserTable.CCNID_FLD].Value = DBNull.Value; } else { ocmdPCS.Parameters[Sys_UserTable.CCNID_FLD].Value = objObject.CCNID; } ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.EMPLOYEEID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_UserTable.EMPLOYEEID_FLD].Value = objObject.EmployeeID; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.MASTERLOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_UserTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.ACTIVATE_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_UserTable.ACTIVATE_FLD].Value = objObject.Activate; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.EXPIREDDATE_FLD, OleDbType.Date)); if (objObject.ExpiredDate == DateTime.MinValue) { ocmdPCS.Parameters[Sys_UserTable.EXPIREDDATE_FLD].Value = DBNull.Value; } else { ocmdPCS.Parameters[Sys_UserTable.EXPIREDDATE_FLD].Value = objObject.ExpiredDate; } ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); //ocmdPCS.ExecuteNonQuery(); return int.Parse(ocmdPCS.ExecuteScalar().ToString()); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE || ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_UNIQUE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to add data to Sys_User /// </Description> /// <Inputs> /// Sys_UserVO /// </Inputs> /// <Outputs> /// newly inserted primarkey value /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Thursday, January 06, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void AddNewUser(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { Sys_UserVO objObject = (Sys_UserVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql= "INSERT INTO Sys_User(" + Sys_UserTable.USERNAME_FLD + "," + Sys_UserTable.PWD_FLD + "," + Sys_UserTable.NAME_FLD + "," + Sys_UserTable.CREATEDDATE_FLD + "," + Sys_UserTable.DESCRIPTION_FLD + "," + Sys_UserTable.CCNID_FLD + "," + Sys_UserTable.EMPLOYEEID_FLD + "," + Sys_UserTable.MASTERLOCATIONID_FLD + "," + Sys_UserTable.ACTIVATE_FLD + "," + Sys_UserTable.EXPIREDDATE_FLD + ")" + "VALUES(?,?,?,?,?,?,?,?,?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.USERNAME_FLD, OleDbType.Char)); ocmdPCS.Parameters[Sys_UserTable.USERNAME_FLD].Value = objObject.UserName; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.PWD_FLD, OleDbType.Char)); ocmdPCS.Parameters[Sys_UserTable.PWD_FLD].Value = objObject.Pwd; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.NAME_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[Sys_UserTable.NAME_FLD].Value = objObject.Name; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.CREATEDDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[Sys_UserTable.CREATEDDATE_FLD].Value = objObject.CreatedDate; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.DESCRIPTION_FLD, OleDbType.Char)); ocmdPCS.Parameters[Sys_UserTable.DESCRIPTION_FLD].Value = objObject.Description; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.CCNID_FLD, OleDbType.Integer)); if (objObject.CCNID <= 0) { ocmdPCS.Parameters[Sys_UserTable.CCNID_FLD].Value = DBNull.Value; } else { ocmdPCS.Parameters[Sys_UserTable.CCNID_FLD].Value = objObject.CCNID; } ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.EMPLOYEEID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_UserTable.EMPLOYEEID_FLD].Value = objObject.EmployeeID; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.MASTERLOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_UserTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.ACTIVATE_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_UserTable.ACTIVATE_FLD].Value = objObject.Activate; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.EXPIREDDATE_FLD, OleDbType.Date)); if (objObject.ExpiredDate == DateTime.MinValue) { ocmdPCS.Parameters[Sys_UserTable.EXPIREDDATE_FLD].Value = DBNull.Value; } else { ocmdPCS.Parameters[Sys_UserTable.EXPIREDDATE_FLD].Value = objObject.ExpiredDate; } ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE || ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_UNIQUE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to delete data from Sys_User /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// void /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql= "DELETE " + Sys_UserTable.TABLE_NAME + " WHERE " + Sys_UserTable.USERID_FLD + "=" + pintID.ToString(); OleDbConnection oconPCS=null; OleDbCommand ocmdPCS =null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get data from Sys_User /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// Sys_UserVO /// </Outputs> /// <Returns> /// Sys_UserVO /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Thursday, January 06, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public int GetUserIDByUserName(string pstrUserName) { const string METHOD_NAME = THIS + ".GetUserIDByUserName()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + Sys_UserTable.USERID_FLD + " FROM " + Sys_UserTable.TABLE_NAME +" WHERE " + Sys_UserTable.USERNAME_FLD + "='" + pstrUserName + "'"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); object objReturnValue = ocmdPCS.ExecuteScalar(); if (objReturnValue == null) { return -1; } else { return int.Parse(objReturnValue.ToString()); } } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get data from Sys_User /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// Sys_UserVO /// </Outputs> /// <Returns> /// Sys_UserVO /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Thursday, January 06, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + Sys_UserTable.USERID_FLD + "," + Sys_UserTable.USERNAME_FLD + "," + Sys_UserTable.PWD_FLD + "," + Sys_UserTable.NAME_FLD + "," + Sys_UserTable.CREATEDDATE_FLD + "," + Sys_UserTable.DESCRIPTION_FLD + "," + Sys_UserTable.CCNID_FLD + "," + Sys_UserTable.EMPLOYEEID_FLD + "," + Sys_UserTable.MASTERLOCATIONID_FLD + "," + Sys_UserTable.ACTIVATE_FLD + "," + Sys_UserTable.EXPIREDDATE_FLD + " FROM " + Sys_UserTable.TABLE_NAME +" WHERE " + Sys_UserTable.USERID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); Sys_UserVO objObject = new Sys_UserVO(); while (odrPCS.Read()) { objObject.UserID = int.Parse(odrPCS[Sys_UserTable.USERID_FLD].ToString()); objObject.UserName = odrPCS[Sys_UserTable.USERNAME_FLD].ToString().Trim(); objObject.Pwd = odrPCS[Sys_UserTable.PWD_FLD].ToString().Trim(); objObject.Name = odrPCS[Sys_UserTable.NAME_FLD].ToString().Trim(); if(odrPCS[Sys_UserTable.CREATEDDATE_FLD].ToString().Length > 0) { objObject.CreatedDate = DateTime.Parse(odrPCS[Sys_UserTable.CREATEDDATE_FLD].ToString()); } objObject.Description = odrPCS[Sys_UserTable.DESCRIPTION_FLD].ToString(); if(odrPCS[Sys_UserTable.CCNID_FLD].ToString().Length > 0) { objObject.CCNID = int.Parse(odrPCS[Sys_UserTable.CCNID_FLD].ToString()); } objObject.EmployeeID = int.Parse(odrPCS[Sys_UserTable.EMPLOYEEID_FLD].ToString()); objObject.MasterLocationID = int.Parse(odrPCS[Sys_UserTable.MASTERLOCATIONID_FLD].ToString()); objObject.Activate = bool.Parse(odrPCS[Sys_UserTable.ACTIVATE_FLD].ToString()); if(odrPCS[Sys_UserTable.EXPIREDDATE_FLD].ToString().Length > 0) { objObject.ExpiredDate = DateTime.Parse(odrPCS[Sys_UserTable.EXPIREDDATE_FLD].ToString()); } } return objObject; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get data from Sys_User /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// Sys_UserVO /// </Outputs> /// <Returns> /// Sys_UserVO /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Thursday, January 06, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public object GetObjectVO(string pstrUserName) { const string METHOD_NAME = THIS + ".GetObjectVO()"; OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + Sys_UserTable.USERID_FLD + "," + Sys_UserTable.USERNAME_FLD + "," + Sys_UserTable.PWD_FLD + "," + Sys_UserTable.NAME_FLD + "," + Sys_UserTable.CREATEDDATE_FLD + "," + Sys_UserTable.DESCRIPTION_FLD + "," + Sys_UserTable.CCNID_FLD + "," + Sys_UserTable.EMPLOYEEID_FLD + "," + Sys_UserTable.MASTERLOCATIONID_FLD + "," + Sys_UserTable.ACTIVATE_FLD + "," + Sys_UserTable.EXPIREDDATE_FLD + " FROM " + Sys_UserTable.TABLE_NAME + " WHERE " + Sys_UserTable.USERNAME_FLD + "= '" + pstrUserName + "'"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); Sys_UserVO objObject = new Sys_UserVO(); while (odrPCS.Read()) { objObject.UserID = int.Parse(odrPCS[Sys_UserTable.USERID_FLD].ToString()); objObject.UserName = odrPCS[Sys_UserTable.USERNAME_FLD].ToString().Trim(); objObject.Pwd = odrPCS[Sys_UserTable.PWD_FLD].ToString().Trim(); objObject.Name = odrPCS[Sys_UserTable.NAME_FLD].ToString().Trim(); if(odrPCS[Sys_UserTable.CREATEDDATE_FLD].ToString().Length > 0) { objObject.CreatedDate = DateTime.Parse(odrPCS[Sys_UserTable.CREATEDDATE_FLD].ToString()); } objObject.Description = odrPCS[Sys_UserTable.DESCRIPTION_FLD].ToString(); if(odrPCS[Sys_UserTable.CCNID_FLD].ToString().Length > 0) { objObject.CCNID = int.Parse(odrPCS[Sys_UserTable.CCNID_FLD].ToString()); } objObject.EmployeeID = int.Parse(odrPCS[Sys_UserTable.EMPLOYEEID_FLD].ToString()); objObject.MasterLocationID = int.Parse(odrPCS[Sys_UserTable.MASTERLOCATIONID_FLD].ToString()); if (odrPCS[Sys_UserTable.ACTIVATE_FLD].ToString().Length > 0) { objObject.Activate = bool.Parse(odrPCS[Sys_UserTable.ACTIVATE_FLD].ToString()); } if(odrPCS[Sys_UserTable.EXPIREDDATE_FLD].ToString().Length > 0) { objObject.ExpiredDate = DateTime.Parse(odrPCS[Sys_UserTable.EXPIREDDATE_FLD].ToString()); } } return objObject; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update data to Sys_User /// </Description> /// <Inputs> /// Sys_UserVO /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; Sys_UserVO objObject = (Sys_UserVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql= "UPDATE Sys_User SET " + Sys_UserTable.USERNAME_FLD + "= ?" + "," + Sys_UserTable.PWD_FLD + "= ?" + "," + Sys_UserTable.NAME_FLD + "= ?" + "," //+ Sys_UserTable.CREATEDDATE_FLD + "= ?" + "," + Sys_UserTable.DESCRIPTION_FLD + "= ?" + "," + Sys_UserTable.CCNID_FLD + "= ?" + "," + Sys_UserTable.EMPLOYEEID_FLD + "= ?" + "," + Sys_UserTable.MASTERLOCATIONID_FLD + "= ?" + "," + Sys_UserTable.ACTIVATE_FLD + "= ?" + "," + Sys_UserTable.EXPIREDDATE_FLD + "= ?" +" WHERE " + Sys_UserTable.USERID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.USERNAME_FLD, OleDbType.VarChar)); ocmdPCS.Parameters[Sys_UserTable.USERNAME_FLD].Value = objObject.UserName; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.PWD_FLD, OleDbType.VarChar)); ocmdPCS.Parameters[Sys_UserTable.PWD_FLD].Value = objObject.Pwd; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.NAME_FLD, OleDbType.VarChar)); ocmdPCS.Parameters[Sys_UserTable.NAME_FLD].Value = objObject.Name; /* ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.CREATEDDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[Sys_UserTable.CREATEDDATE_FLD].Value = objObject.CreatedDate; */ ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.DESCRIPTION_FLD, OleDbType.VarChar)); ocmdPCS.Parameters[Sys_UserTable.DESCRIPTION_FLD].Value = objObject.Description; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.CCNID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_UserTable.CCNID_FLD].Value = objObject.CCNID; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.EMPLOYEEID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_UserTable.EMPLOYEEID_FLD].Value = objObject.EmployeeID; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.MASTERLOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_UserTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.ACTIVATE_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_UserTable.ACTIVATE_FLD].Value = objObject.Activate; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.EXPIREDDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[Sys_UserTable.EXPIREDDATE_FLD].Value = objObject.ExpiredDate; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.USERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_UserTable.USERID_FLD].Value = objObject.UserID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE || ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_UNIQUE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update data to Sys_User /// </Description> /// <Inputs> /// Sys_UserVO /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void UpdateUserInfo(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; Sys_UserVO objObject = (Sys_UserVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql= "UPDATE Sys_User SET " + Sys_UserTable.USERNAME_FLD + "= ?" + "," + Sys_UserTable.PWD_FLD + "= ?" + "," + Sys_UserTable.NAME_FLD + "= ?" + "," //+ Sys_UserTable.CREATEDDATE_FLD + "= ?" + "," + Sys_UserTable.DESCRIPTION_FLD + "= ?" + "," + Sys_UserTable.CCNID_FLD + "= ?" + "," + Sys_UserTable.EMPLOYEEID_FLD + "= ?" + "," + Sys_UserTable.MASTERLOCATIONID_FLD + "= ?" + "," + Sys_UserTable.ACTIVATE_FLD + "= ?" + "," + Sys_UserTable.EXPIREDDATE_FLD + "= ?" +" WHERE " + Sys_UserTable.USERID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.USERNAME_FLD, OleDbType.VarChar)); ocmdPCS.Parameters[Sys_UserTable.USERNAME_FLD].Value = objObject.UserName; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.PWD_FLD, OleDbType.VarChar)); ocmdPCS.Parameters[Sys_UserTable.PWD_FLD].Value = objObject.Pwd; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.NAME_FLD, OleDbType.VarChar)); ocmdPCS.Parameters[Sys_UserTable.NAME_FLD].Value = objObject.Name; /* ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.CREATEDDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[Sys_UserTable.CREATEDDATE_FLD].Value = objObject.CreatedDate; */ ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.DESCRIPTION_FLD, OleDbType.VarChar)); ocmdPCS.Parameters[Sys_UserTable.DESCRIPTION_FLD].Value = objObject.Description; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.CCNID_FLD, OleDbType.Integer)); if (objObject.CCNID <= 0) { ocmdPCS.Parameters[Sys_UserTable.CCNID_FLD].Value = DBNull.Value; } else { ocmdPCS.Parameters[Sys_UserTable.CCNID_FLD].Value = objObject.CCNID; } ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.EMPLOYEEID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_UserTable.EMPLOYEEID_FLD].Value = objObject.EmployeeID; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.MASTERLOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_UserTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.ACTIVATE_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_UserTable.ACTIVATE_FLD].Value = objObject.Activate; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.EXPIREDDATE_FLD, OleDbType.Date)); if (objObject.ExpiredDate == DateTime.MinValue) { ocmdPCS.Parameters[Sys_UserTable.EXPIREDDATE_FLD].Value = DBNull.Value; } else { ocmdPCS.Parameters[Sys_UserTable.EXPIREDDATE_FLD].Value = objObject.ExpiredDate; } ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.USERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[Sys_UserTable.USERID_FLD].Value = objObject.UserID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE || ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_UNIQUE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update data to Sys_User /// </Description> /// <Inputs> /// Sys_UserVO /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void UpdatePassword(string pstrUserName, string pstrNewPassword) { const string METHOD_NAME = THIS + ".Update()"; //prepare value for parameters OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql= "UPDATE Sys_User SET " + Sys_UserTable.PWD_FLD + "= ?" +" WHERE " + Sys_UserTable.USERNAME_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.PWD_FLD, OleDbType.VarChar)); ocmdPCS.Parameters[Sys_UserTable.PWD_FLD].Value = pstrNewPassword; ocmdPCS.Parameters.Add(new OleDbParameter(Sys_UserTable.USERNAME_FLD, OleDbType.VarChar)); ocmdPCS.Parameters[Sys_UserTable.USERNAME_FLD].Value = pstrUserName; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get all data from Sys_User /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// DataSet /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Thursday, January 06, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + Sys_UserTable.USERID_FLD + "," + Sys_UserTable.USERNAME_FLD + "," + Sys_UserTable.PWD_FLD + "," //+ Sys_UserTable.NAME_FLD + "," + "E.Name," + Sys_UserTable.CREATEDDATE_FLD + "," + Sys_UserTable.DESCRIPTION_FLD + "," + "U." + Sys_UserTable.CCNID_FLD + "," + "U." + Sys_UserTable.EMPLOYEEID_FLD + "," + "U." + Sys_UserTable.MASTERLOCATIONID_FLD + "," + "M." + MST_MasterLocationTable.CODE_FLD + " MasterLocationCode," + Sys_UserTable.ACTIVATE_FLD + "," + Sys_UserTable.EXPIREDDATE_FLD + " FROM " + Sys_UserTable.TABLE_NAME + " U" + " INNER JOIN MST_Employee E ON U.EmployeeID=E.EmployeeID" + " INNER JOIN MST_MasterLocation M ON U.MasterLocationID=M.MasterLocationID" + " AND U.UserName <> '" + Constants.SUPER_ADMIN_USER + "'"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,Sys_UserTable.TABLE_NAME); return dstPCS; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get all data from Sys_User /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// DataSet /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Thursday, January 06, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataTable ListAllUsers() { const string METHOD_NAME = THIS + ".ListAllUsers()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + Sys_UserTable.USERID_FLD + "," + Sys_UserTable.USERNAME_FLD + " FROM " + Sys_UserTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,Sys_UserTable.TABLE_NAME); return dstPCS.Tables[0]; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update a DataSet /// </Description> /// <Inputs> /// DataSet /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Thursday, January 06, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void UpdateDataSet(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS =null; OleDbCommandBuilder odcbPCS ; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql= "SELECT " + Sys_UserTable.USERID_FLD + "," + Sys_UserTable.USERNAME_FLD + "," + Sys_UserTable.PWD_FLD + "," + Sys_UserTable.NAME_FLD + "," + Sys_UserTable.CREATEDDATE_FLD + "," + Sys_UserTable.DESCRIPTION_FLD + "," + Sys_UserTable.CCNID_FLD + "," + Sys_UserTable.EMPLOYEEID_FLD + "," + Sys_UserTable.MASTERLOCATIONID_FLD + "," + Sys_UserTable.ACTIVATE_FLD + "," + Sys_UserTable.EXPIREDDATE_FLD + " FROM " + Sys_UserTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = false; odadPCS.Update(pData,Sys_UserTable.TABLE_NAME); pData.Clear(); odadPCS.Fill(pData,pData.Tables[0].TableName); pData.AcceptChanges(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE || ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_UNIQUE_KEYCODE ) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to check authenticate for a user /// </Description> /// <Inputs> /// pobjObjecVO contains UserName and Password of user /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// UserID : If user authenticates /// -1: If user doesn't authenticate /// </Returns> /// <Authors> /// TuanDm /// </Authors> /// <History> /// Tuesday, January 10, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public Sys_UserVO CheckAuthenticate(Sys_UserVO pobjObjecVO) { const string METHOD_NAME = THIS + ".CheckAuthenticate()"; Sys_UserVO objOldObjec = pobjObjecVO; Sys_UserVO objObjec = (Sys_UserVO) GetObjectVO(pobjObjecVO.UserName); PCSComUtils.Common.DS.UtilsDS dsUtils = new PCSComUtils.Common.DS.UtilsDS(); try { // Check null user if(objObjec.UserName == null) { PCSException ex = new PCSException(); ex.mCode = ErrorCode.USERNAME_PASSWORD_INVALID; throw ex; } else if ((objOldObjec.UserName.ToLower() != objObjec.UserName.ToLower())||(objOldObjec.Pwd != objObjec.Pwd)) { PCSException ex = new PCSException(); ex.mCode = ErrorCode.USERNAME_PASSWORD_INVALID; throw ex; } else { if (!objObjec.Activate) { PCSException ex = new PCSException(); ex.mCode = ErrorCode.MESSAGE_ACOUNT_NOTACTIVE; throw ex; } //HACK by Tuan TQ. 11 Jan, 2006 //if(objObjec.ExpiredDate < DateTime.Now) //Rem by Tuan TQ. 11 Jan, 2005 if ((objObjec.ExpiredDate < dsUtils.GetDBDate()) && (objObjec.ExpiredDate != DateTime.MinValue)) { PCSException ex = new PCSException(); ex.mCode = ErrorCode.MESSAGE_ACOUNT_EXPIRE; throw ex; } //End hack } return objObjec; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch(PCSException ex) { throw ex; } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { } } //************************************************************************** /// <Description> /// Get all role for a user defined by username /// </Description> /// <Inputs> /// pstrUserName : UserName of user /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// TuanDm /// </Authors> /// <History> /// Tuesday, January 10, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet ListRoleForUser(string pstrUserName) { const string METHOD_NAME = THIS + ".ListRoleForUser()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + Sys_UserToRoleTable.ROLEID_FLD + " FROM " + Sys_UserToRoleTable.TABLE_NAME + " WHERE " + Sys_UserToRoleTable.USERID_FLD + " IN ( SELECT " + Sys_UserTable.USERID_FLD + " FROM " + Sys_UserTable.TABLE_NAME + " WHERE " + Sys_UserTable.USERNAME_FLD + " = '" + pstrUserName + "' )" ; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,Sys_UserToRoleTable.TABLE_NAME); return dstPCS; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to check authenticate for a user /// </Description> /// <Inputs> /// pobjObjecVO contains UserName and Password of user /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// UserID : If user authenticates /// -1: If user doesn't authenticate /// </Returns> /// <Authors> /// TuanDm /// </Authors> /// <History> /// Tuesday, January 10, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public bool IsSystemAdmin(string pstrUserName) { const string METHOD_NAME = THIS + ".IsSystemAdmin()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT ISNULL(COUNT(*), 0) FROM " + Sys_UserToRoleTable.TABLE_NAME + " WHERE " + Sys_UserToRoleTable.ROLEID_FLD + "=" + " (SELECT " + Sys_RoleTable.ROLEID_FLD + " FROM " + Sys_RoleTable.TABLE_NAME + " WHERE " + Sys_RoleTable.NAME_FLD + "='" + Constants.ADMINISTRATORS + "')"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); object objResult = ocmdPCS.ExecuteScalar(); if (objResult != null) { if (int.Parse(objResult.ToString()) > 0) return true; else return false; } else return false; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch(PCSException ex) { throw ex; } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { } } } }
#region Copyright /*Copyright (C) 2015 Konstantin Udilovich 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.Generic; using System.Windows.Controls; using Dynamo.Controls; using Dynamo.Models; using Dynamo.Wpf; using ProtoCore.AST.AssociativeAST; using Kodestruct.Common.CalculationLogger; using Kodestruct.Dynamo.Common; using Kodestruct.Loads.ASCE7.Entities; using Kodestruct.Dynamo.Common.Infra.TreeItems; using System.Xml; using System.Windows; using Kodestruct.Dynamo.UI.Common.TreeItems; using Dynamo.Nodes; using Dynamo.Graph; using Dynamo.Graph.Nodes; using KodestructDynamoUI.Views.Loads.ASCE7; namespace Kodestruct.Loads.ASCE7.General { /// <summary> ///Selection of occupancy for determination of Risk Category /// </summary> [NodeName("Building occupancy ID selection")] [NodeCategory("Kodestruct.Loads.ASCE7.General")] [NodeDescription("Selection of occupancy for determination of Risk Category")] [IsDesignScriptCompatible] public class BuildingOccupancyIdSelection : UiNodeBase { public BuildingOccupancyIdSelection() { ReportEntry=""; BuildingOccupancyDescription ="Commercial building"; BuildingOccupancyId = "Commercial building"; //OutPortData.Add(new PortData("ReportEntry", "Calculation log entries (for reporting)")); OutPortData.Add(new PortData("BuildingOccupancyId", "Occupancy description")); RegisterAllPorts(); //PropertyChanged += NodePropertyChanged; } #region BuildingOccupancyDescription Property private string _BuildingOccupancyDescription; public string BuildingOccupancyDescription { get { return _BuildingOccupancyDescription; } set { _BuildingOccupancyDescription = value; RaisePropertyChanged("BuildingOccupancyDescription"); } } #endregion /// <summary> /// Gets the type of this class, to be used in base class for reflection /// </summary> protected override Type GetModelType() { return GetType(); } #region properties #region InputProperties #endregion #region OutputProperties #region BuildingOccupancyIdProperty /// <summary> /// BuildingOccupancy property /// </summary> /// <value>Occupancy description</value> public string _BuildingOccupancyId; public string BuildingOccupancyId { get { return _BuildingOccupancyId; } set { _BuildingOccupancyId = value; RaisePropertyChanged("BuildingOccupancyId"); OnNodeModified(true); } } #endregion #region ReportEntryProperty /// <summary> /// log property /// </summary> /// <value>Calculation entries that can be converted into a report.</value> public string reportEntry; public string ReportEntry { get { return reportEntry; } set { reportEntry = value; RaisePropertyChanged("ReportEntry"); OnNodeModified(true); } } #endregion #endregion #endregion #region Serialization /// <summary> ///Saves property values to be retained when opening the node /// </summary> protected override void SerializeCore(XmlElement nodeElement, SaveContext context) { base.SerializeCore(nodeElement, context); nodeElement.SetAttribute("BuildingOccupancyId", BuildingOccupancyId); } /// <summary> ///Retrieved property values when opening the node /// </summary> protected override void DeserializeCore(XmlElement nodeElement, SaveContext context) { base.DeserializeCore(nodeElement, context); var attrib = nodeElement.Attributes["BuildingOccupancyId"]; if (attrib == null) return; BuildingOccupancyId = attrib.Value; SetOccupancyDescription(); } public void UpdateSelectionEvents() { if (TreeViewControl != null) { TreeViewControl.SelectedItemChanged += OnTreeViewSelectionChanged; } } private void OnTreeViewSelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { OnSelectedItemChanged(e.NewValue); } private void SetOccupancyDescription() { Uri uri = new Uri("pack://application:,,,/KodestructDynamoUI;component/Views/Loads/ASCE7/General/BuildingOccupancyTreeData.xml"); XmlTreeHelper treeHelper = new XmlTreeHelper(); treeHelper.ExamineXmlTreeFile(uri, new EvaluateXmlNodeDelegate(FindDescription)); } private void FindDescription(XmlNode node) { if (null != node.Attributes["Id"]) { if (node.Attributes["Id"].Value== BuildingOccupancyId) { BuildingOccupancyDescription = node.Attributes["Description"].Value; } } } #endregion #region treeView elements public TreeView TreeViewControl { get; set; } public void DisplayComponentUI(XTreeItem selectedComponent) { } private XTreeItem selectedItem; public XTreeItem SelectedItem { get { return selectedItem; } set { selectedItem = value; } } private void OnSelectedItemChanged(object i) { XmlElement item = i as XmlElement; XTreeItem xtreeItem = new XTreeItem() { Header = item.GetAttribute("Header"), Description = item.GetAttribute("Description"), Id = item.GetAttribute("Id"), ResourcePath = item.GetAttribute("ResourcePath"), Tag = item.GetAttribute("Tag"), TemplateName = item.GetAttribute("TemplateName") }; if (item != null) { string Id = xtreeItem.Id; if (Id != "X") { BuildingOccupancyId = xtreeItem.Id; BuildingOccupancyDescription = xtreeItem.Description; SelectedItem = xtreeItem; DisplayComponentUI(xtreeItem); } } } #endregion //Additional UI is a user control which is based on the user selection // can remove this property #region Additional UI private UserControl additionalUI; public UserControl AdditionalUI { get { return additionalUI; } set { additionalUI = value; RaisePropertyChanged("AdditionalUI"); } } #endregion /// <summary> ///Customization of WPF view in Dynamo UI /// </summary> public class BuildingOccupancyViewCustomization : UiNodeBaseViewCustomization, INodeViewCustomization<BuildingOccupancyIdSelection> { public void CustomizeView(BuildingOccupancyIdSelection model, NodeView nodeView) { base.CustomizeView(model, nodeView); BuildingOccupancyIdView control = new BuildingOccupancyIdView(); control.DataContext = model; TreeView tv = control.FindName("selectionTree") as TreeView; if (tv!=null) { model.TreeViewControl = tv; model.UpdateSelectionEvents(); } nodeView.inputGrid.Children.Add(control); base.CustomizeView(model, nodeView); } } } }
using Lucene.Net.Documents; namespace Lucene.Net.Search { using Lucene.Net.Index; using NUnit.Framework; using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Document = Documents.Document; using Field = Field; using FieldInvertState = Lucene.Net.Index.FieldInvertState; using FloatDocValuesField = FloatDocValuesField; using IndexReader = Lucene.Net.Index.IndexReader; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using PerFieldSimilarityWrapper = Lucene.Net.Search.Similarities.PerFieldSimilarityWrapper; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using Similarity = Lucene.Net.Search.Similarities.Similarity; using Term = Lucene.Net.Index.Term; /// <summary> /// Tests the use of indexdocvalues in scoring. /// /// In the example, a docvalues field is used as a per-document boost (separate from the norm) /// @lucene.experimental /// </summary> [TestFixture] public class TestDocValuesScoring : LuceneTestCase { private const float SCORE_EPSILON = 0.001f; // for comparing floats [Test] public virtual void TestSimple() { Directory dir = NewDirectory(); RandomIndexWriter iw = new RandomIndexWriter(Random(), dir); Document doc = new Document(); Field field = NewTextField("foo", "", Field.Store.NO); doc.Add(field); Field dvField = new FloatDocValuesField("foo_boost", 0.0F); doc.Add(dvField); Field field2 = NewTextField("bar", "", Field.Store.NO); doc.Add(field2); field.StringValue = "quick brown fox"; field2.StringValue = "quick brown fox"; dvField.FloatValue = 2f; // boost x2 iw.AddDocument(doc); field.StringValue = "jumps over lazy brown dog"; field2.StringValue = "jumps over lazy brown dog"; dvField.FloatValue = 4f; // boost x4 iw.AddDocument(doc); IndexReader ir = iw.Reader; iw.Dispose(); // no boosting IndexSearcher searcher1 = NewSearcher(ir, false); Similarity @base = searcher1.Similarity; // boosting IndexSearcher searcher2 = NewSearcher(ir, false); searcher2.Similarity = new PerFieldSimilarityWrapperAnonymousInnerClassHelper(this, field, @base); // in this case, we searched on field "foo". first document should have 2x the score. TermQuery tq = new TermQuery(new Term("foo", "quick")); QueryUtils.Check(Random(), tq, searcher1); QueryUtils.Check(Random(), tq, searcher2); TopDocs noboost = searcher1.Search(tq, 10); TopDocs boost = searcher2.Search(tq, 10); Assert.AreEqual(1, noboost.TotalHits); Assert.AreEqual(1, boost.TotalHits); //System.out.println(searcher2.Explain(tq, boost.ScoreDocs[0].Doc)); Assert.AreEqual(boost.ScoreDocs[0].Score, noboost.ScoreDocs[0].Score * 2f, SCORE_EPSILON); // this query matches only the second document, which should have 4x the score. tq = new TermQuery(new Term("foo", "jumps")); QueryUtils.Check(Random(), tq, searcher1); QueryUtils.Check(Random(), tq, searcher2); noboost = searcher1.Search(tq, 10); boost = searcher2.Search(tq, 10); Assert.AreEqual(1, noboost.TotalHits); Assert.AreEqual(1, boost.TotalHits); Assert.AreEqual(boost.ScoreDocs[0].Score, noboost.ScoreDocs[0].Score * 4f, SCORE_EPSILON); // search on on field bar just for kicks, nothing should happen, since we setup // our sim provider to only use foo_boost for field foo. tq = new TermQuery(new Term("bar", "quick")); QueryUtils.Check(Random(), tq, searcher1); QueryUtils.Check(Random(), tq, searcher2); noboost = searcher1.Search(tq, 10); boost = searcher2.Search(tq, 10); Assert.AreEqual(1, noboost.TotalHits); Assert.AreEqual(1, boost.TotalHits); Assert.AreEqual(boost.ScoreDocs[0].Score, noboost.ScoreDocs[0].Score, SCORE_EPSILON); ir.Dispose(); dir.Dispose(); } private class PerFieldSimilarityWrapperAnonymousInnerClassHelper : PerFieldSimilarityWrapper { private readonly TestDocValuesScoring OuterInstance; private Field Field; private Similarity @base; public PerFieldSimilarityWrapperAnonymousInnerClassHelper(TestDocValuesScoring outerInstance, Field field, Similarity @base) { this.OuterInstance = outerInstance; this.Field = field; this.@base = @base; fooSim = new BoostingSimilarity(@base, "foo_boost"); } internal readonly Similarity fooSim; public override Similarity Get(string field) { return "foo".Equals(field) ? fooSim : @base; } public override float Coord(int overlap, int maxOverlap) { return @base.Coord(overlap, maxOverlap); } public override float QueryNorm(float sumOfSquaredWeights) { return @base.QueryNorm(sumOfSquaredWeights); } } /// <summary> /// Similarity that wraps another similarity and boosts the final score /// according to whats in a docvalues field. /// /// @lucene.experimental /// </summary> internal class BoostingSimilarity : Similarity { internal readonly Similarity Sim; internal readonly string BoostField; public BoostingSimilarity(Similarity sim, string boostField) { this.Sim = sim; this.BoostField = boostField; } public override long ComputeNorm(FieldInvertState state) { return Sim.ComputeNorm(state); } public override SimWeight ComputeWeight(float queryBoost, CollectionStatistics collectionStats, params TermStatistics[] termStats) { return Sim.ComputeWeight(queryBoost, collectionStats, termStats); } public override SimScorer DoSimScorer(SimWeight stats, AtomicReaderContext context) { SimScorer sub = Sim.DoSimScorer(stats, context); FieldCache.Floats values = FieldCache.DEFAULT.GetFloats(context.AtomicReader, BoostField, false); return new SimScorerAnonymousInnerClassHelper(this, sub, values); } private class SimScorerAnonymousInnerClassHelper : SimScorer { private readonly BoostingSimilarity OuterInstance; private SimScorer Sub; private FieldCache.Floats Values; public SimScorerAnonymousInnerClassHelper(BoostingSimilarity outerInstance, SimScorer sub, FieldCache.Floats values) { this.OuterInstance = outerInstance; this.Sub = sub; this.Values = values; } public override float Score(int doc, float freq) { return Values.Get(doc) * Sub.Score(doc, freq); } public override float ComputeSlopFactor(int distance) { return Sub.ComputeSlopFactor(distance); } public override float ComputePayloadFactor(int doc, int start, int end, BytesRef payload) { return Sub.ComputePayloadFactor(doc, start, end, payload); } public override Explanation Explain(int doc, Explanation freq) { Explanation boostExplanation = new Explanation(Values.Get(doc), "indexDocValue(" + OuterInstance.BoostField + ")"); Explanation simExplanation = Sub.Explain(doc, freq); Explanation expl = new Explanation(boostExplanation.Value * simExplanation.Value, "product of:"); expl.AddDetail(boostExplanation); expl.AddDetail(simExplanation); return expl; } } } } }
// Copyright (c) 2011-2013, Eric Maupin // 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 Gablarski nor the names of its // contributors may be used to endorse or promote products // or services derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS // AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Cadenza; using Gablarski.Messages; using Tempest; namespace Gablarski.Server { public class ServerUserHandler : IServerUserHandler { public ServerUserHandler (IGablarskiServerContext context, IServerUserManager manager) { this.context = context; this.Manager = manager; this.context.RegisterMessageHandler<ConnectMessage> (OnConnectMessage); this.context.RegisterMessageHandler<LoginMessage> (OnLoginMessage); this.context.RegisterMessageHandler<JoinMessage> (OnJoinMessage); this.context.RegisterMessageHandler<SetCommentMessage> (OnSetCommentMessage); this.context.RegisterMessageHandler<SetStatusMessage> (OnSetStatusMessage); this.context.RegisterMessageHandler<SetPermissionsMessage> (OnSetPermissionsMessage); this.context.RegisterMessageHandler<KickUserMessage> (OnKickUserMessage); this.context.RegisterMessageHandler<RegisterMessage> (OnRegisterMessage); this.context.RegisterMessageHandler<RegistrationApprovalMessage> (OnRegistrationApprovalMessage); this.context.RegisterMessageHandler<BanUserMessage> (OnBanUserMessage); this.context.RegisterMessageHandler<RequestMuteUserMessage> (OnRequestMuteUserMessage); this.context.RegisterMessageHandler<RequestUserListMessage> (OnRequestUserListMessage); this.context.RegisterMessageHandler<ChannelChangeMessage> (OnChannelChangeMessage); } public IUserInfo this[int userId] { get { return Manager[userId]; } } public IUserInfo this[IConnection connection] { get { return Manager.GetUser (connection); } } public IServerConnection this[IUserInfo user] { get { return (IServerConnection)Manager.GetConnection (user); } } /// <summary> /// Gets the connections for joined users. /// </summary> public IEnumerable<IConnection> Connections { get { return Manager.GetUserConnections(); } } public void ApproveRegistration (string username) { if (username == null) throw new ArgumentNullException ("username"); if (this.context.UserProvider.RegistrationMode != UserRegistrationMode.Approved) throw new NotSupportedException(); this.context.UserProvider.ApproveRegistration (username); } public void ApproveRegistration (IUserInfo user) { if (user == null) throw new ArgumentNullException ("user"); if (this.context.UserProvider.RegistrationMode != UserRegistrationMode.PreApproved) throw new NotSupportedException(); lock (this.approvals) this.approvals.Add (user); } public async Task DisconnectAsync (IConnection connection) { if (connection == null) throw new ArgumentNullException ("connection"); IUserInfo user = Manager.GetUser (connection); Manager.Disconnect (connection); List<Task> tasks = new List<Task>(); if (user != null) { foreach (IConnection c in this.context.Connections) tasks.Add (c.SendAsync (new UserDisconnectedMessage (user.UserId))); } tasks.Add (connection.DisconnectAsync()); await Task.WhenAll (tasks).ConfigureAwait (false); } public void Move (IUserInfo user, IChannelInfo channel) { if (user == null) throw new ArgumentNullException ("user"); if (channel == null) throw new ArgumentNullException ("channel"); int previousChannel = user.CurrentChannelId; if (previousChannel == channel.ChannelId) return; IUserInfo realUser = this[user.UserId]; if (realUser == null) return; IChannelInfo realChannel = context.Channels[channel.ChannelId]; if (realChannel == null) return; var changeInfo = new ChannelChangeInfo (user.UserId, channel.ChannelId, previousChannel); int numUsers = context.Users.Count (u => u.CurrentChannelId == channel.ChannelId); if (channel.UserLimit != 0 && numUsers >= channel.UserLimit) return; Manager.Move (realUser, realChannel); foreach (var connection in Manager.GetConnections()) connection.SendAsync (new UserChangedChannelMessage { ChangeInfo = changeInfo }); } public void Move (IConnection mover, IUserInfo user, IChannelInfo channel) { if (mover == null) throw new ArgumentNullException ("mover"); if (user == null) throw new ArgumentNullException ("user"); if (channel == null) throw new ArgumentNullException ("channel"); IUserInfo movingUser = this.context.Users[mover]; int moverId = (movingUser != null) ? movingUser.UserId : 0; MoveUser (moverId, user.UserId, channel.ChannelId); } public async Task DisconnectAsync (IUserInfo user, DisconnectionReason reason) { if (user == null) throw new ArgumentNullException ("user"); IConnection c = Manager.GetConnection (user); if (c == null) return; Manager.Disconnect (c); if (c.IsConnected) { await c.SendAsync (new DisconnectMessage (reason)).ConfigureAwait (false); await c.DisconnectAsync().ConfigureAwait (false); } List<Task> tasks = new List<Task>(); foreach (IConnection connection in Manager.GetConnections()) tasks.Add (connection.SendAsync (new UserDisconnectedMessage (user.UserId))); await Task.WhenAll (tasks).ConfigureAwait (false); } public IEnumerator<IUserInfo> GetEnumerator() { return Manager.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } internal readonly IServerUserManager Manager; private readonly IGablarskiServerContext context; private readonly HashSet<IUserInfo> approvals = new HashSet<IUserInfo>(); internal void OnConnectMessage (MessageEventArgs<ConnectMessage> e) { var msg = e.Message; if (!msg.Host.IsNullOrWhitespace() && msg.Port != 0) { foreach (var r in this.context.Redirectors) { IPEndPoint redirect = r.CheckRedirect (msg.Host, msg.Port); if (redirect == null) continue; e.Connection.SendAsync (new RedirectMessage { Host = redirect.Address.ToString(), Port = redirect.Port }); return; } } Manager.Connect (e.Connection); SendInfoMessages (e.Connection); } internal void OnJoinMessage (MessageEventArgs<JoinMessage> e) { var join = e.Message; if (!e.Connection.IsConnected) return; if (join.Nickname.IsNullOrWhitespace ()) { e.Connection.SendAsync (new JoinResultMessage (LoginResultState.FailedInvalidNickname, null)); return; } if (!String.IsNullOrEmpty (this.context.Settings.ServerPassword) && join.ServerPassword != this.context.Settings.ServerPassword) { e.Connection.SendAsync (new JoinResultMessage (LoginResultState.FailedServerPassword, null)); return; } IUserInfo info = GetJoiningUserInfo (e.Connection, join); if (info == null) return; LoginResultState result = LoginResultState.Success; if (Manager.GetIsNicknameInUse (join.Nickname)) { if (!AttemptNicknameRecovery (info, join.Nickname)) result = LoginResultState.FailedNicknameInUse; } var msg = new JoinResultMessage (result, info); if (result == LoginResultState.Success) { Manager.Join (e.Connection, info); e.Connection.SendAsync (msg); if (!Manager.GetIsLoggedIn (e.Connection)) e.Connection.SendAsync (new PermissionsMessage (info.UserId, this.context.PermissionsProvider.GetPermissions (info.UserId))); foreach (IConnection connection in this.context.Connections) connection.SendAsync (new UserJoinedMessage (info)); } else e.Connection.SendAsync (msg); } internal void OnLoginMessage (MessageEventArgs<LoginMessage> e) { var login = e.Message; if (login.Username.IsNullOrWhitespace()) { e.Connection.SendAsync (new LoginResultMessage (new LoginResult (0, LoginResultState.FailedUsername))); return; } LoginResult result = this.context.UserProvider.Login (login.Username, login.Password); e.Connection.SendAsync (new LoginResultMessage (result)); if (result.Succeeded) { Manager.Login (e.Connection, new UserInfo (login.Username, result.UserId, this.context.ChannelsProvider.DefaultChannel.ChannelId, false)); e.Connection.SendAsync (new PermissionsMessage (result.UserId, this.context.PermissionsProvider.GetPermissions (result.UserId))); } } internal void OnRequestUserListMessage (MessageEventArgs<RequestUserListMessage> e) { var msg = e.Message; if (msg.Mode == UserListMode.Current) { if (!context.GetPermission (PermissionName.RequestChannelList)) { e.Connection.SendAsync (new PermissionDeniedMessage (GablarskiMessageType.RequestUserList)); return; } e.Connection.SendAsync (new UserInfoListMessage (this)); } else { if (!context.GetPermission (PermissionName.RequestFullUserList)) { e.Connection.SendAsync (new PermissionDeniedMessage (GablarskiMessageType.RequestUserList)); return; } e.Connection.SendAsync (new UserListMessage (context.UserProvider.GetUsers())); } } internal void OnChannelChangeMessage (MessageEventArgs<ChannelChangeMessage> e) { var change = (ChannelChangeMessage)e.Message; IUserInfo requestingUser = this.context.Users[e.Connection]; MoveUser ((requestingUser != null) ? requestingUser.UserId : 0, change.TargetUserId, change.TargetChannelId); } internal void OnRequestMuteUserMessage (MessageEventArgs<RequestMuteUserMessage> e) { var msg = e.Message; if (!context.GetPermission (PermissionName.MuteUser, e.Connection)) { e.Connection.SendAsync (new PermissionDeniedMessage (GablarskiMessageType.RequestMuteUser)); return; } IUserInfo user = Manager.FirstOrDefault (u => u.UserId == msg.TargetId); if (user == null) return; if (user.IsMuted == msg.Unmute) Manager.ToggleMute (user); else return; foreach (IConnection connection in this.context.Connections) connection.SendAsync (new UserMutedMessage { UserId = user.UserId, Unmuted = msg.Unmute }); } internal void OnKickUserMessage (MessageEventArgs<KickUserMessage> e) { var msg = e.Message; var kicker = context.Users[e.Connection]; if (kicker == null) return; if (msg.FromServer && !context.GetPermission (PermissionName.KickPlayerFromServer, e.Connection)) { e.Connection.SendAsync (new PermissionDeniedMessage (GablarskiMessageType.KickUser)); return; } var user = this.context.Users[msg.UserId]; if (user == null) return; if (!msg.FromServer && !context.GetPermission (PermissionName.KickPlayerFromChannel, user.CurrentChannelId, kicker.UserId)) { e.Connection.SendAsync (new PermissionDeniedMessage (GablarskiMessageType.KickUser)); return; } foreach (IUserInfo u in context.Users) { IConnection connection = this.context.Users[u]; if (connection == null) continue; connection.SendAsync (new UserKickedMessage { FromServer = msg.FromServer, UserId = msg.UserId }); } if (msg.FromServer) DisconnectAsync (user, DisconnectionReason.Kicked); else context.Users.Move (user, context.ChannelsProvider.DefaultChannel); } internal void OnSetCommentMessage (MessageEventArgs<SetCommentMessage> e) { var msg = e.Message; IUserInfo user = Manager.GetUser (e.Connection); if (user == null || user.Comment == msg.Comment) return; user = Manager.SetComment (user, msg.Comment); foreach (IConnection connection in Manager.GetConnections()) connection.SendAsync (new UserUpdatedMessage (user)); } internal void OnSetStatusMessage (MessageEventArgs<SetStatusMessage> e) { var msg = e.Message; IUserInfo user = Manager.GetUser (e.Connection); if (user == null || user.Status == msg.Status) return; user = Manager.SetStatus (user, msg.Status); foreach (IConnection connection in Manager.GetConnections()) connection.SendAsync (new UserUpdatedMessage (user)); } internal void OnRegistrationApprovalMessage (MessageEventArgs<RegistrationApprovalMessage> e) { var msg = e.Message; if (!Manager.GetIsConnected (e.Connection)) return; if (!this.context.GetPermission (PermissionName.ApproveRegistrations, e.Connection)) { e.Connection.SendAsync (new PermissionDeniedMessage (GablarskiMessageType.RegistrationApproval)); return; } if (this.context.UserProvider.RegistrationMode == UserRegistrationMode.Approved) { var user = this.context.Users[msg.UserId]; if (user != null) ApproveRegistration (user); } else if (this.context.UserProvider.RegistrationMode == UserRegistrationMode.PreApproved) { if (msg.Username != null) ApproveRegistration (msg.Username); } } internal void OnRegisterMessage (MessageEventArgs<RegisterMessage> e) { var msg = e.Message; if (!Manager.GetIsConnected (e.Connection)) return; if (!this.context.UserProvider.UpdateSupported) { e.Connection.SendAsync (new RegisterResultMessage { Result = RegisterResult.FailedUnsupported }); return; } switch (this.context.UserProvider.RegistrationMode) { case UserRegistrationMode.Approved: case UserRegistrationMode.Normal: break; case UserRegistrationMode.PreApproved: var user = this.context.Users[e.Connection]; if (user == null) return; if (!this.approvals.Remove (user)) { e.Connection.SendAsync (new RegisterResultMessage { Result = RegisterResult.FailedNotApproved }); return; } break; case UserRegistrationMode.Message: case UserRegistrationMode.WebPage: case UserRegistrationMode.None: e.Connection.SendAsync (new RegisterResultMessage { Result = RegisterResult.FailedUnsupported }); return; default: e.Connection.SendAsync (new RegisterResultMessage { Result = RegisterResult.FailedUnknown }); return; } var result = this.context.UserProvider.Register (msg.Username, msg.Password); e.Connection.SendAsync (new RegisterResultMessage { Result = result }); } internal void OnSetPermissionsMessage (MessageEventArgs<SetPermissionsMessage> e) { var msg = e.Message; if (!e.Connection.IsConnected || !context.PermissionsProvider.UpdatedSupported) return; if (!context.GetPermission (PermissionName.ModifyPermissions, e.Connection)) { e.Connection.SendAsync (new PermissionDeniedMessage (GablarskiMessageType.SetPermissions)); return; } var perms = msg.Permissions.ToList(); if (perms.Count == 0) return; context.PermissionsProvider.SetPermissions (msg.UserId, perms); IUserInfo target = Manager[msg.UserId]; if (target == null) return; IConnection c = Manager.GetConnection (target); if (c != null) c.SendAsync (new PermissionsMessage (msg.UserId, context.PermissionsProvider.GetPermissions (msg.UserId))); } internal void OnBanUserMessage (MessageEventArgs<BanUserMessage> e) { var msg = (BanUserMessage)e.Message; if (!Manager.GetIsConnected (e.Connection)) return; if (!context.GetPermission (PermissionName.BanUser, e.Connection)) { e.Connection.SendAsync (new PermissionDeniedMessage (GablarskiMessageType.BanUser)); return; } if (msg.Removing) context.UserProvider.RemoveBan (msg.BanInfo); else context.UserProvider.AddBan (msg.BanInfo); } private IUserInfo GetJoiningUserInfo (IConnection connection, JoinMessage join) { if (!Manager.GetIsConnected (connection)) { connection.SendAsync (new JoinResultMessage (LoginResultState.FailedNotConnected, null)); return null; } IUserInfo info = this.Manager.GetUser (connection); if (info == null) { if (!this.context.Settings.AllowGuestLogins) { connection.SendAsync (new JoinResultMessage (LoginResultState.FailedUsername, null)); return null; } LoginResult r = this.context.UserProvider.Login (join.Nickname, null); if (!r.Succeeded) { connection.SendAsync (new JoinResultMessage (r.ResultState, null)); return null; } info = new UserInfo (join.Nickname, join.Phonetic, join.Nickname, r.UserId, this.context.ChannelsProvider.DefaultChannel.ChannelId, false); } else info = new UserInfo (join.Nickname, join.Phonetic, info); return info; } private void SendInfoMessages (IConnection connection) { connection.SendAsync (new ServerInfoMessage { ServerInfo = new ServerInfo (context.Settings, context.UserProvider) }); connection.SendAsync (new ChannelListMessage (this.context.ChannelsProvider.GetChannels(), this.context.ChannelsProvider.DefaultChannel)); connection.SendAsync (new UserInfoListMessage (Manager)); connection.SendAsync (new SourceListMessage (this.context.Sources)); } /// <returns><c>true</c> if the nickname is now free, <c>false</c> otherwise.</returns> private bool AttemptNicknameRecovery (IUserInfo info, string nickname) { if (info == null) throw new ArgumentNullException ("info"); if (nickname == null) throw new ArgumentNullException ("nickname"); nickname = nickname.ToLower().Trim(); IUserInfo current = Manager.Where (u => u.Nickname != null).Single (u => u.Nickname.ToLower().Trim() == nickname); if (info.IsRegistered && info.UserId == current.UserId) { Manager.Disconnect (current); return true; } return false; } private void MoveUser (int moverId, int userId, int channelId) { IConnection requester = null; IUserInfo requestingUser = (moverId == 0) ? null : this.context.Users[moverId]; if (requestingUser != null) requester = this.context.Users[requestingUser]; IUserInfo user = this.context.Users[userId]; if (user == null) return; ChannelChangeInfo info = (requestingUser != null) ? new ChannelChangeInfo (userId, channelId, user.CurrentChannelId, requestingUser.UserId) : new ChannelChangeInfo (userId, channelId, user.CurrentChannelId); IChannelInfo channel = this.context.Channels[channelId]; if (channel == null) { if (requester != null) requester.SendAsync (new ChannelChangeResultMessage (ChannelChangeResult.FailedUnknownChannel, info)); return; } if (!user.Equals (requestingUser)) { if (!this.context.GetPermission (PermissionName.ChangePlayersChannel, channel.ChannelId, moverId)) { if (requester != null) requester.SendAsync (new ChannelChangeResultMessage (ChannelChangeResult.FailedPermissions, info)); return; } } else if (!this.context.GetPermission (PermissionName.ChangeChannel, channel.ChannelId, user.UserId)) { if (requester != null) requester.SendAsync (new ChannelChangeResultMessage (ChannelChangeResult.FailedPermissions, info)); return; } if (channel.UserLimit != 0 && channel.UserLimit <= context.Users.Count (u => u.CurrentChannelId == channel.ChannelId)) { if (requester != null) requester.SendAsync (new ChannelChangeResultMessage (ChannelChangeResult.FailedFull, info)); return; } Manager.Move (user, channel); foreach (IConnection connection in Manager.GetConnections()) connection.SendAsync (new UserChangedChannelMessage { ChangeInfo = info }); } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using Microsoft.DotNet.PlatformAbstractions; namespace Microsoft.DotNet.Internal.ProjectModel.Utilities { internal static class PathUtility { public static bool IsChildOfDirectory(string dir, string candidate) { if (dir == null) { throw new ArgumentNullException(nameof(dir)); } if (candidate == null) { throw new ArgumentNullException(nameof(candidate)); } dir = Path.GetFullPath(dir); dir = EnsureTrailingSlash(dir); candidate = Path.GetFullPath(candidate); return candidate.StartsWith(dir, StringComparison.OrdinalIgnoreCase); } public static string EnsureTrailingSlash(string path) { return EnsureTrailingCharacter(path, Path.DirectorySeparatorChar); } public static string EnsureTrailingForwardSlash(string path) { return EnsureTrailingCharacter(path, '/'); } private static string EnsureTrailingCharacter(string path, char trailingCharacter) { if (path == null) { throw new ArgumentNullException(nameof(path)); } // if the path is empty, we want to return the original string instead of a single trailing character. if (path.Length == 0 || path[path.Length - 1] == trailingCharacter) { return path; } return path + trailingCharacter; } public static void EnsureParentDirectory(string filePath) { string directory = Path.GetDirectoryName(filePath); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } } /// <summary> /// Returns <paramref name="path2"/> relative to <paramref name="path1"/>, with Path.DirectorySeparatorChar as separator /// </summary> public static string GetRelativePath(string path1, string path2) { return GetRelativePath(path1, path2, Path.DirectorySeparatorChar, includeDirectoryTraversals: true); } /// <summary> /// Returns <paramref name="path2"/> relative to <paramref name="path1"/>, with <c>Path.DirectorySeparatorChar</c> /// as separator but ignoring directory traversals. /// </summary> public static string GetRelativePathIgnoringDirectoryTraversals(string path1, string path2) { return GetRelativePath(path1, path2, Path.DirectorySeparatorChar, false); } /// <summary> /// Returns <paramref name="path2"/> relative to <paramref name="path1"/>, with given path separator /// </summary> public static string GetRelativePath(string path1, string path2, char separator, bool includeDirectoryTraversals) { if (string.IsNullOrEmpty(path1)) { throw new ArgumentException("Path must have a value", nameof(path1)); } if (string.IsNullOrEmpty(path2)) { throw new ArgumentException("Path must have a value", nameof(path2)); } StringComparison compare; if (RuntimeEnvironment.OperatingSystemPlatform == Platform.Windows) { compare = StringComparison.OrdinalIgnoreCase; // check if paths are on the same volume if (!string.Equals(Path.GetPathRoot(path1), Path.GetPathRoot(path2))) { // on different volumes, "relative" path is just path2 return path2; } } else { compare = StringComparison.Ordinal; } var index = 0; var path1Segments = path1.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); var path2Segments = path2.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); // if path1 does not end with / it is assumed the end is not a directory // we will assume that is isn't a directory by ignoring the last split var len1 = path1Segments.Length - 1; var len2 = path2Segments.Length; // find largest common absolute path between both paths var min = Math.Min(len1, len2); while (min > index) { if (!string.Equals(path1Segments[index], path2Segments[index], compare)) { break; } // Handle scenarios where folder and file have same name (only if os supports same name for file and directory) // e.g. /file/name /file/name/app else if ((len1 == index && len2 > index + 1) || (len1 > index && len2 == index + 1)) { break; } ++index; } var path = ""; // check if path2 ends with a non-directory separator and if path1 has the same non-directory at the end if (len1 + 1 == len2 && !string.IsNullOrEmpty(path1Segments[index]) && string.Equals(path1Segments[index], path2Segments[index], compare)) { return path; } if (includeDirectoryTraversals) { for (var i = index; len1 > i; ++i) { path += ".." + separator; } } for (var i = index; len2 - 1 > i; ++i) { path += path2Segments[i] + separator; } // if path2 doesn't end with an empty string it means it ended with a non-directory name, so we add it back if (!string.IsNullOrEmpty(path2Segments[len2 - 1])) { path += path2Segments[len2 - 1]; } return path; } public static string GetAbsolutePath(string basePath, string relativePath) { if (basePath == null) { throw new ArgumentNullException(nameof(basePath)); } if (relativePath == null) { throw new ArgumentNullException(nameof(relativePath)); } Uri resultUri = new Uri(new Uri(basePath), new Uri(relativePath, UriKind.Relative)); return resultUri.LocalPath; } public static string GetDirectoryName(string path) { path = path.TrimEnd(Path.DirectorySeparatorChar); return path.Substring(Path.GetDirectoryName(path).Length).Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); } public static string GetPathWithForwardSlashes(string path) { return path.Replace('\\', '/'); } public static string GetPathWithBackSlashes(string path) { return path.Replace('/', '\\'); } public static string GetPathWithDirectorySeparator(string path) { if (Path.DirectorySeparatorChar == '/') { return GetPathWithForwardSlashes(path); } else { return GetPathWithBackSlashes(path); } } } }
#region Copyright & License // // Copyright 2001-2005 The Apache Software Foundation // // 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.IO; using log4net.Util; using log4net.Util.PatternStringConverters; using log4net.Core; namespace log4net.Util { /// <summary> /// This class implements a patterned string. /// </summary> /// <remarks> /// <para> /// This string has embedded patterns that are resolved and expanded /// when the string is formatted. /// </para> /// <para> /// This class functions similarly to the <see cref="log4net.Layout.PatternLayout"/> /// in that it accepts a pattern and renders it to a string. Unlike the /// <see cref="log4net.Layout.PatternLayout"/> however the <c>PatternString</c> /// does not render the properties of a specific <see cref="LoggingEvent"/> but /// of the process in general. /// </para> /// <para> /// The recognized conversion pattern names are: /// </para> /// <list type="table"> /// <listheader> /// <term>Conversion Pattern Name</term> /// <description>Effect</description> /// </listheader> /// <item> /// <term>appdomain</term> /// <description> /// <para> /// Used to output the friendly name of the current AppDomain. /// </para> /// </description> /// </item> /// <item> /// <term>date</term> /// <description> /// <para> /// Used to output the date of the logging event in the local time zone. /// To output the date in universal time use the <c>%utcdate</c> pattern. /// The date conversion /// specifier may be followed by a <i>date format specifier</i> enclosed /// between braces. For example, <b>%date{HH:mm:ss,fff}</b> or /// <b>%date{dd MMM yyyy HH:mm:ss,fff}</b>. If no date format specifier is /// given then ISO8601 format is /// assumed (<see cref="log4net.DateFormatter.Iso8601DateFormatter"/>). /// </para> /// <para> /// The date format specifier admits the same syntax as the /// time pattern string of the <see cref="DateTime.ToString(string)"/>. /// </para> /// <para> /// For better results it is recommended to use the log4net date /// formatters. These can be specified using one of the strings /// "ABSOLUTE", "DATE" and "ISO8601" for specifying /// <see cref="log4net.DateFormatter.AbsoluteTimeDateFormatter"/>, /// <see cref="log4net.DateFormatter.DateTimeDateFormatter"/> and respectively /// <see cref="log4net.DateFormatter.Iso8601DateFormatter"/>. For example, /// <b>%date{ISO8601}</b> or <b>%date{ABSOLUTE}</b>. /// </para> /// <para> /// These dedicated date formatters perform significantly /// better than <see cref="DateTime.ToString(string)"/>. /// </para> /// </description> /// </item> /// <item> /// <term>env</term> /// <description> /// <para> /// Used to output the a specific environment variable. The key to /// lookup must be specified within braces and directly following the /// pattern specifier, e.g. <b>%env{COMPUTERNAME}</b> would include the value /// of the <c>COMPUTERNAME</c> environment variable. /// </para> /// <para> /// The <c>env</c> pattern is not supported on the .NET Compact Framework. /// </para> /// </description> /// </item> /// <item> /// <term>identity</term> /// <description> /// <para> /// Used to output the user name for the currently active user /// (Principal.Identity.Name). /// </para> /// </description> /// </item> /// <item> /// <term>newline</term> /// <description> /// <para> /// Outputs the platform dependent line separator character or /// characters. /// </para> /// <para> /// This conversion pattern name offers the same performance as using /// non-portable line separator strings such as "\n", or "\r\n". /// Thus, it is the preferred way of specifying a line separator. /// </para> /// </description> /// </item> /// <item> /// <term>processid</term> /// <description> /// <para> /// Used to output the system process ID for the current process. /// </para> /// </description> /// </item> /// <item> /// <term>property</term> /// <description> /// <para> /// Used to output a specific context property. The key to /// lookup must be specified within braces and directly following the /// pattern specifier, e.g. <b>%property{user}</b> would include the value /// from the property that is keyed by the string 'user'. Each property value /// that is to be included in the log must be specified separately. /// Properties are stored in logging contexts. By default /// the <c>log4net:HostName</c> property is set to the name of machine on /// which the event was originally logged. /// </para> /// <para> /// If no key is specified, e.g. <b>%property</b> then all the keys and their /// values are printed in a comma separated list. /// </para> /// <para> /// The properties of an event are combined from a number of different /// contexts. These are listed below in the order in which they are searched. /// </para> /// <list type="definition"> /// <item> /// <term>the thread properties</term> /// <description> /// The <see cref="ThreadContext.Properties"/> that are set on the current /// thread. These properties are shared by all events logged on this thread. /// </description> /// </item> /// <item> /// <term>the global properties</term> /// <description> /// The <see cref="GlobalContext.Properties"/> that are set globally. These /// properties are shared by all the threads in the AppDomain. /// </description> /// </item> /// </list> /// </description> /// </item> /// <item> /// <term>random</term> /// <description> /// <para> /// Used to output a random string of characters. The string is made up of /// uppercase letters and numbers. By default the string is 4 characters long. /// The length of the string can be specified within braces directly following the /// pattern specifier, e.g. <b>%random{8}</b> would output an 8 character string. /// </para> /// </description> /// </item> /// <item> /// <term>username</term> /// <description> /// <para> /// Used to output the WindowsIdentity for the currently /// active user. /// </para> /// </description> /// </item> /// <item> /// <term>utcdate</term> /// <description> /// <para> /// Used to output the date of the logging event in universal time. /// The date conversion /// specifier may be followed by a <i>date format specifier</i> enclosed /// between braces. For example, <b>%utcdate{HH:mm:ss,fff}</b> or /// <b>%utcdate{dd MMM yyyy HH:mm:ss,fff}</b>. If no date format specifier is /// given then ISO8601 format is /// assumed (<see cref="log4net.DateFormatter.Iso8601DateFormatter"/>). /// </para> /// <para> /// The date format specifier admits the same syntax as the /// time pattern string of the <see cref="DateTime.ToString(string)"/>. /// </para> /// <para> /// For better results it is recommended to use the log4net date /// formatters. These can be specified using one of the strings /// "ABSOLUTE", "DATE" and "ISO8601" for specifying /// <see cref="log4net.DateFormatter.AbsoluteTimeDateFormatter"/>, /// <see cref="log4net.DateFormatter.DateTimeDateFormatter"/> and respectively /// <see cref="log4net.DateFormatter.Iso8601DateFormatter"/>. For example, /// <b>%utcdate{ISO8601}</b> or <b>%utcdate{ABSOLUTE}</b>. /// </para> /// <para> /// These dedicated date formatters perform significantly /// better than <see cref="DateTime.ToString(string)"/>. /// </para> /// </description> /// </item> /// <item> /// <term>%</term> /// <description> /// <para> /// The sequence %% outputs a single percent sign. /// </para> /// </description> /// </item> /// </list> /// <para> /// Additional pattern converters may be registered with a specific <see cref="PatternString"/> /// instance using <see cref="AddConverter(PatternString.ConverterInfo)"/> or /// <see cref="AddConverter(string, Type)" />. /// </para> /// <para> /// See the <see cref="log4net.Layout.PatternLayout"/> for details on the /// <i>format modifiers</i> supported by the patterns. /// </para> /// </remarks> /// <author>Nicko Cadell</author> public class PatternString : IOptionHandler { #region Static Fields /// <summary> /// Internal map of converter identifiers to converter types. /// </summary> private static Hashtable s_globalRulesRegistry; #endregion Static Fields #region Member Variables /// <summary> /// the pattern /// </summary> private string m_pattern; /// <summary> /// the head of the pattern converter chain /// </summary> private PatternConverter m_head; /// <summary> /// patterns defined on this PatternString only /// </summary> private Hashtable m_instanceRulesRegistry = new Hashtable(); #endregion #region Static Constructor /// <summary> /// Initialize the global registry /// </summary> static PatternString() { s_globalRulesRegistry = new Hashtable(15); s_globalRulesRegistry.Add("appdomain", typeof(AppDomainPatternConverter)); s_globalRulesRegistry.Add("date", typeof(DatePatternConverter)); #if !NETCF s_globalRulesRegistry.Add("env", typeof(EnvironmentPatternConverter)); #endif s_globalRulesRegistry.Add("identity", typeof(IdentityPatternConverter)); s_globalRulesRegistry.Add("literal", typeof(LiteralPatternConverter)); s_globalRulesRegistry.Add("newline", typeof(NewLinePatternConverter)); s_globalRulesRegistry.Add("processid", typeof(ProcessIdPatternConverter)); s_globalRulesRegistry.Add("property", typeof(PropertyPatternConverter)); s_globalRulesRegistry.Add("random", typeof(RandomStringPatternConverter)); s_globalRulesRegistry.Add("username", typeof(UserNamePatternConverter)); s_globalRulesRegistry.Add("utcdate", typeof(UtcDatePatternConverter)); s_globalRulesRegistry.Add("utcDate", typeof(UtcDatePatternConverter)); s_globalRulesRegistry.Add("UtcDate", typeof(UtcDatePatternConverter)); } #endregion Static Constructor #region Constructors /// <summary> /// Default constructor /// </summary> /// <remarks> /// <para> /// Initialize a new instance of <see cref="PatternString"/> /// </para> /// </remarks> public PatternString() { } /// <summary> /// Constructs a PatternString /// </summary> /// <param name="pattern">The pattern to use with this PatternString</param> /// <remarks> /// <para> /// Initialize a new instance of <see cref="PatternString"/> with the pattern specified. /// </para> /// </remarks> public PatternString(string pattern) { m_pattern = pattern; ActivateOptions(); } #endregion /// <summary> /// Gets or sets the pattern formatting string /// </summary> /// <value> /// The pattern formatting string /// </value> /// <remarks> /// <para> /// The <b>ConversionPattern</b> option. This is the string which /// controls formatting and consists of a mix of literal content and /// conversion specifiers. /// </para> /// </remarks> public string ConversionPattern { get { return m_pattern; } set { m_pattern = value; } } #region Implementation of IOptionHandler /// <summary> /// Initialize object options /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// </remarks> virtual public void ActivateOptions() { m_head = CreatePatternParser(m_pattern).Parse(); } #endregion /// <summary> /// Create the <see cref="PatternParser"/> used to parse the pattern /// </summary> /// <param name="pattern">the pattern to parse</param> /// <returns>The <see cref="PatternParser"/></returns> /// <remarks> /// <para> /// Returns PatternParser used to parse the conversion string. Subclasses /// may override this to return a subclass of PatternParser which recognize /// custom conversion pattern name. /// </para> /// </remarks> private PatternParser CreatePatternParser(string pattern) { PatternParser patternParser = new PatternParser(pattern); // Add all the builtin patterns foreach(DictionaryEntry entry in s_globalRulesRegistry) { patternParser.PatternConverters.Add(entry.Key, entry.Value); } // Add the instance patterns foreach(DictionaryEntry entry in m_instanceRulesRegistry) { patternParser.PatternConverters[entry.Key] = entry.Value; } return patternParser; } /// <summary> /// Produces a formatted string as specified by the conversion pattern. /// </summary> /// <param name="writer">The TextWriter to write the formatted event to</param> /// <remarks> /// <para> /// Format the pattern to the <paramref name="writer"/>. /// </para> /// </remarks> public void Format(TextWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } PatternConverter c = m_head; // loop through the chain of pattern converters while(c != null) { c.Format(writer, null); c = c.Next; } } /// <summary> /// Format the pattern as a string /// </summary> /// <returns>the pattern formatted as a string</returns> /// <remarks> /// <para> /// Format the pattern to a string. /// </para> /// </remarks> public string Format() { StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); Format(writer); return writer.ToString(); } /// <summary> /// Add a converter to this PatternString /// </summary> /// <param name="converterInfo">the converter info</param> /// <remarks> /// <para> /// This version of the method is used by the configurator. /// Programmatic users should use the alternative <see cref="AddConverter(string,Type)"/> method. /// </para> /// </remarks> public void AddConverter(ConverterInfo converterInfo) { AddConverter(converterInfo.Name, converterInfo.Type); } /// <summary> /// Add a converter to this PatternString /// </summary> /// <param name="name">the name of the conversion pattern for this converter</param> /// <param name="type">the type of the converter</param> /// <remarks> /// <para> /// Add a converter to this PatternString /// </para> /// </remarks> public void AddConverter(string name, Type type) { if (name == null) throw new ArgumentNullException("name"); if (type == null) throw new ArgumentNullException("type"); if (!typeof(PatternConverter).IsAssignableFrom(type)) { throw new ArgumentException("The converter type specified ["+type+"] must be a subclass of log4net.Util.PatternConverter", "type"); } m_instanceRulesRegistry[name] = type; } /// <summary> /// Wrapper class used to map converter names to converter types /// </summary> /// <remarks> /// <para> /// Wrapper class used to map converter names to converter types /// </para> /// </remarks> public sealed class ConverterInfo { private string m_name; private Type m_type; /// <summary> /// default constructor /// </summary> public ConverterInfo() { } /// <summary> /// Gets or sets the name of the conversion pattern /// </summary> /// <value> /// The name of the conversion pattern /// </value> /// <remarks> /// <para> /// Gets or sets the name of the conversion pattern /// </para> /// </remarks> public string Name { get { return m_name; } set { m_name = value; } } /// <summary> /// Gets or sets the type of the converter /// </summary> /// <value> /// The type of the converter /// </value> /// <remarks> /// <para> /// Gets or sets the type of the converter /// </para> /// </remarks> public Type Type { get { return m_type; } set { m_type = value; } } } } }
// Copyright 2006-2008 Splicer Project - http://www.codeplex.com/splicer/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Threading; using System.Xml; using DirectShowLib; using DirectShowLib.DES; using Splicer.Properties; using Splicer.Timeline; using Splicer.Utilities; namespace Splicer.Renderer { public enum RendererState { Initializing, Initialized, GraphStarted, GraphCompleting, GraphCompleted, Cancelling, Canceled } public abstract class AbstractRenderer : IRenderer { private const string DestinationParameterName = "destination"; private const string GraphBuilderParameterName = "graphBuilder"; private const string PinParameterName = "pin"; private const string TimelineParameterName = "timeline"; /// <summary> /// The first audio group, or null if no audio /// </summary> private readonly IGroup _firstAudioGroup; /// <summary> /// the first video group, or null if no video /// </summary> private readonly IGroup _firstVideoGroup; private readonly object _renderLock = new object(); /// <summary> /// Object we lock against to avoid cross-thread problems with setting state. /// </summary> private readonly object _stateLock = new object(); private RendererAsyncResult _cancelResult; /// <summary> /// Handles cleanup of objects we aren't retaining references to /// </summary> private DisposalCleanup _cleanup = new DisposalCleanup(); /// <summary> /// IGraphBuilder object for the timeline /// </summary> private IGraphBuilder _graph; /// <summary> /// Media control interface from _graph /// </summary> private IMediaControl _mediaControl; /// <summary> /// The engine to process the timeline (can't be released /// until the graph processing is complete) /// </summary> private IRenderEngine _renderEngine; private RendererAsyncResult _renderResult; /// <summary> /// the state of the renderer /// </summary> private RendererState _state = RendererState.Initializing; /// <summary> /// The timeline this class will render into a graph /// </summary> private ITimeline _timeline; protected AbstractRenderer(ITimeline timeline) { if (timeline == null) throw new ArgumentNullException(TimelineParameterName); _timeline = timeline; int hr = 0; // create the render engine _renderEngine = (IRenderEngine) new RenderEngine(); _cleanup.Add(_renderEngine); // tell the render engine about the timeline it should use hr = _renderEngine.SetTimelineObject(_timeline.DesTimeline); DESError.ThrowExceptionForHR(hr); // connect up the front end hr = _renderEngine.ConnectFrontEnd(); DESError.ThrowExceptionForHR(hr); // Get the filtergraph - used all over the place hr = _renderEngine.GetFilterGraph(out _graph); _cleanup.Add(Graph); DESError.ThrowExceptionForHR(hr); // find the first (and usually last) audio and video group, we use these // when rendering to track progress _firstAudioGroup = _timeline.FindFirstGroupOfType(GroupType.Audio); _firstVideoGroup = _timeline.FindFirstGroupOfType(GroupType.Video); } protected IRenderEngine RenderEngine { get { return _renderEngine; } } protected IGroup FirstVideoGroup { get { return _firstVideoGroup; } } protected IGroup FirstAudioGroup { get { return _firstAudioGroup; } } protected DisposalCleanup Cleanup { get { return _cleanup; } } protected ITimeline Timeline { get { return _timeline; } } /// <summary> /// IGraphBuilder object for the timeline /// </summary> protected IGraphBuilder Graph { get { return _graph; } } #region IRenderer Members public RendererState State { get { return _state; } } public event EventHandler RenderCompleted { add { _renderCompleted += value; } remove { _renderCompleted -= value; } } /// <summary> /// Returns an XML description of the capture graph (as seen by DES). /// </summary> /// <remarks> /// Might be useful for debugging, handy for implementing some unit tests (where you /// want to make sure changes to implementation don't alter the expected DES capture graph). /// </remarks> /// <returns>String containing XML</returns> [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)] public string ToXml() { IXml2Dex pXML; string sRet; int hr; pXML = (IXml2Dex) new Xml2Dex(); try { hr = pXML.WriteXML(_timeline.DesTimeline, out sRet); DESError.ThrowExceptionForHR(hr); } finally { Marshal.ReleaseComObject(pXML); } // the xml sometimes contains strange characters, so we "normalize" it // on the way out return NormalizeXml(sRet); } [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)] public void SaveToGraphFile(string fileName) { FilterGraphTools.SaveGraphFile(Graph, fileName); } /// <summary> /// Begins rendering and returns immediately. /// </summary> /// <remarks> /// Final status is sent as a <see cref="AbstractRenderer.RenderCompleted"/> event. /// </remarks> public IAsyncResult BeginRender(AsyncCallback callback, object state) { lock (_renderLock) { if ((_renderResult != null) && (_renderResult.Consumed)) { throw new SplicerException(Resources.ErrorPreviousRenderRequestInProgress); } ChangeState(RendererState.GraphStarted); _renderResult = new RendererAsyncResult(callback, state); _cancelResult = null; StartRender(); return _renderResult; } } public void Render() { IAsyncResult result = BeginRender(null, null); EndRender(result); } public void Cancel() { IAsyncResult result = BeginCancel(null, null); EndCancel(result); } public IAsyncResult BeginCancel(AsyncCallback callback, object state) { lock (_renderLock) { if ((_cancelResult != null) && (!_cancelResult.Consumed)) { throw new SplicerException(Resources.ErrorAttemptToCancelWhenCancelInProgress); } else if (_state < RendererState.GraphStarted) { throw new SplicerException(Resources.ErrorGraphNotYetStarted); } else if (_state >= RendererState.GraphCompleting) { throw new SplicerException(Resources.ErrorAttemptToCancelWhenCancelingOrCompleting); } ChangeState(RendererState.GraphStarted, RendererState.Cancelling); _cancelResult = new RendererAsyncResult(callback, state); return _cancelResult; } } public void EndCancel(IAsyncResult result) { lock (_renderLock) { if (_cancelResult != null) { if (_cancelResult != result) { throw new SplicerException(Resources.ErrorAsyncResultNotIssuesByThisInstance); } if (_cancelResult.Consumed) { throw new SplicerException(Resources.ErrorEndCancelAlreadyCalledForAsyncResult); } _cancelResult.AsyncWaitHandle.WaitOne(); _cancelResult.Consume(); if (_cancelResult.Exception != null) { throw new SplicerException(Resources.ErrorExceptionOccuredDuringCancelRenderRequest, _cancelResult.Exception); } _cancelResult = null; } else { throw new SplicerException(Resources.ErrorMustCallBeginCancelBeforeEndCancel); } } } public void EndRender(IAsyncResult result) { lock (_renderLock) { if (_renderResult != null) { if (_renderResult != result) { throw new SplicerException(Resources.ErrorAsyncResultNotIssuesByThisInstance); } if (_renderResult.Consumed) { throw new SplicerException(Resources.ErrorEndRenderAlreadyCalledForAsyncResult); } _renderResult.AsyncWaitHandle.WaitOne(); _renderResult.Consume(); if (_renderResult.Exception != null) { throw new SplicerException(Resources.ErrorExceptionOccuredDuringRenderRequest, _cancelResult.Exception); } else if (_renderResult.Canceled) { throw new SplicerException(Resources.ErrorRenderRequestCanceledByUser); } } else { throw new SplicerException(Resources.ErrorMustCallBeginRenderBeforeEndRender); } } } #endregion private event EventHandler _renderCompleted; protected void OnRenderCompleted() { if (_renderCompleted != null) { _renderCompleted(this, EventArgs.Empty); } } private static string NormalizeXml(string input) { input = input.Substring(input.IndexOf('<')).Substring(0, input.LastIndexOf('>')); var doc = new XmlDocument(); doc.LoadXml(input); return doc.OuterXml; } [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] protected virtual void DisposeRenderer(bool disposing) { if (disposing) { if (_cleanup != null) { (_cleanup).Dispose(); _cleanup = null; } if (_timeline != null) { _timeline.Dispose(); _timeline = null; } } if (_renderEngine != null) { Marshal.ReleaseComObject(_renderEngine); _renderEngine = null; } if (_mediaControl != null) { Marshal.ReleaseComObject(_mediaControl); _mediaControl = null; } if (Graph != null) { Marshal.ReleaseComObject(Graph); _graph = null; } } /// <summary> /// Common routine used by RenderTo* /// </summary> /// <param name="graphBuilder">ICaptureGraphBuilder2 to use</param> /// <param name="callback">Callback to use (or null)</param> /// <param name="typeName">string to use in creating filter graph object descriptions</param> /// <param name="pin">Pin to connect from</param> /// <param name="compressor">Compressor to use, or null for none</param> /// <param name="destination">Endpoint (renderer or file writer) to connect to</param> [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] protected void RenderHelper(ICaptureGraphBuilder2 graphBuilder, ISampleGrabberCB callback, string typeName, IPin pin, IBaseFilter compressor, IBaseFilter destination) { if (graphBuilder == null) throw new ArgumentNullException(GraphBuilderParameterName); if (pin == null) throw new ArgumentNullException(PinParameterName); if (destination == null) throw new ArgumentNullException(DestinationParameterName); int hr; IBaseFilter ibfSampleGrabber = null; try { // If no callback was provided, don't create a samplegrabber if (callback != null) { var isg = (ISampleGrabber) new SampleGrabber(); ibfSampleGrabber = (IBaseFilter) isg; _cleanup.Add(ibfSampleGrabber); hr = isg.SetCallback(callback, 1); DESError.ThrowExceptionForHR(hr); hr = Graph.AddFilter(ibfSampleGrabber, typeName + " sample grabber"); DESError.ThrowExceptionForHR(hr); } // If a compressor was provided, add it to the graph and connect it up if (compressor != null) { // Connect the pin. hr = Graph.AddFilter(compressor, typeName + " Compressor"); DESError.ThrowExceptionForHR(hr); FilterGraphTools.ConnectFilters(Graph, pin, ibfSampleGrabber, true); FilterGraphTools.ConnectFilters(Graph, ibfSampleGrabber, compressor, true); FilterGraphTools.ConnectFilters(Graph, compressor, destination, true); } else { // Just connect the SampleGrabber (if any) hr = graphBuilder.RenderStream(null, null, pin, ibfSampleGrabber, destination); DESError.ThrowExceptionForHR(hr); } } finally { if (ibfSampleGrabber != null) { Marshal.ReleaseComObject(ibfSampleGrabber); } } } /// <summary> /// Called from RenderWindow to add the renderer to the graph, create a sample grabber, add it /// to the graph and connect it all up /// </summary> /// <param name="graphBuilder">ICaptureGraphBuilder2 to use</param> /// <param name="callback">ICaptureGraphBuilder2 to use</param> /// <param name="typeName">String to use in creating filter graph object descriptions</param> /// <param name="pin">Pin to connect from</param> /// <param name="renderer">Renderer to add</param> [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] protected void RenderWindowHelper(ICaptureGraphBuilder2 graphBuilder, ISampleGrabberCB callback, string typeName, IPin pin, IBaseFilter renderer) { int hr; // Add the renderer to the graph hr = Graph.AddFilter(renderer, typeName + " Renderer"); _cleanup.Add(renderer); DESError.ThrowExceptionForHR(hr); // Do everything else RenderHelper(graphBuilder, callback, typeName, pin, null, renderer); } [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] protected void RenderGroups(ICaptureGraphBuilder2 graphBuilder, IBaseFilter audioCompressor, IBaseFilter videoCompressor, IBaseFilter multiplexer, ICallbackParticipant[] audioParticipants, ICallbackParticipant[] videoParticipants) { RenderGroups(graphBuilder, audioCompressor, videoCompressor, multiplexer, multiplexer, audioParticipants, videoParticipants); } [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] protected void RenderGroups(ICaptureGraphBuilder2 graphBuilder, IBaseFilter audioCompressor, IBaseFilter videoCompressor, IBaseFilter audioDestination, IBaseFilter videoDestination, ICallbackParticipant[] audioParticipants, ICallbackParticipant[] videoParticipants) { int hr = 0; if (audioCompressor != null) _cleanup.Add(audioCompressor); if (videoCompressor != null) _cleanup.Add(videoCompressor); if (audioDestination != null) _cleanup.Add(audioDestination); if ((videoDestination != null) && (audioDestination != videoDestination)) _cleanup.Add(videoDestination); IAMTimeline desTimeline = _timeline.DesTimeline; int groupCount; hr = desTimeline.GetGroupCount(out groupCount); DESError.ThrowExceptionForHR(hr); // Walk the groups. For this class, there is one group that // contains all the video, and a second group for the audio. for (int i = (groupCount - 1); i >= 0; i--) { IAMTimelineObj group; hr = desTimeline.GetGroup(out group, i); DESError.ThrowExceptionForHR(hr); try { // Inform the graph we will be writing to disk (rather than previewing) var timelineGroup = (IAMTimelineGroup) group; hr = timelineGroup.SetPreviewMode(false); DESError.ThrowExceptionForHR(hr); } finally { Marshal.ReleaseComObject(group); } IPin pPin; // Get the IPin for the current group hr = _renderEngine.GetGroupOutputPin(i, out pPin); _cleanup.Add(pPin); DESError.ThrowExceptionForHR(hr); try { if (FilterGraphTools.IsVideo(pPin)) { // Create a sample grabber, add it to the graph and connect it all up var mcb = new CallbackHandler(videoParticipants); RenderHelper(graphBuilder, mcb, "Video", pPin, videoCompressor, videoDestination); } else { // Create a sample grabber, add it to the graph and connect it all up var mcb = new CallbackHandler(audioParticipants); RenderHelper(graphBuilder, mcb, "Audio", pPin, audioCompressor, audioDestination); } } finally { Marshal.ReleaseComObject(pPin); } } } private void StartRender() { int hr; _mediaControl = (IMediaControl) Graph; _cleanup.Add(_mediaControl); var eventThread = new Thread(EventWait); eventThread.Name = Resources.MediaEventThreadName; eventThread.Start(); hr = _mediaControl.Run(); DESError.ThrowExceptionForHR(hr); } /// <summary> /// Called on a new thread to process events from the graph. The thread /// exits when the graph finishes. Cancelling is done here. /// </summary> private void EventWait() { try { // Returned when GetEvent is called but there are no events const int E_ABORT = unchecked((int) 0x80004004); int hr; IntPtr p1, p2; EventCode ec; // TODO: present the event code in the OnCompleted event EventCode exitCode; var pEvent = (IMediaEvent) Graph; do { // Read the event for ( hr = pEvent.GetEvent(out ec, out p1, out p2, 100); hr >= 0 && _state < RendererState.GraphCompleted; hr = pEvent.GetEvent(out ec, out p1, out p2, 100) ) { switch (ec) { // If the clip is finished playing case EventCode.Complete: case EventCode.ErrorAbort: ChangeState(RendererState.GraphStarted, RendererState.GraphCompleting); exitCode = ec; // Release any resources the message allocated hr = pEvent.FreeEventParams(ec, p1, p2); DESError.ThrowExceptionForHR(hr); break; default: // Release any resources the message allocated hr = pEvent.FreeEventParams(ec, p1, p2); DESError.ThrowExceptionForHR(hr); break; } } // If the error that exited the loop wasn't due to running out of events if (hr != E_ABORT) { DESError.ThrowExceptionForHR(hr); } } while (_state < RendererState.GraphCompleting); // If the user canceled if (_state == RendererState.Cancelling) { // Stop the graph, send an appropriate exit code hr = _mediaControl.Stop(); exitCode = EventCode.UserAbort; } if (_state == RendererState.GraphCompleting) { ChangeState(RendererState.GraphCompleted); OnRenderCompleted(); if (_renderResult != null) _renderResult.Complete(false); if (_cancelResult != null) _cancelResult.Complete(false); } else { ChangeState(RendererState.Canceled); OnRenderCompleted(); if (_renderResult != null) _renderResult.Complete(true); if (_cancelResult != null) _cancelResult.Complete(false); } } catch (COMException ex) { if (_renderResult != null) _renderResult.Complete(ex); if (_cancelResult != null) _cancelResult.Complete(ex); } } protected void ChangeState(RendererState newState) { lock (_stateLock) { _state = newState; } } protected void ChangeState(RendererState expectedState, RendererState newState) { lock (_stateLock) { if (_state == expectedState) { _state = newState; } } } protected void DisableClock() { int hr = ((IMediaFilter) Graph).SetSyncSource(null); DsError.ThrowExceptionForHR(hr); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace PartyHubAPI.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Threading; using System.Threading.Tasks; namespace System.Net.Sockets { // The System.Net.Sockets.TcpClient class provide TCP services at a higher level // of abstraction than the System.Net.Sockets.Socket class. System.Net.Sockets.TcpClient // is used to create a Client connection to a remote host. public class TcpClient : IDisposable { private Socket _clientSocket; private bool _active; private NetworkStream _dataStream; // IPv6: Maintain address family for the client. private AddressFamily _family = AddressFamily.InterNetwork; // Initializes a new instance of the System.Net.Sockets.TcpClient class. public TcpClient() : this(AddressFamily.InterNetwork) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "TcpClient", null); } if (Logging.On) { Logging.Exit(Logging.Sockets, this, "TcpClient", null); } } // Initializes a new instance of the System.Net.Sockets.TcpClient class. public TcpClient(AddressFamily family) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "TcpClient", family); } // Validate parameter if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6) { throw new ArgumentException(SR.Format(SR.net_protocol_invalid_family, "TCP"), "family"); } _family = family; initialize(); if (Logging.On) { Logging.Exit(Logging.Sockets, this, "TcpClient", null); } } // Used by TcpListener.Accept(). internal TcpClient(Socket acceptedSocket) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "TcpClient", acceptedSocket); } Client = acceptedSocket; _active = true; if (Logging.On) { Logging.Exit(Logging.Sockets, this, "TcpClient", null); } } // Used by the class to provide the underlying network socket. public Socket Client { get { return _clientSocket; } set { _clientSocket = value; } } // Used by the class to indicate that a connection has been made. protected bool Active { get { return _active; } set { _active = value; } } public int Available { get { return _clientSocket.Available; } } public bool Connected { get { return _clientSocket.Connected; } } public bool ExclusiveAddressUse { get { return _clientSocket.ExclusiveAddressUse; } set { _clientSocket.ExclusiveAddressUse = value; } } internal IAsyncResult BeginConnect(string host, int port, AsyncCallback requestCallback, object state) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "BeginConnect", host); } IAsyncResult result = Client.BeginConnect(host, port, requestCallback, state); if (Logging.On) { Logging.Exit(Logging.Sockets, this, "BeginConnect", null); } return result; } internal IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "BeginConnect", address); } IAsyncResult result = Client.BeginConnect(address, port, requestCallback, state); if (Logging.On) { Logging.Exit(Logging.Sockets, this, "BeginConnect", null); } return result; } internal IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback requestCallback, object state) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "BeginConnect", addresses); } IAsyncResult result = Client.BeginConnect(addresses, port, requestCallback, state); if (Logging.On) { Logging.Exit(Logging.Sockets, this, "BeginConnect", null); } return result; } internal void EndConnect(IAsyncResult asyncResult) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "EndConnect", asyncResult); } Client.EndConnect(asyncResult); _active = true; if (Logging.On) { Logging.Exit(Logging.Sockets, this, "EndConnect", null); } } public Task ConnectAsync(IPAddress address, int port) { return Task.Factory.FromAsync( (targetAddess, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetAddess, targetPort, callback, state), asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult), address, port, state: this); } public Task ConnectAsync(string host, int port) { return Task.Factory.FromAsync( (targetHost, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetHost, targetPort, callback, state), asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult), host, port, state: this); } public Task ConnectAsync(IPAddress[] addresses, int port) { return Task.Factory.FromAsync( (targetAddresses, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetAddresses, targetPort, callback, state), asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult), addresses, port, state: this); } // Returns the stream used to read and write data to the remote host. public NetworkStream GetStream() { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "GetStream", ""); } if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!Client.Connected) { throw new InvalidOperationException(SR.net_notconnected); } if (_dataStream == null) { _dataStream = new NetworkStream(Client, true); } if (Logging.On) { Logging.Exit(Logging.Sockets, this, "GetStream", _dataStream); } return _dataStream; } private bool _cleanedUp = false; // Disposes the Tcp connection. protected virtual void Dispose(bool disposing) { if (Logging.On) { Logging.Enter(Logging.Sockets, this, "Dispose", ""); } if (_cleanedUp) { if (Logging.On) { Logging.Exit(Logging.Sockets, this, "Dispose", ""); } return; } if (disposing) { IDisposable dataStream = _dataStream; if (dataStream != null) { dataStream.Dispose(); } else { // If the NetworkStream wasn't created, the Socket might // still be there and needs to be closed. In the case in which // we are bound to a local IPEndPoint this will remove the // binding and free up the IPEndPoint for later uses. Socket chkClientSocket = Client; if (chkClientSocket != null) { try { chkClientSocket.InternalShutdown(SocketShutdown.Both); } finally { chkClientSocket.Dispose(); Client = null; } } } GC.SuppressFinalize(this); } _cleanedUp = true; if (Logging.On) { Logging.Exit(Logging.Sockets, this, "Dispose", ""); } } public void Dispose() { Dispose(true); } ~TcpClient() { #if DEBUG GlobalLog.SetThreadSource(ThreadKinds.Finalization); using (GlobalLog.SetThreadKind(ThreadKinds.System | ThreadKinds.Async)) { #endif Dispose(false); #if DEBUG } #endif } // Gets or sets the size of the receive buffer in bytes. public int ReceiveBufferSize { get { return numericOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer); } set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value); } } // Gets or sets the size of the send buffer in bytes. public int SendBufferSize { get { return numericOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer); } set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, value); } } // Gets or sets the receive time out value of the connection in milliseconds. public int ReceiveTimeout { get { return numericOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); } set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, value); } } // Gets or sets the send time out value of the connection in milliseconds. public int SendTimeout { get { return numericOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout); } set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, value); } } // Gets or sets the value of the connection's linger option. public LingerOption LingerState { get { return (LingerOption)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger); } set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, value); } } // Enables or disables delay when send or receive buffers are full. public bool NoDelay { get { return numericOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay) != 0 ? true : false; } set { Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, value ? 1 : 0); } } private void initialize() { // IPv6: Use the address family from the constructor (or Connect method). Client = new Socket(_family, SocketType.Stream, ProtocolType.Tcp); _active = false; } private int numericOption(SocketOptionLevel optionLevel, SocketOptionName optionName) { return (int)Client.GetSocketOption(optionLevel, optionName); } } }
// // RSAOAEPKeyExchangeDeformatterTest.cs - NUnit Test Cases for RSAOAEPKeyExchangeDeformatter // // Author: // Sebastien Pouliot ([email protected]) // // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using NUnit.Framework; using System; using System.Security.Cryptography; namespace MonoTests.System.Security.Cryptography { [TestFixture] public class RSAOAEPKeyExchangeDeformatterTest : Assertion { protected static RSA key; [SetUp] public void SetUp () { // generating a keypair is REALLY long and the framework // makes sure that we generate one (even if create an object // to import an existing key) if (key == null) { key = RSA.Create (); key.ImportParameters (AllTests.GetRsaKey (true)); } } public void AssertEquals (string msg, byte[] array1, byte[] array2) { AllTests.AssertEquals (msg, array1, array2); } // LAMESPEC: RSAOAEPKeyExchangeDeformatter.RNG versus RSAOAEPKeyExchangeFormatter.Rng [Test] public void Properties () { RSAOAEPKeyExchangeDeformatter keyex = new RSAOAEPKeyExchangeDeformatter (); keyex.SetKey (key); Assertion.AssertNull("RSAOAEPKeyExchangeDeformatter.Parameters", keyex.Parameters); Assertion.AssertEquals("RSAOAEPKeyExchangeDeformatter.ToString()", "System.Security.Cryptography.RSAOAEPKeyExchangeDeformatter", keyex.ToString ()); } // TestExchangeMin (1) // Test vector (EM) generated by CryptoAPI on Windows XP [Test] public void CapiExchangeMin () { byte[] M = { 0x01 }; byte[] EM = { 0x4D, 0x5F, 0x26, 0x67, 0x88, 0x07, 0xF1, 0xB5, 0x85, 0x33, 0xDA, 0x8B, 0xD6, 0x9E, 0x9B, 0x56, 0xE6, 0x54, 0x49, 0xF3, 0x4A, 0x8B, 0x5B, 0xB2, 0xCB, 0x10, 0x50, 0x91, 0x85, 0xBC, 0xE1, 0x5E, 0xDC, 0x8A, 0xAE, 0x63, 0xAD, 0x57, 0xC3, 0x03, 0x78, 0xDD, 0xCE, 0xCD, 0x46, 0x71, 0x43, 0x2F, 0x7F, 0xA4, 0x6A, 0x93, 0xE4, 0xB7, 0x4C, 0x36, 0x92, 0x5C, 0xFF, 0xAC, 0x32, 0xE8, 0x71, 0x1E, 0x69, 0xD6, 0x8C, 0xB5, 0x65, 0xA5, 0x83, 0xC2, 0x3F, 0xED, 0x35, 0x6F, 0x03, 0x0D, 0x4B, 0xE1, 0x0F, 0x7B, 0x5D, 0x0A, 0x68, 0x90, 0x71, 0xA0, 0xD6, 0xC0, 0xEC, 0x6B, 0x24, 0x45, 0x3D, 0x9C, 0x11, 0xD9, 0xC8, 0xFB, 0xC8, 0x8F, 0xDB, 0x48, 0x70, 0x1F, 0xC4, 0x7D, 0x83, 0x58, 0x95, 0xDC, 0x36, 0xA0, 0x68, 0xE1, 0xCF, 0x2D, 0xA9, 0x8A, 0xF0, 0xB8, 0xA6, 0x0D, 0x6E, 0xA6, 0x9C, 0xBC }; AsymmetricKeyExchangeDeformatter keyback = new RSAOAEPKeyExchangeDeformatter (key); try { byte[] Mback = keyback.DecryptKeyExchange (EM); AssertEquals ("RSAOAEPKeyExchangeDeformatter 1", M, Mback); } catch (CryptographicException ce) { // not supported by every version of Windows - Minimum: Windows XP Console.WriteLine (ce.Message + " (" + Environment.OSVersion.ToString () + ")"); } } // test with a message 128 bits (16 bytes) long // Test vector (EM) generated by CryptoAPI on Windows XP [Test] public void CapiExchange128 () { byte[] M = { 0xd4, 0x36, 0xe9, 0x95, 0x69, 0xfd, 0x32, 0xa7, 0xc8, 0xa0, 0x5b, 0xbc, 0x90, 0xd3, 0x2c, 0x49 }; byte[] EM = { 0x6D, 0xAA, 0xBC, 0x7C, 0xE7, 0x7C, 0xE6, 0x16, 0x72, 0x6F, 0xBE, 0xAF, 0x26, 0xBF, 0x87, 0x77, 0xB5, 0x47, 0x25, 0x37, 0x01, 0xC7, 0xD8, 0x18, 0xA8, 0x09, 0x0F, 0x1F, 0x13, 0x24, 0xD0, 0x2A, 0xD4, 0xDC, 0x5A, 0x2D, 0x91, 0x6D, 0x11, 0x6C, 0x1A, 0x67, 0xB2, 0xFC, 0xA3, 0xE7, 0xF4, 0xEF, 0xDC, 0xEC, 0xB2, 0xAF, 0x42, 0xB5, 0xD9, 0x7A, 0x6D, 0xE5, 0x76, 0xBA, 0x7D, 0x04, 0xCA, 0x17, 0xB0, 0x06, 0x88, 0x4D, 0xE8, 0xCC, 0x82, 0xEA, 0x13, 0xC8, 0x12, 0x05, 0x05, 0xC6, 0xB0, 0x4B, 0x53, 0x1D, 0x07, 0xFA, 0x09, 0x64, 0x30, 0xCD, 0x5C, 0xE3, 0x41, 0xB1, 0x25, 0x94, 0x05, 0x5A, 0xC2, 0xD8, 0x2E, 0xC4, 0x39, 0x51, 0x73, 0x75, 0x0C, 0x4B, 0x2F, 0x4B, 0xAD, 0x04, 0x54, 0x32, 0x30, 0x94, 0xF4, 0xFE, 0x92, 0xF4, 0xB4, 0x54, 0x07, 0x22, 0xCD, 0xB5, 0xB2, 0x01, 0x95, 0xA0 }; AsymmetricKeyExchangeDeformatter keyback = new RSAOAEPKeyExchangeDeformatter (key); try { byte[] Mback = keyback.DecryptKeyExchange (EM); AssertEquals ("RSAOAEPKeyExchangeFormatter 1", M, Mback); } catch (CryptographicException ce) { // not supported by every version of Windows - Minimum: Windows XP Console.WriteLine (ce.Message + " (" + Environment.OSVersion.ToString () + ")"); } } // test with a message 160 bits (20 bytes) long // Test vector (EM) generated by CryptoAPI on Windows XP [Test] public void CapiExchange192 () { byte[] M = { 0xd4, 0x36, 0xe9, 0x95, 0x69, 0xfd, 0x32, 0xa7, 0xc8, 0xa0, 0x5b, 0xbc, 0x90, 0xd3, 0x2c, 0x49, 0x00, 0x00, 0x00, 0x00 }; byte[] EM = { 0x72, 0x0A, 0x0E, 0xA0, 0x8C, 0x40, 0x69, 0x9D, 0x78, 0xBC, 0x94, 0x4B, 0x2C, 0x14, 0xC0, 0xC8, 0x13, 0x8B, 0x6D, 0x2F, 0x01, 0xE3, 0x45, 0x33, 0xE7, 0x9B, 0x87, 0xDB, 0x37, 0xBD, 0xA9, 0x63, 0xCC, 0x94, 0x8F, 0xBB, 0x1D, 0x61, 0xA1, 0x5E, 0x6A, 0x33, 0xBD, 0xD5, 0xC8, 0x22, 0x40, 0xB1, 0x32, 0xFB, 0x6F, 0x2A, 0x3B, 0x8A, 0x15, 0x4E, 0xC1, 0x25, 0xF0, 0x34, 0x17, 0x9A, 0x68, 0x34, 0x27, 0x5B, 0x49, 0xC5, 0xEA, 0x4D, 0x7F, 0x07, 0x4C, 0xAC, 0xF8, 0xE3, 0xD7, 0x9E, 0x72, 0xB0, 0xD1, 0xAD, 0x9E, 0x9C, 0xBB, 0xC6, 0x79, 0x14, 0x63, 0x5E, 0x13, 0xD1, 0x02, 0xDE, 0x57, 0xB5, 0xBC, 0x57, 0x68, 0xAC, 0xE3, 0xEF, 0x79, 0xED, 0xAF, 0xC0, 0xBB, 0xFE, 0xB3, 0xA6, 0x4C, 0xE8, 0x79, 0xE2, 0x3A, 0xB3, 0x37, 0x97, 0x90, 0x05, 0xCF, 0xB9, 0x1A, 0x92, 0xEC, 0x73, 0xC5, 0x8D }; AsymmetricKeyExchangeDeformatter keyback = new RSAOAEPKeyExchangeDeformatter (key); try { byte[] Mback = keyback.DecryptKeyExchange (EM); AssertEquals ("RSAOAEPKeyExchangeFormatter 1", M, Mback); } catch (CryptographicException ce) { // not supported by every version of Windows - Minimum: Windows XP Console.WriteLine (ce.Message + " (" + Environment.OSVersion.ToString () + ")"); } } // Max = (key size in bytes) - 2 * (hash length) - 2 // Test vector (EM) generated by CryptoAPI on Windows XP [Test] public void CapiExchangeMax () { byte[] M = new byte [(key.KeySize >> 3) - 2 * 20 - 2]; byte[] EM = { 0x45, 0x31, 0xA7, 0x4A, 0xE5, 0x8B, 0xC7, 0x0C, 0x5C, 0x8B, 0xE6, 0xAB, 0xC5, 0x99, 0xF3, 0x31, 0xB9, 0x64, 0xFA, 0x19, 0x4A, 0x41, 0xF3, 0x49, 0x05, 0x0B, 0x28, 0xD5, 0x96, 0x43, 0x0E, 0xEB, 0x62, 0x0B, 0x22, 0xFE, 0x5F, 0x92, 0x4F, 0x60, 0xB9, 0xAE, 0x7F, 0xAA, 0xC8, 0x82, 0x66, 0xD7, 0x19, 0xCF, 0xC0, 0x69, 0x1C, 0xAA, 0x7E, 0x95, 0x5D, 0x70, 0x3D, 0x4A, 0x1D, 0x3B, 0x55, 0xBC, 0x7D, 0x36, 0xCF, 0x98, 0x09, 0xF8, 0x20, 0x92, 0x34, 0x79, 0x0B, 0x1A, 0x91, 0xE5, 0xFB, 0x94, 0xAD, 0x2A, 0x15, 0x6E, 0x3D, 0xF4, 0xA5, 0x6F, 0x6B, 0xAE, 0x77, 0x80, 0x3C, 0xF5, 0xCC, 0x84, 0x3A, 0xF9, 0xCE, 0x9F, 0x06, 0xF6, 0xCC, 0xA8, 0x75, 0xE1, 0x55, 0x56, 0xA5, 0x76, 0x50, 0x28, 0xA7, 0x3E, 0x91, 0x11, 0x5C, 0x82, 0x7C, 0x1A, 0x92, 0x02, 0x74, 0xCC, 0xA9, 0x6C, 0xFC, 0xA4 }; AsymmetricKeyExchangeDeformatter keyback = new RSAOAEPKeyExchangeDeformatter (key); try { byte[] Mback = keyback.DecryptKeyExchange (EM); AssertEquals ("RSAOAEPKeyExchangeFormatter 1", M, Mback); } catch (CryptographicException ce) { // not supported by every version of Windows - Minimum: Windows XP Console.WriteLine (ce.Message + " (" + Environment.OSVersion.ToString () + ")"); } } // TestExchangeMin (1) // Test vector (EM) generated by Mono on Windows [Test] public void MonoExchangeMin() { byte[] M = { 0x01 }; byte[] EM = { 0x75, 0x06, 0x33, 0xB4, 0x47, 0xDB, 0x9C, 0x72, 0x1A, 0x09, 0x48, 0xEA, 0xF3, 0xED, 0xCF, 0xA7, 0x6D, 0x09, 0x8E, 0xF5, 0xC9, 0x70, 0x18, 0xF7, 0x22, 0xCC, 0xEC, 0xCB, 0xD3, 0x2B, 0xE7, 0xE3, 0x0A, 0x47, 0xF4, 0xE1, 0x66, 0x73, 0xEA, 0x7F, 0x5B, 0x27, 0x32, 0x62, 0x9D, 0x0C, 0x2F, 0x88, 0x2E, 0x3A, 0x37, 0x6C, 0x0C, 0x09, 0x1D, 0xF3, 0xE1, 0x80, 0x66, 0x26, 0x29, 0x97, 0x3D, 0xB7, 0xE6, 0x01, 0xD0, 0x88, 0x9C, 0x68, 0x3F, 0x62, 0x7C, 0x71, 0x36, 0xDA, 0xC3, 0xE2, 0x93, 0x20, 0x95, 0xF8, 0x15, 0x89, 0x73, 0x24, 0xDF, 0xFB, 0x72, 0xD9, 0x63, 0x19, 0x84, 0x41, 0x92, 0x3C, 0x71, 0x36, 0xB9, 0x09, 0x24, 0xD6, 0x8E, 0x2D, 0x5A, 0xF2, 0x4B, 0xF4, 0xCD, 0x58, 0xEB, 0x4E, 0xE4, 0x97, 0xB3, 0x09, 0xED, 0xCF, 0x6A, 0x6D, 0xBC, 0xE4, 0xD4, 0x8D, 0xEC, 0xA6, 0x35, 0x53 }; AsymmetricKeyExchangeDeformatter keyback = new RSAOAEPKeyExchangeDeformatter (key); try { byte[] Mback = keyback.DecryptKeyExchange (EM); AssertEquals ("RSAOAEPKeyExchangeDeformatter Min", M, Mback); } catch (CryptographicException ce) { // not supported by every version of Windows - Minimum: Windows XP Console.WriteLine (ce.Message + " (" + Environment.OSVersion.ToString () + ")"); } } // test with a message 128 bits (16 bytes) long // Test vector (EM) generated by Mono on Windows [Test] public void MonoExchange128() { byte[] M = { 0xd4, 0x36, 0xe9, 0x95, 0x69, 0xfd, 0x32, 0xa7, 0xc8, 0xa0, 0x5b, 0xbc, 0x90, 0xd3, 0x2c, 0x49 }; byte[] EM = { 0x3A, 0x18, 0xE7, 0xF7, 0x45, 0x32, 0x5B, 0x60, 0x46, 0x2A, 0x20, 0x1A, 0x69, 0x98, 0x84, 0x68, 0x76, 0xC0, 0x01, 0x7D, 0x37, 0xE7, 0xEB, 0x72, 0x18, 0xD7, 0xF3, 0xE5, 0x1B, 0x2C, 0xB2, 0x47, 0x86, 0x9D, 0x90, 0xE8, 0x38, 0x43, 0x0C, 0x58, 0x59, 0xDB, 0x2A, 0x46, 0xBA, 0x15, 0xD9, 0x79, 0x77, 0xB5, 0x8B, 0xA7, 0x06, 0x15, 0xE1, 0xBF, 0xA2, 0xA7, 0x69, 0xC6, 0x6A, 0x6C, 0x4F, 0x87, 0xA3, 0xA1, 0xBC, 0x21, 0x46, 0x68, 0x61, 0xEC, 0x1E, 0xE1, 0x2B, 0xEF, 0xD7, 0xE0, 0x61, 0xAF, 0xF5, 0xDA, 0x27, 0xCB, 0xFC, 0x98, 0x0C, 0x12, 0x59, 0x45, 0x64, 0x75, 0x58, 0xB5, 0x5B, 0x7A, 0x9B, 0x76, 0x68, 0x14, 0x9F, 0xAB, 0x64, 0xC7, 0x4E, 0xB7, 0xFF, 0x7D, 0x3D, 0xA3, 0x11, 0x9E, 0xE8, 0x06, 0xAF, 0x5D, 0xA3, 0xEB, 0x8E, 0x1E, 0x38, 0x5D, 0x0D, 0xC3, 0x8C, 0xC3, 0xF0, 0x57 }; AsymmetricKeyExchangeDeformatter keyback = new RSAOAEPKeyExchangeDeformatter (key); try { byte[] Mback = keyback.DecryptKeyExchange (EM); AssertEquals ("RSAOAEPKeyExchangeFormatter 128", M, Mback); } catch (CryptographicException ce) { // not supported by every version of Windows - Minimum: Windows XP Console.WriteLine (ce.Message + " (" + Environment.OSVersion.ToString () + ")"); } } // test with a message 160 bits (20 bytes) long // Test vector (EM) generated by Mono on Windows [Test] public void MonoExchange192() { byte[] M = { 0xd4, 0x36, 0xe9, 0x95, 0x69, 0xfd, 0x32, 0xa7, 0xc8, 0xa0, 0x5b, 0xbc, 0x90, 0xd3, 0x2c, 0x49, 0x00, 0x00, 0x00, 0x00 }; byte[] EM = { 0xAD, 0xFA, 0x95, 0x2E, 0xCE, 0x23, 0xBE, 0xA5, 0x77, 0x81, 0x34, 0x98, 0x64, 0x58, 0x02, 0xAB, 0x62, 0x28, 0x97, 0x84, 0x6D, 0xF3, 0xE1, 0x9D, 0xB2, 0x04, 0xA8, 0xB0, 0x1D, 0x48, 0xFC, 0x94, 0x1A, 0x3A, 0xB1, 0x72, 0x39, 0xE1, 0xFE, 0x25, 0xF6, 0x6E, 0x64, 0xA5, 0x84, 0xA3, 0x2F, 0x3D, 0x49, 0x4F, 0x7F, 0xD1, 0x45, 0x74, 0xFB, 0x42, 0x6F, 0x50, 0x5C, 0x19, 0x44, 0xB8, 0x0F, 0x3B, 0x31, 0x94, 0x8E, 0xC2, 0x44, 0x47, 0xA2, 0xE9, 0x6E, 0x7F, 0x58, 0x49, 0x38, 0xB9, 0x2C, 0xB8, 0x0E, 0xA9, 0x7A, 0x86, 0x2B, 0xDB, 0xED, 0x5A, 0x16, 0x48, 0x41, 0x84, 0x3B, 0xE3, 0xA8, 0x26, 0x01, 0xAE, 0x09, 0x41, 0xB3, 0x95, 0xC5, 0xA4, 0x5A, 0x82, 0xC3, 0x37, 0x57, 0xD9, 0x03, 0x53, 0x8D, 0x28, 0x24, 0xA4, 0x37, 0x2A, 0xA9, 0xC7, 0x66, 0xAD, 0xAC, 0x5F, 0x3A, 0xF0, 0xE5, 0x90 }; AsymmetricKeyExchangeDeformatter keyback = new RSAOAEPKeyExchangeDeformatter (key); try { byte[] Mback = keyback.DecryptKeyExchange (EM); AssertEquals ("RSAOAEPKeyExchangeFormatter 192", M, Mback); } catch (CryptographicException ce) { // not supported by every version of Windows - Minimum: Windows XP Console.WriteLine (ce.Message + " (" + Environment.OSVersion.ToString () + ")"); } } // Max = (key size in bytes) - 2 * (hash length) - 2 // Test vector (EM) generated by Mono on Windows [Test] public void MonoExchangeMax() { byte[] M = new byte [(key.KeySize >> 3) - 2 * 20 - 2]; byte[] EM = { 0x6C, 0x3E, 0x71, 0x14, 0xAD, 0xDE, 0x46, 0x26, 0x42, 0xA8, 0x84, 0x40, 0xCC, 0x06, 0x73, 0xCC, 0x88, 0x76, 0x40, 0x08, 0x93, 0xE5, 0x5F, 0xFF, 0x7D, 0x02, 0x88, 0xE9, 0x2D, 0xF6, 0x90, 0xA1, 0x8F, 0x64, 0x9A, 0x79, 0x67, 0x63, 0xA5, 0xBE, 0xCE, 0x7F, 0x48, 0x65, 0x8F, 0x53, 0x24, 0x70, 0x4F, 0x2A, 0x61, 0x7C, 0x95, 0xB6, 0xD0, 0x1D, 0x6F, 0x92, 0xA5, 0x2B, 0xB9, 0x13, 0x6B, 0xD2, 0xEB, 0x1D, 0x4F, 0x1E, 0x51, 0x6D, 0x65, 0xA6, 0x97, 0xE8, 0x60, 0x4B, 0x19, 0xE4, 0x23, 0xDC, 0x22, 0xED, 0x23, 0x02, 0x5E, 0x0C, 0x0B, 0x99, 0x5D, 0xBA, 0xFC, 0xBD, 0x75, 0x2F, 0x3E, 0xCD, 0x33, 0xBF, 0x08, 0xD5, 0x31, 0x68, 0x7C, 0x51, 0x2E, 0xBF, 0x8A, 0xBF, 0xA9, 0x8F, 0x0A, 0xDF, 0xB0, 0x91, 0xB1, 0x95, 0x03, 0x37, 0x3C, 0x77, 0x61, 0x75, 0x06, 0x61, 0xD8, 0x94, 0x04, 0x42 }; AsymmetricKeyExchangeDeformatter keyback = new RSAOAEPKeyExchangeDeformatter (key); try { byte[] Mback = keyback.DecryptKeyExchange (EM); AssertEquals ("RSAOAEPKeyExchangeFormatter Max", M, Mback); } catch (CryptographicException ce) { // not supported by every version of Windows - Minimum: Windows XP Console.WriteLine (ce.Message + " (" + Environment.OSVersion.ToString () + ")"); } } // TestExchangeTooBig [Test] [ExpectedException (typeof (CryptographicException))] public void ExchangeTooBig() { AsymmetricKeyExchangeDeformatter keyex = new RSAOAEPKeyExchangeDeformatter (key); byte[] EM = new byte [(key.KeySize >> 3) + 1]; // invalid format byte[] M = keyex.DecryptKeyExchange (EM); } [Test] public void Parameters () { RSAOAEPKeyExchangeDeformatter keyex = new RSAOAEPKeyExchangeDeformatter (key); keyex.Parameters = "Mono"; AssertNull ("Parameters", keyex.Parameters); } [Test] #if NET_2_0 [ExpectedException (typeof (CryptographicUnexpectedOperationException))] #else [ExpectedException (typeof (NullReferenceException))] #endif public void ExchangeNoKey () { AsymmetricKeyExchangeDeformatter keyex = new RSAOAEPKeyExchangeDeformatter (); byte[] M = keyex.DecryptKeyExchange (new byte [(key.KeySize >> 3) - 2 * 20 - 2]); } [Test] [ExpectedException (typeof (InvalidCastException))] public void ExchangeDSAKey () { DSA dsa = DSA.Create (); AsymmetricKeyExchangeDeformatter keyex = new RSAOAEPKeyExchangeDeformatter (dsa); } } }
namespace GoogleApi.Entities.Translate.Common.Enums.Extensions { /// <summary> /// Language Extensions. /// </summary> public static class LanguageExtension { /// <summary> /// Gets the ISO-639-1 code for the specified <see cref="Language"/>. /// </summary> /// <param name="language">The <see cref="Language"/>.</param> /// <returns>The ISO-639-1 code matching the passed <paramref name="language"/>.</returns> public static string ToCode(this Language language) { switch (language) { case Language.Afrikaans: return "af"; case Language.Albanian: return "sq"; case Language.Amharic: return "am"; case Language.Arabic: return "ar"; case Language.Armenian: return "hy"; case Language.Azeerbaijani: return "az"; case Language.Basque: return "eu"; case Language.Belarusian: return "be"; case Language.Bengali: return "bn"; case Language.Bosnian: return "bs"; case Language.Bulgarian: return "bg"; case Language.Catalan: return "ca"; case Language.Cebuano: return "ceb"; case Language.Chichewa: return "ny"; case Language.Chinese: return "zh-CN"; case Language.Chinese_Simplified: return "zh-CN"; case Language.Chinese_Traditional: return "zh-TW"; case Language.Corsican: return "co"; case Language.Croatian: return "hr"; case Language.Czech: return "cs"; case Language.Danish: return "da"; case Language.Dutch: return "nl"; case Language.English: return "en"; case Language.Esperanto: return "eo"; case Language.Estonian: return "et"; case Language.Filipino: return "tl"; case Language.Finnish: return "fi"; case Language.French: return "fr"; case Language.Frisian: return "fy"; case Language.Galician: return "gl"; case Language.Georgian: return "ka"; case Language.German: return "de"; case Language.Greek: return "el"; case Language.Gujarati: return "gu"; case Language.Haitian_Creole: return "ht"; case Language.Hausa: return "ha"; case Language.Hawaiian: return "haw"; case Language.Hebrew: return "iw"; case Language.Hindi: return "hi"; case Language.Hmong: return "hmn"; case Language.Hungarian: return "hu"; case Language.Icelandic: return "is"; case Language.Igbo: return "ig"; case Language.Indonesian: return "id"; case Language.Irish: return "ga"; case Language.Italian: return "it"; case Language.Japanese: return "ja"; case Language.Javanese: return "jw"; case Language.Kannada: return "kn"; case Language.Kazakh: return "kk"; case Language.Khmer: return "km"; case Language.Korean: return "ko"; case Language.Kurdish: return "ku"; case Language.Kyrgyz: return "ky"; case Language.Lao: return "lo"; case Language.Latin: return "la"; case Language.Latvian: return "lv"; case Language.Lithuanian: return "lt"; case Language.Luxembourgish: return "lb"; case Language.Macedonian: return "mk"; case Language.Malagasy: return "mg"; case Language.Malay: return "ms"; case Language.Malayalam: return "ml"; case Language.Maltese: return "mt"; case Language.Maori: return "mi"; case Language.Marathi: return "mr"; case Language.Mongolian: return "mn"; case Language.Burmese: return "my"; case Language.Nepali: return "ne"; case Language.Norwegian: return "no"; case Language.Pashto: return "ps"; case Language.Persian: return "fa"; case Language.Polish: return "pl"; case Language.Portuguese: return "pt"; case Language.Punjabi: return "ma"; case Language.Romanian: return "ro"; case Language.Russian: return "ru"; case Language.Samoan: return "sm"; case Language.Scots_Gaelic: return "gd"; case Language.Serbian: return "sr"; case Language.Sesotho: return "st"; case Language.Shona: return "sn"; case Language.Sindhi: return "sd"; case Language.Sinhala: return "si"; case Language.Slovak: return "sk"; case Language.Slovenian: return "sl"; case Language.Somali: return "so"; case Language.Spanish: return "es"; case Language.Sundanese: return "su"; case Language.Swahili: return "sw"; case Language.Swedish: return "sv"; case Language.Tajik: return "tg"; case Language.Tamil: return "ta"; case Language.Telugu: return "te"; case Language.Thai: return "th"; case Language.Turkish: return "tr"; case Language.Ukrainian: return "uk"; case Language.Urdu: return "ur"; case Language.Uzbek: return "uz"; case Language.Vietnamese: return "vi"; case Language.Welsh: return "cy"; case Language.Xhosa: return "xh"; case Language.Yiddish: return "yi"; case Language.Yoruba: return "yo"; case Language.Zulu: return "zu"; default: return string.Empty; } } /// <summary> /// Determines whether the <see cref="Language"/> passed is comptabile with <see cref="Model.Nmt"/>. /// https://cloud.google.com/translate/docs/languages /// </summary> /// <param name="language">The <see cref="Language"/> to evaluate.</param> /// <returns>True, if compatable with <see cref="Model.Nmt"/>, otherwise false.</returns> public static bool IsValidNmt(this Language language) { switch (language) { case Language.Afrikaans: return true; case Language.Arabic: return true; case Language.Bulgarian: return true; case Language.Chinese_Simplified: return true; case Language.Chinese_Traditional: return true; case Language.Croatian: return true; case Language.Czech: return true; case Language.Danish: return true; case Language.Dutch: return true; case Language.English: return true; case Language.French: return true; case Language.German: return true; case Language.Greek: return true; case Language.Hebrew: return true; case Language.Hindi: return true; case Language.Icelandic: return true; case Language.Indonesian: return true; case Language.Italian: return true; case Language.Japanese: return true; case Language.Korean: return true; case Language.Norwegian: return true; case Language.Polish: return true; case Language.Portuguese: return true; case Language.Romanian: return true; case Language.Russian: return true; case Language.Slovak: return true; case Language.Spanish: return true; case Language.Swedish: return true; case Language.Thai: return true; case Language.Turkish: return true; case Language.Vietnamese: return true; case Language.Albanian: case Language.Amharic: case Language.Armenian: case Language.Azeerbaijani: case Language.Basque: case Language.Belarusian: case Language.Bengali: case Language.Bosnian: case Language.Catalan: case Language.Cebuano: case Language.Chichewa: case Language.Chinese: case Language.Corsican: case Language.Esperanto: case Language.Estonian: case Language.Filipino: case Language.Finnish: case Language.Frisian: case Language.Galician: case Language.Georgian: case Language.Gujarati: case Language.Haitian_Creole: case Language.Hausa: case Language.Hawaiian: case Language.Hmong: case Language.Hungarian: case Language.Igbo: case Language.Irish: case Language.Javanese: case Language.Kannada: case Language.Kazakh: case Language.Khmer: case Language.Kurdish: case Language.Kyrgyz: case Language.Lao: case Language.Latin: case Language.Latvian: case Language.Lithuanian: case Language.Luxembourgish: case Language.Macedonian: case Language.Malagasy: case Language.Malay: case Language.Malayalam: case Language.Maltese: case Language.Maori: case Language.Marathi: case Language.Mongolian: case Language.Burmese: case Language.Nepali: case Language.Pashto: case Language.Persian: case Language.Punjabi: case Language.Samoan: case Language.Scots_Gaelic: case Language.Serbian: case Language.Sesotho: case Language.Shona: case Language.Sindhi: case Language.Sinhala: case Language.Slovenian: case Language.Somali: case Language.Sundanese: case Language.Swahili: case Language.Tajik: case Language.Tamil: case Language.Telugu: case Language.Ukrainian: case Language.Urdu: case Language.Uzbek: case Language.Welsh: case Language.Xhosa: case Language.Yiddish: case Language.Yoruba: case Language.Zulu: return false; default: return false; } } } }
// ------------------------------------------------------------------------------ // Copyright (c) 2014 Microsoft Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // ------------------------------------------------------------------------------ namespace Microsoft.Live.Phone { using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.Phone.BackgroundTransfer; using Microsoft.Live.Operations; /// <summary> /// Class that converts a Download BackgroundTransferRequest's TransferStatusChanged events /// to the Task&lt;T&gt; pattern. /// </summary> internal class BackgroundUploadCompletedEventAdapter : IBackgroundUploadResponseHandlerObserver { #region Fields private readonly IBackgroundTransferService backgroundTransferService; /// <summary> /// Used to set the result of the Upload on. /// </summary> private readonly TaskCompletionSource<LiveOperationResult> tcs; #endregion #region Events public event Action<BackgroundTransferRequest> BackgroundTransferRequestCompleted; #endregion #region Constructors /// <summary> /// Constructs a new BackgroundUploadCompletedEventAdapter injected with the given parameters. /// </summary> /// <param name="backgroundTransferService">The BackgroundTransferService used to Add and Remove requests on.</param> /// <param name="tcs">The TaskCompletionSource to set the result of the operation on.</param> public BackgroundUploadCompletedEventAdapter( IBackgroundTransferService backgroundTransferService, TaskCompletionSource<LiveOperationResult> tcs) { Debug.Assert(backgroundTransferService != null); Debug.Assert(tcs != null); this.backgroundTransferService = backgroundTransferService; this.tcs = tcs; } #endregion #region Methods /// <summary> /// Attaches to this BackgroundTransferRequest's TransferStatusChanged event. /// </summary> /// <param name="request">request to attach to</param> public Task<LiveOperationResult> ConvertTransferStatusChangedToTask(BackgroundTransferRequest request) { Debug.Assert(BackgroundTransferHelper.IsUploadRequest(request)); if (request.TransferStatus != TransferStatus.Completed) { request.TransferStatusChanged += this.HandleTransferStatusChanged; } else { // If we are working with an already completed request just handle it now. this.OnTransferStatusComplete(request); } return this.tcs.Task; } /// <summary> /// Callback used when the BackgroundUploadResponseHandler finishes with a success response. /// This method will convert the result into a LiveCompletedEventArgs and call OnCompleted. /// </summary> /// <param name="result">The result dictionary from the upload response.</param> /// <param name="rawResult">The raw string from the upload response.</param> /// <param name="userState">The userstate of the request.</param> public void OnSuccessResponse(IDictionary<string, object> result, string rawResult) { this.tcs.TrySetResult(new LiveOperationResult(result, rawResult)); } /// <summary> /// Callback used when the BackgroundUploadResponseHandler finishes with an error in the json response. /// This method will conver the error result into a LiveCompletedEventArgs and call OnCompleted. /// </summary> /// <param name="code">The error code from the error.</param> /// <param name="message">The error message from the error.</param> public void OnErrorResponse(string code, string message) { var exception = new LiveConnectException(code, message); this.tcs.TrySetException(exception); } /// <summary> /// Callback used when the BackgroundUploadResponseHandler finishes with an error. /// </summary> /// <param name="exception">The exception from the BackgroundUploadResponseHandler.</param> public void OnError(Exception exception) { var e = new LiveConnectException(ApiOperation.ApiClientErrorCode, ResourceHelper.GetString("BackgroundUploadResponseHandlerError"), exception); this.tcs.TrySetException(e); } /// <summary> /// Called when a BackgroundTransferRequest's TransferStatus is set to Completed. /// This method will remove the request from the BackgroundTransferService and convert /// the result over to a LiveOperationResult and set it on the TaskCompletionSource. /// </summary> /// <param name="request"></param> private void OnTransferStatusComplete(BackgroundTransferRequest request) { Debug.Assert(request.TransferStatus == TransferStatus.Completed); Debug.Assert(BackgroundTransferHelper.IsUploadRequest(request)); // Remove the transfer request in order to make room in the queue for more transfers. // Transfers are not automatically removed by the system. // Cancelled requests have already been removed from the system and cannot be removed twice. if (!BackgroundTransferHelper.IsCanceledRequest(request)) { try { this.backgroundTransferService.Remove(request); } catch (Exception exception) { this.tcs.TrySetException(new LiveConnectException( ApiOperation.ApiClientErrorCode, ResourceHelper.GetString("BackgroundTransferServiceRemoveError"), exception)); return; } } this.OnBackgroundTransferRequestCompleted(request); if (request.TransferError != null) { var exception = new LiveConnectException(ApiOperation.ApiServerErrorCode, ResourceHelper.GetString("ServerError"), request.TransferError); this.tcs.TrySetException(exception); return; } if (!BackgroundTransferHelper.IsSuccessfulStatusCode(request.StatusCode)) { var exception = new LiveConnectException(ApiOperation.ApiServerErrorCode, ResourceHelper.GetString("ServerError")); this.tcs.TrySetException(exception); return; } // Once we know we have a *good* upload, we have to send it to the response handler // to read it's JSON response body. We are an observer to this class, so it will call us back // with its result. var responseHandler = new BackgroundUploadResponseHandler( request.DownloadLocation, this); responseHandler.ReadJsonResponseFromDownloadLocation(); } /// <summary> /// Callback used to listen to BackgroundTransferRequest.TransferStatusChanged events. /// This method ignores all TransferStatus changes except for TransferStatus.Completed. /// </summary> /// <param name="sender">The sender of the call.</param> /// <param name="e">The eventargs from the BackgroundTransferRequest.</param> private void HandleTransferStatusChanged(object sender, BackgroundTransferEventArgs e) { BackgroundTransferRequest request = e.Request; if (request.TransferStatus != TransferStatus.Completed) { return; } request.TransferStatusChanged -= this.HandleTransferStatusChanged; this.OnTransferStatusComplete(request); } private void OnBackgroundTransferRequestCompleted(BackgroundTransferRequest request) { Action<BackgroundTransferRequest> handler = BackgroundTransferRequestCompleted; if (handler != null) { handler(request); } } #endregion } }
// File generated from our OpenAPI spec namespace Stripe { using Newtonsoft.Json; using Stripe.Infrastructure; public class DisputeEvidence : StripeEntity<DisputeEvidence> { /// <summary> /// Any server or activity logs showing proof that the customer accessed or downloaded the /// purchased digital product. This information should include IP addresses, corresponding /// timestamps, and any detailed recorded activity. /// </summary> [JsonProperty("access_activity_log")] public string AccessActivityLog { get; set; } /// <summary> /// The billing address provided by the customer. /// </summary> [JsonProperty("billing_address")] public string BillingAddress { get; set; } #region Expandable CancellationPolicy /// <summary> /// (ID of the File) /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) Your /// subscription cancellation policy, as shown to the customer. /// </summary> [JsonIgnore] public string CancellationPolicyId { get => this.InternalCancellationPolicy?.Id; set => this.InternalCancellationPolicy = SetExpandableFieldId(value, this.InternalCancellationPolicy); } /// <summary> /// (Expanded) /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) Your /// subscription cancellation policy, as shown to the customer. /// /// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>. /// </summary> [JsonIgnore] public File CancellationPolicy { get => this.InternalCancellationPolicy?.ExpandedObject; set => this.InternalCancellationPolicy = SetExpandableFieldObject(value, this.InternalCancellationPolicy); } [JsonProperty("cancellation_policy")] [JsonConverter(typeof(ExpandableFieldConverter<File>))] internal ExpandableField<File> InternalCancellationPolicy { get; set; } #endregion /// <summary> /// An explanation of how and when the customer was shown your refund policy prior to /// purchase. /// </summary> [JsonProperty("cancellation_policy_disclosure")] public string CancellationPolicyDisclosure { get; set; } /// <summary> /// A justification for why the customer's subscription was not canceled. /// </summary> [JsonProperty("cancellation_rebuttal")] public string CancellationRebuttal { get; set; } #region Expandable CustomerCommunication /// <summary> /// (ID of the File) /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) Any /// communication with the customer that you feel is relevant to your case. Examples include /// emails proving that the customer received the product or service, or demonstrating their /// use of or satisfaction with the product or service. /// </summary> [JsonIgnore] public string CustomerCommunicationId { get => this.InternalCustomerCommunication?.Id; set => this.InternalCustomerCommunication = SetExpandableFieldId(value, this.InternalCustomerCommunication); } /// <summary> /// (Expanded) /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) Any /// communication with the customer that you feel is relevant to your case. Examples include /// emails proving that the customer received the product or service, or demonstrating their /// use of or satisfaction with the product or service. /// /// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>. /// </summary> [JsonIgnore] public File CustomerCommunication { get => this.InternalCustomerCommunication?.ExpandedObject; set => this.InternalCustomerCommunication = SetExpandableFieldObject(value, this.InternalCustomerCommunication); } [JsonProperty("customer_communication")] [JsonConverter(typeof(ExpandableFieldConverter<File>))] internal ExpandableField<File> InternalCustomerCommunication { get; set; } #endregion /// <summary> /// The email address of the customer. /// </summary> [JsonProperty("customer_email_address")] public string CustomerEmailAddress { get; set; } /// <summary> /// The name of the customer. /// </summary> [JsonProperty("customer_name")] public string CustomerName { get; set; } /// <summary> /// The IP address that the customer used when making the purchase. /// </summary> [JsonProperty("customer_purchase_ip")] public string CustomerPurchaseIp { get; set; } #region Expandable CustomerSignature /// <summary> /// (ID of the File) /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) A /// relevant document or contract showing the customer's signature. /// </summary> [JsonIgnore] public string CustomerSignatureId { get => this.InternalCustomerSignature?.Id; set => this.InternalCustomerSignature = SetExpandableFieldId(value, this.InternalCustomerSignature); } /// <summary> /// (Expanded) /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) A /// relevant document or contract showing the customer's signature. /// /// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>. /// </summary> [JsonIgnore] public File CustomerSignature { get => this.InternalCustomerSignature?.ExpandedObject; set => this.InternalCustomerSignature = SetExpandableFieldObject(value, this.InternalCustomerSignature); } [JsonProperty("customer_signature")] [JsonConverter(typeof(ExpandableFieldConverter<File>))] internal ExpandableField<File> InternalCustomerSignature { get; set; } #endregion #region Expandable DuplicateChargeDocumentation /// <summary> /// (ID of the File) /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) /// Documentation for the prior charge that can uniquely identify the charge, such as a /// receipt, shipping label, work order, etc. This document should be paired with a similar /// document from the disputed payment that proves the two payments are separate. /// </summary> [JsonIgnore] public string DuplicateChargeDocumentationId { get => this.InternalDuplicateChargeDocumentation?.Id; set => this.InternalDuplicateChargeDocumentation = SetExpandableFieldId(value, this.InternalDuplicateChargeDocumentation); } /// <summary> /// (Expanded) /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) /// Documentation for the prior charge that can uniquely identify the charge, such as a /// receipt, shipping label, work order, etc. This document should be paired with a similar /// document from the disputed payment that proves the two payments are separate. /// /// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>. /// </summary> [JsonIgnore] public File DuplicateChargeDocumentation { get => this.InternalDuplicateChargeDocumentation?.ExpandedObject; set => this.InternalDuplicateChargeDocumentation = SetExpandableFieldObject(value, this.InternalDuplicateChargeDocumentation); } [JsonProperty("duplicate_charge_documentation")] [JsonConverter(typeof(ExpandableFieldConverter<File>))] internal ExpandableField<File> InternalDuplicateChargeDocumentation { get; set; } #endregion /// <summary> /// An explanation of the difference between the disputed charge versus the prior charge /// that appears to be a duplicate. /// </summary> [JsonProperty("duplicate_charge_explanation")] public string DuplicateChargeExplanation { get; set; } /// <summary> /// The Stripe ID for the prior charge which appears to be a duplicate of the disputed /// charge. /// </summary> [JsonProperty("duplicate_charge_id")] public string DuplicateChargeId { get; set; } /// <summary> /// A description of the product or service that was sold. /// </summary> [JsonProperty("product_description")] public string ProductDescription { get; set; } #region Expandable Receipt /// <summary> /// (ID of the File) /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) Any /// receipt or message sent to the customer notifying them of the charge. /// </summary> [JsonIgnore] public string ReceiptId { get => this.InternalReceipt?.Id; set => this.InternalReceipt = SetExpandableFieldId(value, this.InternalReceipt); } /// <summary> /// (Expanded) /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) Any /// receipt or message sent to the customer notifying them of the charge. /// /// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>. /// </summary> [JsonIgnore] public File Receipt { get => this.InternalReceipt?.ExpandedObject; set => this.InternalReceipt = SetExpandableFieldObject(value, this.InternalReceipt); } [JsonProperty("receipt")] [JsonConverter(typeof(ExpandableFieldConverter<File>))] internal ExpandableField<File> InternalReceipt { get; set; } #endregion #region Expandable RefundPolicy /// <summary> /// (ID of the File) /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) Your /// refund policy, as shown to the customer. /// </summary> [JsonIgnore] public string RefundPolicyId { get => this.InternalRefundPolicy?.Id; set => this.InternalRefundPolicy = SetExpandableFieldId(value, this.InternalRefundPolicy); } /// <summary> /// (Expanded) /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) Your /// refund policy, as shown to the customer. /// /// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>. /// </summary> [JsonIgnore] public File RefundPolicy { get => this.InternalRefundPolicy?.ExpandedObject; set => this.InternalRefundPolicy = SetExpandableFieldObject(value, this.InternalRefundPolicy); } [JsonProperty("refund_policy")] [JsonConverter(typeof(ExpandableFieldConverter<File>))] internal ExpandableField<File> InternalRefundPolicy { get; set; } #endregion /// <summary> /// Documentation demonstrating that the customer was shown your refund policy prior to /// purchase. /// </summary> [JsonProperty("refund_policy_disclosure")] public string RefundPolicyDisclosure { get; set; } /// <summary> /// A justification for why the customer is not entitled to a refund. /// </summary> [JsonProperty("refund_refusal_explanation")] public string RefundRefusalExplanation { get; set; } /// <summary> /// The date on which the customer received or began receiving the purchased service, in a /// clear human-readable format. /// </summary> [JsonProperty("service_date")] public string ServiceDate { get; set; } #region Expandable ServiceDocumentation /// <summary> /// (ID of the File) /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) /// Documentation showing proof that a service was provided to the customer. This could /// include a copy of a signed contract, work order, or other form of written agreement. /// </summary> [JsonIgnore] public string ServiceDocumentationId { get => this.InternalServiceDocumentation?.Id; set => this.InternalServiceDocumentation = SetExpandableFieldId(value, this.InternalServiceDocumentation); } /// <summary> /// (Expanded) /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) /// Documentation showing proof that a service was provided to the customer. This could /// include a copy of a signed contract, work order, or other form of written agreement. /// /// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>. /// </summary> [JsonIgnore] public File ServiceDocumentation { get => this.InternalServiceDocumentation?.ExpandedObject; set => this.InternalServiceDocumentation = SetExpandableFieldObject(value, this.InternalServiceDocumentation); } [JsonProperty("service_documentation")] [JsonConverter(typeof(ExpandableFieldConverter<File>))] internal ExpandableField<File> InternalServiceDocumentation { get; set; } #endregion /// <summary> /// The address to which a physical product was shipped. You should try to include as /// complete address information as possible. /// </summary> [JsonProperty("shipping_address")] public string ShippingAddress { get; set; } /// <summary> /// The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. If /// multiple carriers were used for this purchase, please separate them with commas. /// </summary> [JsonProperty("shipping_carrier")] public string ShippingCarrier { get; set; } /// <summary> /// The date on which a physical product began its route to the shipping address, in a clear /// human-readable format. /// </summary> [JsonProperty("shipping_date")] public string ShippingDate { get; set; } #region Expandable ShippingDocumentation /// <summary> /// (ID of the File) /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) /// Documentation showing proof that a product was shipped to the customer at the same /// address the customer provided to you. This could include a copy of the shipment receipt, /// shipping label, etc. It should show the customer's full shipping address, if possible. /// </summary> [JsonIgnore] public string ShippingDocumentationId { get => this.InternalShippingDocumentation?.Id; set => this.InternalShippingDocumentation = SetExpandableFieldId(value, this.InternalShippingDocumentation); } /// <summary> /// (Expanded) /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) /// Documentation showing proof that a product was shipped to the customer at the same /// address the customer provided to you. This could include a copy of the shipment receipt, /// shipping label, etc. It should show the customer's full shipping address, if possible. /// /// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>. /// </summary> [JsonIgnore] public File ShippingDocumentation { get => this.InternalShippingDocumentation?.ExpandedObject; set => this.InternalShippingDocumentation = SetExpandableFieldObject(value, this.InternalShippingDocumentation); } [JsonProperty("shipping_documentation")] [JsonConverter(typeof(ExpandableFieldConverter<File>))] internal ExpandableField<File> InternalShippingDocumentation { get; set; } #endregion /// <summary> /// The tracking number for a physical product, obtained from the delivery service. If /// multiple tracking numbers were generated for this purchase, please separate them with /// commas. /// </summary> [JsonProperty("shipping_tracking_number")] public string ShippingTrackingNumber { get; set; } #region Expandable UncategorizedFile /// <summary> /// (ID of the File) /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) Any /// additional evidence or statements. /// </summary> [JsonIgnore] public string UncategorizedFileId { get => this.InternalUncategorizedFile?.Id; set => this.InternalUncategorizedFile = SetExpandableFieldId(value, this.InternalUncategorizedFile); } /// <summary> /// (Expanded) /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) Any /// additional evidence or statements. /// /// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>. /// </summary> [JsonIgnore] public File UncategorizedFile { get => this.InternalUncategorizedFile?.ExpandedObject; set => this.InternalUncategorizedFile = SetExpandableFieldObject(value, this.InternalUncategorizedFile); } [JsonProperty("uncategorized_file")] [JsonConverter(typeof(ExpandableFieldConverter<File>))] internal ExpandableField<File> InternalUncategorizedFile { get; set; } #endregion /// <summary> /// Any additional evidence or statements. /// </summary> [JsonProperty("uncategorized_text")] public string UncategorizedText { get; set; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Xunit; namespace System.Collections.Immutable.Tests { public class ImmutableHashSetBuilderTest : ImmutablesTestBase { [Fact] public void CreateBuilder() { var builder = ImmutableHashSet.CreateBuilder<string>(); Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer); builder = ImmutableHashSet.CreateBuilder<string>(StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer); } [Fact] public void ToBuilder() { var builder = ImmutableHashSet<int>.Empty.ToBuilder(); Assert.True(builder.Add(3)); Assert.True(builder.Add(5)); Assert.False(builder.Add(5)); Assert.Equal(2, builder.Count); Assert.True(builder.Contains(3)); Assert.True(builder.Contains(5)); Assert.False(builder.Contains(7)); var set = builder.ToImmutable(); Assert.Equal(builder.Count, set.Count); Assert.True(builder.Add(8)); Assert.Equal(3, builder.Count); Assert.Equal(2, set.Count); Assert.True(builder.Contains(8)); Assert.False(set.Contains(8)); } [Fact] public void BuilderFromSet() { var set = ImmutableHashSet<int>.Empty.Add(1); var builder = set.ToBuilder(); Assert.True(builder.Contains(1)); Assert.True(builder.Add(3)); Assert.True(builder.Add(5)); Assert.False(builder.Add(5)); Assert.Equal(3, builder.Count); Assert.True(builder.Contains(3)); Assert.True(builder.Contains(5)); Assert.False(builder.Contains(7)); var set2 = builder.ToImmutable(); Assert.Equal(builder.Count, set2.Count); Assert.True(set2.Contains(1)); Assert.True(builder.Add(8)); Assert.Equal(4, builder.Count); Assert.Equal(3, set2.Count); Assert.True(builder.Contains(8)); Assert.False(set.Contains(8)); Assert.False(set2.Contains(8)); } [Fact] public void EnumerateBuilderWhileMutating() { var builder = ImmutableHashSet<int>.Empty.Union(Enumerable.Range(1, 10)).ToBuilder(); CollectionAssertAreEquivalent(Enumerable.Range(1, 10).ToArray(), builder.ToArray()); var enumerator = builder.GetEnumerator(); Assert.True(enumerator.MoveNext()); builder.Add(11); // Verify that a new enumerator will succeed. CollectionAssertAreEquivalent(Enumerable.Range(1, 11).ToArray(), builder.ToArray()); // Try enumerating further with the previous enumerable now that we've changed the collection. Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); enumerator.Reset(); enumerator.MoveNext(); // resetting should fix the problem. // Verify that by obtaining a new enumerator, we can enumerate all the contents. CollectionAssertAreEquivalent(Enumerable.Range(1, 11).ToArray(), builder.ToArray()); } [Fact] public void BuilderReusesUnchangedImmutableInstances() { var collection = ImmutableHashSet<int>.Empty.Add(1); var builder = collection.ToBuilder(); Assert.Same(collection, builder.ToImmutable()); // no changes at all. builder.Add(2); var newImmutable = builder.ToImmutable(); Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance. Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance. } [Fact] public void EnumeratorTest() { var builder = ImmutableHashSet.Create(1).ToBuilder(); ManuallyEnumerateTest(new[] { 1 }, ((IEnumerable<int>)builder).GetEnumerator()); } [Fact] public void Clear() { var set = ImmutableHashSet.Create(1); var builder = set.ToBuilder(); builder.Clear(); Assert.Equal(0, builder.Count); } [Fact] public void KeyComparer() { var builder = ImmutableHashSet.Create("a", "B").ToBuilder(); Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer); Assert.True(builder.Contains("a")); Assert.False(builder.Contains("A")); builder.KeyComparer = StringComparer.OrdinalIgnoreCase; Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer); Assert.Equal(2, builder.Count); Assert.True(builder.Contains("a")); Assert.True(builder.Contains("A")); var set = builder.ToImmutable(); Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer); } [Fact] public void KeyComparerCollisions() { var builder = ImmutableHashSet.Create("a", "A").ToBuilder(); builder.KeyComparer = StringComparer.OrdinalIgnoreCase; Assert.Equal(1, builder.Count); Assert.True(builder.Contains("a")); var set = builder.ToImmutable(); Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer); Assert.Equal(1, set.Count); Assert.True(set.Contains("a")); } [Fact] public void KeyComparerEmptyCollection() { var builder = ImmutableHashSet.Create<string>().ToBuilder(); Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer); builder.KeyComparer = StringComparer.OrdinalIgnoreCase; Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer); var set = builder.ToImmutable(); Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer); } [Fact] public void UnionWith() { var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder(); Assert.Throws<ArgumentNullException>(() => builder.UnionWith(null)); builder.UnionWith(new[] { 2, 3, 4 }); Assert.Equal(new[] { 1, 2, 3, 4 }, builder); } [Fact] public void ExceptWith() { var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder(); Assert.Throws<ArgumentNullException>(() => builder.ExceptWith(null)); builder.ExceptWith(new[] { 2, 3, 4 }); Assert.Equal(new[] { 1 }, builder); } [Fact] public void SymmetricExceptWith() { var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder(); Assert.Throws<ArgumentNullException>(() => builder.SymmetricExceptWith(null)); builder.SymmetricExceptWith(new[] { 2, 3, 4 }); Assert.Equal(new[] { 1, 4 }, builder); } [Fact] public void IntersectWith() { var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder(); Assert.Throws<ArgumentNullException>(() => builder.IntersectWith(null)); builder.IntersectWith(new[] { 2, 3, 4 }); Assert.Equal(new[] { 2, 3 }, builder); } [Fact] public void IsProperSubsetOf() { var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); Assert.Throws<ArgumentNullException>(() => builder.IsProperSubsetOf(null)); Assert.False(builder.IsProperSubsetOf(Enumerable.Range(1, 3))); Assert.True(builder.IsProperSubsetOf(Enumerable.Range(1, 5))); } [Fact] public void IsProperSupersetOf() { var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); Assert.Throws<ArgumentNullException>(() => builder.IsProperSupersetOf(null)); Assert.False(builder.IsProperSupersetOf(Enumerable.Range(1, 3))); Assert.True(builder.IsProperSupersetOf(Enumerable.Range(1, 2))); } [Fact] public void IsSubsetOf() { var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); Assert.Throws<ArgumentNullException>(() => builder.IsSubsetOf(null)); Assert.False(builder.IsSubsetOf(Enumerable.Range(1, 2))); Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 3))); Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 5))); } [Fact] public void IsSupersetOf() { var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); Assert.Throws<ArgumentNullException>(() => builder.IsSupersetOf(null)); Assert.False(builder.IsSupersetOf(Enumerable.Range(1, 4))); Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 3))); Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 2))); } [Fact] public void Overlaps() { var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); Assert.Throws<ArgumentNullException>(() => builder.Overlaps(null)); Assert.True(builder.Overlaps(Enumerable.Range(3, 2))); Assert.False(builder.Overlaps(Enumerable.Range(4, 3))); } [Fact] public void Remove() { var builder = ImmutableHashSet.Create("a").ToBuilder(); Assert.Throws<ArgumentNullException>(() => builder.Remove(null)); Assert.False(builder.Remove("b")); Assert.True(builder.Remove("a")); } [Fact] public void SetEquals() { var builder = ImmutableHashSet.Create("a").ToBuilder(); Assert.Throws<ArgumentNullException>(() => builder.SetEquals(null)); Assert.False(builder.SetEquals(new[] { "b" })); Assert.True(builder.SetEquals(new[] { "a" })); Assert.True(builder.SetEquals(builder)); } [Fact] public void ICollectionOfTMethods() { ICollection<string> builder = ImmutableHashSet.Create("a").ToBuilder(); builder.Add("b"); Assert.True(builder.Contains("b")); var array = new string[3]; builder.CopyTo(array, 1); Assert.Null(array[0]); CollectionAssertAreEquivalent(new[] { null, "a", "b" }, array); Assert.False(builder.IsReadOnly); CollectionAssertAreEquivalent(new[] { "a", "b" }, builder.ToArray()); // tests enumerator } [Fact] public void DebuggerAttributesValid() { DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableHashSet.CreateBuilder<int>()); } } }
#region File Description //----------------------------------------------------------------------------- // LoadingScreen.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.IO; using System.IO.IsolatedStorage; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input.Touch; #endregion namespace HoneycombRush { class HighScoreScreen : GameScreen { #region Fields static readonly string HighScoreFilename = "highscores.txt"; const int highscorePlaces = 5; public static List<KeyValuePair<string, int>> highScore = new List<KeyValuePair<string, int>>(highscorePlaces) { new KeyValuePair<string,int> ("Jasper",55000), new KeyValuePair<string,int> ("Ellen",52750), new KeyValuePair<string,int> ("Terry",52200), new KeyValuePair<string,int> ("Lori",50200), new KeyValuePair<string,int> ("Michael",50750), }; SpriteFont highScoreFont; Dictionary<int, string> numberPlaceMapping; #endregion #region Initialzations /// <summary> /// Creates a new highscore screen instance. /// </summary> public HighScoreScreen() { EnabledGestures = GestureType.Tap; numberPlaceMapping = new Dictionary<int, string>(); InitializeMapping(); } /// <summary> /// Load screen resources /// </summary> public override void LoadContent() { highScoreFont = Load<SpriteFont>(@"Fonts\HighScoreFont"); base.LoadContent(); } #endregion #region Handle Input /// <summary> /// Handles user input as a part of screen logic update. /// </summary> /// <param name="gameTime">Game time information.</param> /// <param name="input">Input information.</param> public override void HandleInput(GameTime gameTime, InputState input) { if (input == null) { throw new ArgumentNullException("input"); } if (input.IsPauseGame(null)) { Exit(); } // Return to the main menu when a tep gesture is recognized if (input.Gestures.Count > 0) { GestureSample sample = input.Gestures[0]; if (sample.GestureType == GestureType.Tap) { Exit(); input.Gestures.Clear(); } } } /// <summary> /// Exit this screen. /// </summary> private void Exit() { this.ExitScreen(); ScreenManager.AddScreen(new BackgroundScreen("titlescreen"), null); ScreenManager.AddScreen(new MainMenuScreen(), null); } #endregion #region Render /// <summary> /// Renders the screen. /// </summary> /// <param name="gameTime">Game time information</param> public override void Draw(GameTime gameTime) { ScreenManager.SpriteBatch.Begin(); // Draw the highscores table for (int i = 0; i < highScore.Count; i++) { if (!string.IsNullOrEmpty(highScore[i].Key)) { // Draw place number ScreenManager.SpriteBatch.DrawString(highScoreFont, GetPlaceString(i), new Vector2(20, i * 72 + 86), Color.Black); // Draw Name ScreenManager.SpriteBatch.DrawString(highScoreFont, highScore[i].Key, new Vector2(210, i * 72 + 86), Color.DarkRed); // Draw score ScreenManager.SpriteBatch.DrawString(highScoreFont, highScore[i].Value.ToString(), new Vector2(560, i * 72 + 86), Color.Yellow); } } ScreenManager.SpriteBatch.End(); base.Draw(gameTime); } #endregion #region Highscore loading/saving logic /// <summary> /// Check if a score belongs on the high score table. /// </summary> /// <returns></returns> public static bool IsInHighscores(int score) { // If the score is better than the worst score in the table return score > highScore[highscorePlaces - 1].Value; } /// <summary> /// Put high score on highscores table. /// </summary> /// <param name="name">Player's name.</param> /// <param name="score">The player's score.</param> public static void PutHighScore(string playerName, int score) { if (IsInHighscores(score)) { highScore[highscorePlaces - 1] = new KeyValuePair<string, int>(playerName, score); OrderGameScore(); SaveHighscore(); } } /// <summary> /// Order the high scores table. /// </summary> private static void OrderGameScore() { highScore.Sort(CompareScores); } /// <summary> /// Comparison method used to compare two highscore entries. /// </summary> /// <param name="score1">First highscore entry.</param> /// <param name="score2">Second highscore entry.</param> /// <returns>1 if the first highscore is smaller than the second, 0 if both /// are equal and -1 otherwise.</returns> private static int CompareScores(KeyValuePair<string, int> score1, KeyValuePair<string, int> score2) { if (score1.Value < score2.Value) { return 1; } if (score1.Value == score2.Value) { return 0; } return -1; } /// <summary> /// Saves the current highscore to a text file. /// </summary> public static void SaveHighscore() { // Get the place to store the data using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { // Create the file to save the data using (IsolatedStorageFileStream isfs = isf.CreateFile(HighScoreScreen.HighScoreFilename)) { using (StreamWriter writer = new StreamWriter(isfs)) { for (int i = 0; i < highScore.Count; i++) { // Write the scores writer.WriteLine(highScore[i].Key); writer.WriteLine(highScore[i].Value.ToString()); } } } } } /// <summary> /// Loads the high score from a text file. /// </summary> public static void LoadHighscores() { // Get the place the data stored using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { // Try to open the file if (isf.FileExists(HighScoreScreen.HighScoreFilename)) { using (IsolatedStorageFileStream isfs = isf.OpenFile(HighScoreScreen.HighScoreFilename, FileMode.Open)) { // Get the stream to read the data using (StreamReader reader = new StreamReader(isfs)) { // Read the highscores int i = 0; while (!reader.EndOfStream) { string name = reader.ReadLine(); string score = reader.ReadLine(); highScore[i++] = new KeyValuePair<string, int>(name, int.Parse(score)); } } } } } OrderGameScore(); } private string GetPlaceString(int number) { return numberPlaceMapping[number]; } private void InitializeMapping() { numberPlaceMapping.Add(0, "1ST"); numberPlaceMapping.Add(1, "2ND"); numberPlaceMapping.Add(2, "3RD"); numberPlaceMapping.Add(3, "4TH"); numberPlaceMapping.Add(4, "5TH"); } #endregion } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact [email protected]. /// /// StyleSheetResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Autopilot.V1.Assistant { public class StyleSheetResource : Resource { private static Request BuildFetchRequest(FetchStyleSheetOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Autopilot, "/v1/Assistants/" + options.PathAssistantSid + "/StyleSheet", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Returns Style sheet JSON object for the Assistant /// </summary> /// <param name="options"> Fetch StyleSheet parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of StyleSheet </returns> public static StyleSheetResource Fetch(FetchStyleSheetOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Returns Style sheet JSON object for the Assistant /// </summary> /// <param name="options"> Fetch StyleSheet parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of StyleSheet </returns> public static async System.Threading.Tasks.Task<StyleSheetResource> FetchAsync(FetchStyleSheetOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Returns Style sheet JSON object for the Assistant /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant with the StyleSheet resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of StyleSheet </returns> public static StyleSheetResource Fetch(string pathAssistantSid, ITwilioRestClient client = null) { var options = new FetchStyleSheetOptions(pathAssistantSid); return Fetch(options, client); } #if !NET35 /// <summary> /// Returns Style sheet JSON object for the Assistant /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant with the StyleSheet resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of StyleSheet </returns> public static async System.Threading.Tasks.Task<StyleSheetResource> FetchAsync(string pathAssistantSid, ITwilioRestClient client = null) { var options = new FetchStyleSheetOptions(pathAssistantSid); return await FetchAsync(options, client); } #endif private static Request BuildUpdateRequest(UpdateStyleSheetOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Autopilot, "/v1/Assistants/" + options.PathAssistantSid + "/StyleSheet", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Updates the style sheet for an Assistant identified by `assistant_sid`. /// </summary> /// <param name="options"> Update StyleSheet parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of StyleSheet </returns> public static StyleSheetResource Update(UpdateStyleSheetOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Updates the style sheet for an Assistant identified by `assistant_sid`. /// </summary> /// <param name="options"> Update StyleSheet parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of StyleSheet </returns> public static async System.Threading.Tasks.Task<StyleSheetResource> UpdateAsync(UpdateStyleSheetOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Updates the style sheet for an Assistant identified by `assistant_sid`. /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant with the StyleSheet resource to update </param> /// <param name="styleSheet"> The JSON string that describes the style sheet object </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of StyleSheet </returns> public static StyleSheetResource Update(string pathAssistantSid, object styleSheet = null, ITwilioRestClient client = null) { var options = new UpdateStyleSheetOptions(pathAssistantSid){StyleSheet = styleSheet}; return Update(options, client); } #if !NET35 /// <summary> /// Updates the style sheet for an Assistant identified by `assistant_sid`. /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant with the StyleSheet resource to update </param> /// <param name="styleSheet"> The JSON string that describes the style sheet object </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of StyleSheet </returns> public static async System.Threading.Tasks.Task<StyleSheetResource> UpdateAsync(string pathAssistantSid, object styleSheet = null, ITwilioRestClient client = null) { var options = new UpdateStyleSheetOptions(pathAssistantSid){StyleSheet = styleSheet}; return await UpdateAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a StyleSheetResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> StyleSheetResource object represented by the provided JSON </returns> public static StyleSheetResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<StyleSheetResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The SID of the Assistant that is the parent of the resource /// </summary> [JsonProperty("assistant_sid")] public string AssistantSid { get; private set; } /// <summary> /// The absolute URL of the StyleSheet resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The JSON string that describes the style sheet object /// </summary> [JsonProperty("data")] public object Data { get; private set; } private StyleSheetResource() { } } }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoadSoftDelete.DataAccess; using SelfLoadSoftDelete.DataAccess.ERLevel; namespace SelfLoadSoftDelete.Business.ERLevel { /// <summary> /// G07_Country_Child (editable child object).<br/> /// This is a generated base class of <see cref="G07_Country_Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="G06_Country"/> collection. /// </remarks> [Serializable] public partial class G07_Country_Child : BusinessBase<G07_Country_Child> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Country_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Country_Child_NameProperty = RegisterProperty<string>(p => p.Country_Child_Name, "Regions Child Name"); /// <summary> /// Gets or sets the Regions Child Name. /// </summary> /// <value>The Regions Child Name.</value> public string Country_Child_Name { get { return GetProperty(Country_Child_NameProperty); } set { SetProperty(Country_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="G07_Country_Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="G07_Country_Child"/> object.</returns> internal static G07_Country_Child NewG07_Country_Child() { return DataPortal.CreateChild<G07_Country_Child>(); } /// <summary> /// Factory method. Loads a <see cref="G07_Country_Child"/> object, based on given parameters. /// </summary> /// <param name="country_ID1">The Country_ID1 parameter of the G07_Country_Child to fetch.</param> /// <returns>A reference to the fetched <see cref="G07_Country_Child"/> object.</returns> internal static G07_Country_Child GetG07_Country_Child(int country_ID1) { return DataPortal.FetchChild<G07_Country_Child>(country_ID1); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="G07_Country_Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public G07_Country_Child() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="G07_Country_Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="G07_Country_Child"/> object from the database, based on given criteria. /// </summary> /// <param name="country_ID1">The Country ID1.</param> protected void Child_Fetch(int country_ID1) { var args = new DataPortalHookArgs(country_ID1); OnFetchPre(args); using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var dal = dalManager.GetProvider<IG07_Country_ChildDal>(); var data = dal.Fetch(country_ID1); Fetch(data); } OnFetchPost(args); } private void Fetch(IDataReader data) { using (var dr = new SafeDataReader(data)) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="G07_Country_Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Country_Child_NameProperty, dr.GetString("Country_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="G07_Country_Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(G06_Country parent) { using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<IG07_Country_ChildDal>(); using (BypassPropertyChecks) { dal.Insert( parent.Country_ID, Country_Child_Name ); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="G07_Country_Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(G06_Country parent) { if (!IsDirty) return; using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<IG07_Country_ChildDal>(); using (BypassPropertyChecks) { dal.Update( parent.Country_ID, Country_Child_Name ); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="G07_Country_Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(G06_Country parent) { using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IG07_Country_ChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.Country_ID); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
/*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ using Microsoft.Samples.VisualStudio.CodeSweep.Scanner; using Microsoft.Samples.VisualStudio.CodeSweep.VSPackage.Properties; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using System; using System.Collections.Generic; using System.ComponentModel.Design; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Windows.Forms; namespace Microsoft.Samples.VisualStudio.CodeSweep.VSPackage { class TaskProvider : ITaskProvider, IVsSolutionEvents { public TaskProvider(IServiceProvider provider) { _imageList.ImageSize = new Size(9, 16); _imageList.Images.AddStrip(Resources.priority); _imageList.TransparentColor = Color.FromArgb(0, 255, 0); _serviceProvider = provider; var taskList = _serviceProvider.GetService(typeof(SVsTaskList)) as IVsTaskList; if (taskList == null) { Debug.Fail("Failed to get SVsTaskList service."); return; } int hr = taskList.RegisterTaskProvider(this, out _cookie); Debug.Assert(hr == VSConstants.S_OK, "RegisterTaskProvider did not return S_OK."); Debug.Assert(_cookie != 0, "RegisterTaskProvider did not return a nonzero cookie."); SetCommandHandlers(); ListenForProjectUnload(); } public void SetCurrentProject(IVsProject currentProject) { _currentProject = currentProject; } #region ITaskProvider Members public void AddResult(IScanResult result, string projectFile) { string fullPath = result.FilePath; if (!Path.IsPathRooted(fullPath)) { fullPath = Utilities.AbsolutePathFromRelative(fullPath, Path.GetDirectoryName(projectFile)); } if (result.Scanned) { foreach (IScanHit hit in result.Results) { if (!string.IsNullOrEmpty(hit.Warning)) { // See if we've warned about this term before; if so, don't warn again. if (null == _termsWithDuplicateWarning.Find( item => string.Compare(item, hit.Term.Text, StringComparison.OrdinalIgnoreCase) == 0)) { _tasks.Add(new Task(hit.Term.Text, hit.Term.Severity, hit.Term.Class, hit.Warning, string.Empty, string.Empty, -1, -1, string.Empty, string.Empty, this, _serviceProvider, _currentProject)); _termsWithDuplicateWarning.Add(hit.Term.Text); } } _tasks.Add(new Task(hit.Term.Text, hit.Term.Severity, hit.Term.Class, hit.Term.Comment, hit.Term.RecommendedTerm, fullPath, hit.Line, hit.Column, projectFile, hit.LineText, this, _serviceProvider, _currentProject)); } } else { _tasks.Add(new Task(string.Empty, 1, string.Empty, string.Format(CultureInfo.CurrentUICulture, Resources.FileNotScannedError, fullPath), string.Empty, fullPath, -1, -1, projectFile, string.Empty, this, _serviceProvider, _currentProject)); } Refresh(); } public void Clear() { _tasks.Clear(); Refresh(); } public void ShowTaskList() { var shell = _serviceProvider.GetService(typeof(SVsUIShell)) as IVsUIShell; if (shell == null) { Debug.Fail("Failed to get SVsUIShell service."); return; } object dummy = null; Guid cmdSetGuid = VSConstants.GUID_VSStandardCommandSet97; int hr = shell.PostExecCommand(ref cmdSetGuid, (int)VSConstants.VSStd97CmdID.TaskListWindow, 0, ref dummy); Debug.Assert(hr == VSConstants.S_OK, "PostExecCommand did not return S_OK."); } /// <summary> /// Returns an image index between 0 and 2 inclusive corresponding to the specified severity. /// </summary> public static int GetImageIndexForSeverity(int severity) { return Math.Max(1, Math.Min(3, severity)) - 1; } public bool IsShowingIgnoredInstances { get; private set; } #endregion ITaskProvider Members #region IVsTaskProvider Members public int EnumTaskItems(out IVsEnumTaskItems ppenum) { ppenum = new TaskEnumerator(_tasks, IsShowingIgnoredInstances); return VSConstants.S_OK; } [DllImport("comctl32.dll")] static extern IntPtr ImageList_Duplicate(IntPtr original); public int ImageList(out IntPtr phImageList) { phImageList = ImageList_Duplicate(_imageList.Handle); return VSConstants.S_OK; } public int OnTaskListFinalRelease(IVsTaskList pTaskList) { if ((_cookie != 0) && (null != pTaskList)) { int hr = pTaskList.UnregisterTaskProvider(_cookie); Debug.Assert(hr == VSConstants.S_OK, "UnregisterTaskProvider did not return S_OK."); } return VSConstants.S_OK; } public int ReRegistrationKey(out string pbstrKey) { pbstrKey = string.Empty; return VSConstants.E_NOTIMPL; } public int SubcategoryList(uint cbstr, string[] rgbstr, out uint pcActual) { pcActual = 0; return VSConstants.E_NOTIMPL; } #endregion IVsTaskProvider Members #region IVsTaskProvider3 Members public int GetColumn(int iColumn, VSTASKCOLUMN[] pColumn) { switch ((Task.TaskFields)iColumn) { case Task.TaskFields.Class: pColumn[0].bstrCanonicalName = "Class"; pColumn[0].bstrHeading = Resources.ClassColumn; pColumn[0].bstrLocalizedName = Resources.ClassColumn; pColumn[0].bstrTip = string.Empty; pColumn[0].cxDefaultWidth = 91; pColumn[0].cxMinWidth = 0; pColumn[0].fAllowHide = 1; pColumn[0].fAllowUserSort = 1; pColumn[0].fDescendingSort = 0; pColumn[0].fDynamicSize = 1; pColumn[0].fFitContent = 0; pColumn[0].fMoveable = 1; pColumn[0].fShowSortArrow = 1; pColumn[0].fSizeable = 1; pColumn[0].fVisibleByDefault = 1; pColumn[0].iDefaultSortPriority = -1; pColumn[0].iField = (int)Task.TaskFields.Class; pColumn[0].iImage = -1; break; case Task.TaskFields.Priority: pColumn[0].bstrCanonicalName = "Priority"; pColumn[0].bstrHeading = "!"; pColumn[0].bstrLocalizedName = Resources.PriorityColumn; pColumn[0].bstrTip = Resources.PriorityColumn; pColumn[0].cxDefaultWidth = 22; pColumn[0].cxMinWidth = 0; pColumn[0].fAllowHide = 1; pColumn[0].fAllowUserSort = 1; pColumn[0].fDescendingSort = 0; pColumn[0].fDynamicSize = 0; pColumn[0].fFitContent = 0; pColumn[0].fMoveable = 1; pColumn[0].fShowSortArrow = 0; pColumn[0].fSizeable = 1; pColumn[0].fVisibleByDefault = 1; pColumn[0].iDefaultSortPriority = -1; pColumn[0].iField = (int)Task.TaskFields.Priority; pColumn[0].iImage = -1; break; case Task.TaskFields.PriorityNumber: pColumn[0].bstrCanonicalName = "Priority Number"; pColumn[0].bstrHeading = "!#"; pColumn[0].bstrLocalizedName = Resources.PriorityNumberColumn; pColumn[0].bstrTip = Resources.PriorityNumberColumn; pColumn[0].cxDefaultWidth = 50; pColumn[0].cxMinWidth = 0; pColumn[0].fAllowHide = 1; pColumn[0].fAllowUserSort = 1; pColumn[0].fDescendingSort = 0; pColumn[0].fDynamicSize = 0; pColumn[0].fFitContent = 0; pColumn[0].fMoveable = 1; pColumn[0].fShowSortArrow = 0; pColumn[0].fSizeable = 1; pColumn[0].fVisibleByDefault = 0; pColumn[0].iDefaultSortPriority = 0; pColumn[0].iField = (int)Task.TaskFields.PriorityNumber; pColumn[0].iImage = -1; break; case Task.TaskFields.Replacement: pColumn[0].bstrCanonicalName = "Replacement"; pColumn[0].bstrHeading = Resources.ReplacementColumn; pColumn[0].bstrLocalizedName = Resources.ReplacementColumn; pColumn[0].bstrTip = string.Empty; pColumn[0].cxDefaultWidth = 140; pColumn[0].cxMinWidth = 0; pColumn[0].fAllowHide = 1; pColumn[0].fAllowUserSort = 1; pColumn[0].fDescendingSort = 0; pColumn[0].fDynamicSize = 0; pColumn[0].fFitContent = 0; pColumn[0].fMoveable = 1; pColumn[0].fShowSortArrow = 1; pColumn[0].fSizeable = 1; pColumn[0].fVisibleByDefault = 0; pColumn[0].iDefaultSortPriority = -1; pColumn[0].iField = (int)Task.TaskFields.Replacement; pColumn[0].iImage = -1; break; case Task.TaskFields.Term: pColumn[0].bstrCanonicalName = "Term"; pColumn[0].bstrHeading = Resources.TermColumn; pColumn[0].bstrLocalizedName = Resources.TermColumn; pColumn[0].bstrTip = string.Empty; pColumn[0].cxDefaultWidth = 103; pColumn[0].cxMinWidth = 0; pColumn[0].fAllowHide = 1; pColumn[0].fAllowUserSort = 1; pColumn[0].fDescendingSort = 0; pColumn[0].fDynamicSize = 1; pColumn[0].fFitContent = 0; pColumn[0].fMoveable = 1; pColumn[0].fShowSortArrow = 1; pColumn[0].fSizeable = 1; pColumn[0].fVisibleByDefault = 1; pColumn[0].iDefaultSortPriority = -1; pColumn[0].iField = (int)Task.TaskFields.Term; pColumn[0].iImage = -1; break; default: return VSConstants.E_INVALIDARG; } return VSConstants.S_OK; } public int GetColumnCount(out int pnColumns) { pnColumns = Enum.GetValues(typeof(Task.TaskFields)).Length; return VSConstants.S_OK; } public int GetProviderFlags(out uint tpfFlags) { tpfFlags = (uint)(__VSTASKPROVIDERFLAGS.TPF_NOAUTOROUTING | __VSTASKPROVIDERFLAGS.TPF_ALWAYSVISIBLE); return VSConstants.S_OK; } public int GetProviderGuid(out Guid pguidProvider) { pguidProvider = _providerGuid; return VSConstants.S_OK; } public int GetProviderName(out string pbstrName) { pbstrName = Resources.AppName; return VSConstants.S_OK; } public int GetProviderToolbar(out Guid pguidGroup, out uint pdwID) { pguidGroup = GuidList.guidVSPackageCmdSet; pdwID = 0x2020; return VSConstants.S_OK; } public int GetSurrogateProviderGuid(out Guid pguidProvider) { pguidProvider = Guid.Empty; return VSConstants.E_NOTIMPL; } public int OnBeginTaskEdit(IVsTaskItem pItem) { return VSConstants.E_NOTIMPL; } public int OnEndTaskEdit(IVsTaskItem pItem, int fCommitChanges, out int pfAllowChanges) { pfAllowChanges = 0; return VSConstants.E_NOTIMPL; } #endregion IVsTaskProvider3 Members #region IVsSolutionEvents Members public int OnAfterCloseSolution(object pUnkReserved) { return VSConstants.S_OK; } public int OnAfterLoadProject(IVsHierarchy pStubHierarchy, IVsHierarchy pRealHierarchy) { return VSConstants.S_OK; } public int OnAfterOpenProject(IVsHierarchy pHierarchy, int fAdded) { return VSConstants.S_OK; } public int OnAfterOpenSolution(object pUnkReserved, int fNewSolution) { return VSConstants.S_OK; } public int OnBeforeCloseProject(IVsHierarchy pHierarchy, int fRemoved) { string projFile = ProjectUtilities.GetProjectFilePath(pHierarchy as IVsProject); if (!string.IsNullOrEmpty(projFile)) { // Remove all tasks for the project that is being closed. for (int i = 0; i < _tasks.Count; ++i) { if (_tasks[i].ProjectFile == projFile) { _tasks.RemoveAt(i); --i; } } Refresh(); } return VSConstants.S_OK; } public int OnBeforeCloseSolution(object pUnkReserved) { return VSConstants.S_OK; } public int OnBeforeUnloadProject(IVsHierarchy pRealHierarchy, IVsHierarchy pStubHierarchy) { return VSConstants.S_OK; } public int OnQueryCloseProject(IVsHierarchy pHierarchy, int fRemoving, ref int pfCancel) { return VSConstants.S_OK; } public int OnQueryCloseSolution(object pUnkReserved, ref int pfCancel) { return VSConstants.S_OK; } public int OnQueryUnloadProject(IVsHierarchy pRealHierarchy, ref int pfCancel) { return VSConstants.S_OK; } #endregion IVsSolutionEvents Members #region Private Members static readonly Guid _providerGuid = new Guid("{9ACC41B7-15B4-4dd7-A0F3-0A935D5647F3}"); readonly List<Task> _tasks = new List<Task>(); readonly IServiceProvider _serviceProvider; readonly uint _cookie; readonly List<string> _termsWithDuplicateWarning = new List<string>(); readonly ImageList _imageList = new ImageList(); uint _solutionEventsCookie = 0; IVsProject _currentProject; private void ListenForProjectUnload() { var solution = _serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution; if (solution == null) { Debug.Fail("Failed to get SVsSolution service."); return; } int hr = solution.AdviseSolutionEvents(this, out _solutionEventsCookie); Debug.Assert(hr == VSConstants.S_OK, "AdviseSolutionEvents did not return S_OK."); Debug.Assert(_solutionEventsCookie != 0, "AdviseSolutionEvents did not return a nonzero cookie."); } private void SetCommandHandlers() { var mcs = _serviceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (mcs == null) { Debug.Fail("Failed to get IMenuCommandService service."); return; } CommandID ignoreID = new CommandID(GuidList.guidVSPackageCmdSet, (int)PkgCmdIDList.cmdidIgnore); OleMenuCommand ignoreCommand = new OleMenuCommand(new EventHandler(IgnoreSelectedItems), new EventHandler(QueryIgnore), ignoreID); mcs.AddCommand(ignoreCommand); ignoreCommand.BeforeQueryStatus += new EventHandler(QueryIgnore); CommandID dontIgnoreID = new CommandID(GuidList.guidVSPackageCmdSet, (int)PkgCmdIDList.cmdidDoNotIgnore); OleMenuCommand dontIgnoreCommand = new OleMenuCommand(new EventHandler(DontIgnoreSelectedItems), new EventHandler(QueryDontIgnore), dontIgnoreID); mcs.AddCommand(dontIgnoreCommand); dontIgnoreCommand.BeforeQueryStatus += new EventHandler(QueryDontIgnore); CommandID showIgnoredID = new CommandID(GuidList.guidVSPackageCmdSet, (int)PkgCmdIDList.cmdidShowIgnoredInstances); OleMenuCommand showIgnoredCommand = new OleMenuCommand(new EventHandler(ToggleShowIgnoredInstances), showIgnoredID); mcs.AddCommand(showIgnoredCommand); } List<Task> GetSelectedTasks() { var result = new List<Task>(); int hr = VSConstants.S_OK; var taskList = _serviceProvider.GetService(typeof(SVsTaskList)) as IVsTaskList2; if (taskList == null) { Debug.Fail("Failed to get SVsTaskList service."); return result; } IVsEnumTaskItems enumerator = null; hr = taskList.EnumSelectedItems(out enumerator); Debug.Assert(hr == VSConstants.S_OK, "EnumSelectedItems did not return S_OK."); IVsTaskItem[] items = new IVsTaskItem[] { null }; uint[] fetched = new uint[] { 0 }; for (enumerator.Reset(); enumerator.Next(1, items, fetched) == VSConstants.S_OK && fetched[0] == 1; /*nothing*/) { Task task = items[0] as Task; if (task != null) { result.Add(task); } } return result; } private void QueryIgnore(object sender, EventArgs e) { var mcs = _serviceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (mcs == null) { Debug.Fail("Failed to get IMenuCommandService service."); return; } MenuCommand command = mcs.FindCommand(new CommandID(GuidList.guidVSPackageCmdSet, (int)PkgCmdIDList.cmdidIgnore)); bool anyNotIgnored = GetSelectedTasks().Any(t => !t.Ignored); command.Supported = true; command.Enabled = anyNotIgnored; } private void QueryDontIgnore(object sender, EventArgs e) { var mcs = _serviceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (mcs == null) { Debug.Fail("Failed to get IMenuCommandService service."); return; } MenuCommand command = mcs.FindCommand(new CommandID(GuidList.guidVSPackageCmdSet, (int)PkgCmdIDList.cmdidDoNotIgnore)); bool anyIgnored = GetSelectedTasks().Any(t => t.Ignored); command.Supported = true; command.Enabled = anyIgnored; } private void IgnoreSelectedItems(object sender, EventArgs e) { SetSelectedItemsIgnoreState(true); } private void DontIgnoreSelectedItems(object sender, EventArgs e) { SetSelectedItemsIgnoreState(false); } private void SetSelectedItemsIgnoreState(bool ignore) { foreach (Task task in GetSelectedTasks()) { task.Ignored = ignore; } Refresh(); } private void ToggleShowIgnoredInstances(object sender, EventArgs e) { IsShowingIgnoredInstances = !IsShowingIgnoredInstances; var mcs = _serviceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (mcs != null) { mcs.FindCommand(new CommandID(GuidList.guidVSPackageCmdSet, (int)PkgCmdIDList.cmdidShowIgnoredInstances)).Checked = IsShowingIgnoredInstances; } else { Debug.Fail("Failed to get IMenuCommandService service."); } Refresh(); } private void Refresh() { var taskList = _serviceProvider.GetService(typeof(SVsTaskList)) as IVsTaskList; if (taskList == null) { return; } int hr = taskList.RefreshTasks(_cookie); Debug.Assert(hr == VSConstants.S_OK, "RefreshTasks did not return S_OK."); } #endregion Private Members } }
// *********************************************************************** // Copyright (c) 2009-2014 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Security; using System.Web.UI; using NUnit.Compatibility; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; #if NETSTANDARD1_6 using System.Runtime.InteropServices; #endif namespace NUnit.Framework.Api { /// <summary> /// FrameworkController provides a facade for use in loading, browsing /// and running tests without requiring a reference to the NUnit /// framework. All calls are encapsulated in constructors for /// this class and its nested classes, which only require the /// types of the Common Type System as arguments. /// /// The controller supports four actions: Load, Explore, Count and Run. /// They are intended to be called by a driver, which should allow for /// proper sequencing of calls. Load must be called before any of the /// other actions. The driver may support other actions, such as /// reload on run, by combining these calls. /// </summary> public class FrameworkController : LongLivedMarshalByRefObject { #if !PORTABLE private const string LOG_FILE_FORMAT = "InternalTrace.{0}.{1}.log"; #endif // Pre-loaded test assembly, if passed in constructor private Assembly _testAssembly; #region Constructors /// <summary> /// Construct a FrameworkController using the default builder and runner. /// </summary> /// <param name="assemblyNameOrPath">The AssemblyName or path to the test assembly</param> /// <param name="idPrefix">A prefix used for all test ids created under this controller.</param> /// <param name="settings">A Dictionary of settings to use in loading and running the tests</param> public FrameworkController(string assemblyNameOrPath, string idPrefix, IDictionary settings) { Initialize(assemblyNameOrPath, settings); this.Builder = new DefaultTestAssemblyBuilder(); this.Runner = new NUnitTestAssemblyRunner(this.Builder); Test.IdPrefix = idPrefix; } /// <summary> /// Construct a FrameworkController using the default builder and runner. /// </summary> /// <param name="assembly">The test assembly</param> /// <param name="idPrefix">A prefix used for all test ids created under this controller.</param> /// <param name="settings">A Dictionary of settings to use in loading and running the tests</param> public FrameworkController(Assembly assembly, string idPrefix, IDictionary settings) : this(assembly.FullName, idPrefix, settings) { _testAssembly = assembly; } /// <summary> /// Construct a FrameworkController, specifying the types to be used /// for the runner and builder. This constructor is provided for /// purposes of development. /// </summary> /// <param name="assemblyNameOrPath">The full AssemblyName or the path to the test assembly</param> /// <param name="idPrefix">A prefix used for all test ids created under this controller.</param> /// <param name="settings">A Dictionary of settings to use in loading and running the tests</param> /// <param name="runnerType">The Type of the test runner</param> /// <param name="builderType">The Type of the test builder</param> public FrameworkController(string assemblyNameOrPath, string idPrefix, IDictionary settings, string runnerType, string builderType) { Initialize(assemblyNameOrPath, settings); Builder = (ITestAssemblyBuilder)Reflect.Construct(Type.GetType(builderType)); Runner = (ITestAssemblyRunner)Reflect.Construct(Type.GetType(runnerType), new object[] { Builder }); Test.IdPrefix = idPrefix ?? ""; } /// <summary> /// Construct a FrameworkController, specifying the types to be used /// for the runner and builder. This constructor is provided for /// purposes of development. /// </summary> /// <param name="assembly">The test assembly</param> /// <param name="idPrefix">A prefix used for all test ids created under this controller.</param> /// <param name="settings">A Dictionary of settings to use in loading and running the tests</param> /// <param name="runnerType">The Type of the test runner</param> /// <param name="builderType">The Type of the test builder</param> public FrameworkController(Assembly assembly, string idPrefix, IDictionary settings, string runnerType, string builderType) : this(assembly.FullName, idPrefix, settings, runnerType, builderType) { _testAssembly = assembly; } #if !PORTABLE // This method invokes members on the 'System.Diagnostics.Process' class and must satisfy the link demand of // the full-trust 'PermissionSetAttribute' on this class. Callers of this method have no influence on how the // Process class is used, so we can safely satisfy the link demand with a 'SecuritySafeCriticalAttribute' rather // than a 'SecurityCriticalAttribute' and allow use by security transparent callers. [SecuritySafeCritical] #endif private void Initialize(string assemblyPath, IDictionary settings) { AssemblyNameOrPath = assemblyPath; var newSettings = settings as IDictionary<string, object>; Settings = newSettings ?? settings.Cast<DictionaryEntry>().ToDictionary(de => (string)de.Key, de => de.Value); if (Settings.ContainsKey(FrameworkPackageSettings.InternalTraceLevel)) { var traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), (string)Settings[FrameworkPackageSettings.InternalTraceLevel], true); if (Settings.ContainsKey(FrameworkPackageSettings.InternalTraceWriter)) InternalTrace.Initialize((TextWriter)Settings[FrameworkPackageSettings.InternalTraceWriter], traceLevel); #if !PORTABLE else { var workDirectory = Settings.ContainsKey(FrameworkPackageSettings.WorkDirectory) ? (string)Settings[FrameworkPackageSettings.WorkDirectory] : Directory.GetCurrentDirectory(); #if NETSTANDARD1_6 var id = DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss"); #else var id = Process.GetCurrentProcess().Id; #endif var logName = string.Format(LOG_FILE_FORMAT, id, Path.GetFileName(assemblyPath)); InternalTrace.Initialize(Path.Combine(workDirectory, logName), traceLevel); } #endif } } #endregion #region Properties /// <summary> /// Gets the ITestAssemblyBuilder used by this controller instance. /// </summary> /// <value>The builder.</value> public ITestAssemblyBuilder Builder { get; private set; } /// <summary> /// Gets the ITestAssemblyRunner used by this controller instance. /// </summary> /// <value>The runner.</value> public ITestAssemblyRunner Runner { get; private set; } /// <summary> /// Gets the AssemblyName or the path for which this FrameworkController was created /// </summary> public string AssemblyNameOrPath { get; private set; } /// <summary> /// Gets the Assembly for which this /// </summary> public Assembly Assembly { get; private set; } /// <summary> /// Gets a dictionary of settings for the FrameworkController /// </summary> internal IDictionary<string, object> Settings { get; private set; } #endregion #region Public Action methods Used by nunit.driver for running portable tests /// <summary> /// Loads the tests in the assembly /// </summary> /// <returns></returns> public string LoadTests() { if (_testAssembly != null) Runner.Load(_testAssembly, Settings); else Runner.Load(AssemblyNameOrPath, Settings); return Runner.LoadedTest.ToXml(false).OuterXml; } /// <summary> /// Returns info about the tests in an assembly /// </summary> /// <param name="filter">A string containing the XML representation of the filter to use</param> /// <returns>The XML result of exploring the tests</returns> public string ExploreTests(string filter) { Guard.ArgumentNotNull(filter, "filter"); if (Runner.LoadedTest == null) throw new InvalidOperationException("The Explore method was called but no test has been loaded"); return Runner.ExploreTests(TestFilter.FromXml(filter)).ToXml(true).OuterXml; } /// <summary> /// Runs the tests in an assembly /// </summary> /// <param name="filter">A string containing the XML representation of the filter to use</param> /// <returns>The XML result of the test run</returns> public string RunTests(string filter) { Guard.ArgumentNotNull(filter, "filter"); TNode result = Runner.Run(new TestProgressReporter(null), TestFilter.FromXml(filter)).ToXml(true); // Insert elements as first child in reverse order if (Settings != null) // Some platforms don't have settings InsertSettingsElement(result, Settings); #if !PORTABLE InsertEnvironmentElement(result); #endif return result.OuterXml; } #if !NET_2_0 class ActionCallback : ICallbackEventHandler { Action<string> _callback; public ActionCallback(Action<string> callback) { _callback = callback; } public string GetCallbackResult() { throw new NotImplementedException(); } public void RaiseCallbackEvent(string report) { if (_callback != null) _callback.Invoke(report); } } /// <summary> /// Runs the tests in an assembly synchronously reporting back the test results through the callback /// or through the return value /// </summary> /// <param name="callback">The callback that receives the test results</param> /// <param name="filter">A string containing the XML representation of the filter to use</param> /// <returns>The XML result of the test run</returns> public string RunTests(Action<string> callback, string filter) { Guard.ArgumentNotNull(filter, "filter"); var handler = new ActionCallback(callback); TNode result = Runner.Run(new TestProgressReporter(handler), TestFilter.FromXml(filter)).ToXml(true); // Insert elements as first child in reverse order if (Settings != null) // Some platforms don't have settings InsertSettingsElement(result, Settings); #if !PORTABLE InsertEnvironmentElement(result); #endif return result.OuterXml; } /// <summary> /// Runs the tests in an assembly asynchronously reporting back the test results through the callback /// </summary> /// <param name="callback">The callback that receives the test results</param> /// <param name="filter">A string containing the XML representation of the filter to use</param> private void RunAsync(Action<string> callback, string filter) { Guard.ArgumentNotNull(filter, "filter"); var handler = new ActionCallback(callback); Runner.RunAsync(new TestProgressReporter(handler), TestFilter.FromXml(filter)); } #endif /// <summary> /// Stops the test run /// </summary> /// <param name="force">True to force the stop, false for a cooperative stop</param> public void StopRun(bool force) { Runner.StopRun(force); } /// <summary> /// Counts the number of test cases in the loaded TestSuite /// </summary> /// <param name="filter">A string containing the XML representation of the filter to use</param> /// <returns>The number of tests</returns> public int CountTests(string filter) { Guard.ArgumentNotNull(filter, "filter"); return Runner.CountTestCases(TestFilter.FromXml(filter)); } #endregion #region Private Action Methods Used by Nested Classes private void LoadTests(ICallbackEventHandler handler) { handler.RaiseCallbackEvent(LoadTests()); } private void ExploreTests(ICallbackEventHandler handler, string filter) { Guard.ArgumentNotNull(filter, "filter"); if (Runner.LoadedTest == null) throw new InvalidOperationException("The Explore method was called but no test has been loaded"); handler.RaiseCallbackEvent(Runner.ExploreTests(TestFilter.FromXml(filter)).ToXml(true).OuterXml); } private void RunTests(ICallbackEventHandler handler, string filter) { Guard.ArgumentNotNull(filter, "filter"); TNode result = Runner.Run(new TestProgressReporter(handler), TestFilter.FromXml(filter)).ToXml(true); // Insert elements as first child in reverse order if (Settings != null) // Some platforms don't have settings InsertSettingsElement(result, Settings); #if !PORTABLE InsertEnvironmentElement(result); #endif handler.RaiseCallbackEvent(result.OuterXml); } private void RunAsync(ICallbackEventHandler handler, string filter) { Guard.ArgumentNotNull(filter, "filter"); Runner.RunAsync(new TestProgressReporter(handler), TestFilter.FromXml(filter)); } private void StopRun(ICallbackEventHandler handler, bool force) { StopRun(force); } private void CountTests(ICallbackEventHandler handler, string filter) { handler.RaiseCallbackEvent(CountTests(filter).ToString()); } #if !PORTABLE /// <summary> /// Inserts environment element /// </summary> /// <param name="targetNode">Target node</param> /// <returns>The new node</returns> #if NETSTANDARD1_6 public static TNode InsertEnvironmentElement(TNode targetNode) { TNode env = new TNode("environment"); targetNode.ChildNodes.Insert(0, env); var assemblyName = AssemblyHelper.GetAssemblyName(typeof(FrameworkController).GetTypeInfo().Assembly); env.AddAttribute("framework-version", assemblyName.Version.ToString()); env.AddAttribute("clr-version", RuntimeInformation.FrameworkDescription); env.AddAttribute("os-version", RuntimeInformation.OSDescription); env.AddAttribute("cwd", Directory.GetCurrentDirectory()); env.AddAttribute("machine-name", Environment.MachineName); env.AddAttribute("culture", CultureInfo.CurrentCulture.ToString()); env.AddAttribute("uiculture", CultureInfo.CurrentUICulture.ToString()); env.AddAttribute("os-architecture", RuntimeInformation.ProcessArchitecture.ToString()); return env; } #else public static TNode InsertEnvironmentElement(TNode targetNode) { TNode env = new TNode("environment"); targetNode.ChildNodes.Insert(0, env); env.AddAttribute("framework-version", Assembly.GetExecutingAssembly().GetName().Version.ToString()); env.AddAttribute("clr-version", Environment.Version.ToString()); env.AddAttribute("os-version", Environment.OSVersion.ToString()); env.AddAttribute("platform", Environment.OSVersion.Platform.ToString()); env.AddAttribute("cwd", Environment.CurrentDirectory); env.AddAttribute("machine-name", Environment.MachineName); env.AddAttribute("user", Environment.UserName); env.AddAttribute("user-domain", Environment.UserDomainName); env.AddAttribute("culture", CultureInfo.CurrentCulture.ToString()); env.AddAttribute("uiculture", CultureInfo.CurrentUICulture.ToString()); env.AddAttribute("os-architecture", GetProcessorArchitecture()); return env; } private static string GetProcessorArchitecture() { return IntPtr.Size == 8 ? "x64" : "x86"; } #endif #endif /// <summary> /// Inserts settings element /// </summary> /// <param name="targetNode">Target node</param> /// <param name="settings">Settings dictionary</param> /// <returns>The new node</returns> public static TNode InsertSettingsElement(TNode targetNode, IDictionary<string, object> settings) { TNode settingsNode = new TNode("settings"); targetNode.ChildNodes.Insert(0, settingsNode); foreach (string key in settings.Keys) AddSetting(settingsNode, key, settings[key]); #if PARALLEL // Add default values for display if (!settings.ContainsKey(FrameworkPackageSettings.NumberOfTestWorkers)) AddSetting(settingsNode, FrameworkPackageSettings.NumberOfTestWorkers, NUnitTestAssemblyRunner.DefaultLevelOfParallelism); #endif return settingsNode; } private static void AddSetting(TNode settingsNode, string name, object value) { TNode setting = new TNode("setting"); setting.AddAttribute("name", name); setting.AddAttribute("value", value.ToString()); settingsNode.ChildNodes.Add(setting); } #endregion #region Nested Action Classes #region TestContollerAction /// <summary> /// FrameworkControllerAction is the base class for all actions /// performed against a FrameworkController. /// </summary> public abstract class FrameworkControllerAction : LongLivedMarshalByRefObject { } #endregion #region LoadTestsAction /// <summary> /// LoadTestsAction loads a test into the FrameworkController /// </summary> public class LoadTestsAction : FrameworkControllerAction { /// <summary> /// LoadTestsAction loads the tests in an assembly. /// </summary> /// <param name="controller">The controller.</param> /// <param name="handler">The callback handler.</param> public LoadTestsAction(FrameworkController controller, object handler) { controller.LoadTests((ICallbackEventHandler)handler); } } #endregion #region ExploreTestsAction /// <summary> /// ExploreTestsAction returns info about the tests in an assembly /// </summary> public class ExploreTestsAction : FrameworkControllerAction { /// <summary> /// Initializes a new instance of the <see cref="ExploreTestsAction"/> class. /// </summary> /// <param name="controller">The controller for which this action is being performed.</param> /// <param name="filter">Filter used to control which tests are included (NYI)</param> /// <param name="handler">The callback handler.</param> public ExploreTestsAction(FrameworkController controller, string filter, object handler) { controller.ExploreTests((ICallbackEventHandler)handler, filter); } } #endregion #region CountTestsAction /// <summary> /// CountTestsAction counts the number of test cases in the loaded TestSuite /// held by the FrameworkController. /// </summary> public class CountTestsAction : FrameworkControllerAction { /// <summary> /// Construct a CountsTestAction and perform the count of test cases. /// </summary> /// <param name="controller">A FrameworkController holding the TestSuite whose cases are to be counted</param> /// <param name="filter">A string containing the XML representation of the filter to use</param> /// <param name="handler">A callback handler used to report results</param> public CountTestsAction(FrameworkController controller, string filter, object handler) { controller.CountTests((ICallbackEventHandler)handler, filter); } } #endregion #region RunTestsAction /// <summary> /// RunTestsAction runs the loaded TestSuite held by the FrameworkController. /// </summary> public class RunTestsAction : FrameworkControllerAction { /// <summary> /// Construct a RunTestsAction and run all tests in the loaded TestSuite. /// </summary> /// <param name="controller">A FrameworkController holding the TestSuite to run</param> /// <param name="filter">A string containing the XML representation of the filter to use</param> /// <param name="handler">A callback handler used to report results</param> public RunTestsAction(FrameworkController controller, string filter, object handler) { controller.RunTests((ICallbackEventHandler)handler, filter); } } #endregion #region RunAsyncAction /// <summary> /// RunAsyncAction initiates an asynchronous test run, returning immediately /// </summary> public class RunAsyncAction : FrameworkControllerAction { /// <summary> /// Construct a RunAsyncAction and run all tests in the loaded TestSuite. /// </summary> /// <param name="controller">A FrameworkController holding the TestSuite to run</param> /// <param name="filter">A string containing the XML representation of the filter to use</param> /// <param name="handler">A callback handler used to report results</param> public RunAsyncAction(FrameworkController controller, string filter, object handler) { controller.RunAsync((ICallbackEventHandler)handler, filter); } } #endregion #region StopRunAction /// <summary> /// StopRunAction stops an ongoing run. /// </summary> public class StopRunAction : FrameworkControllerAction { /// <summary> /// Construct a StopRunAction and stop any ongoing run. If no /// run is in process, no error is raised. /// </summary> /// <param name="controller">The FrameworkController for which a run is to be stopped.</param> /// <param name="force">True the stop should be forced, false for a cooperative stop.</param> /// <param name="handler">>A callback handler used to report results</param> /// <remarks>A forced stop will cause threads and processes to be killed as needed.</remarks> public StopRunAction(FrameworkController controller, bool force, object handler) { controller.StopRun((ICallbackEventHandler)handler, force); } } #endregion #endregion } }
using System; using System.ComponentModel.Design; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Input; using System.Windows.Threading; using Microsoft.VisualStudio; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.TextManager.Interop; using NuGet.VisualStudio; using NuGetConsole.Implementation.Console; using NuGetConsole.Implementation.PowerConsole; namespace NuGetConsole.Implementation { /// <summary> /// This class implements the tool window. /// </summary> [Guid("0AD07096-BBA9-4900-A651-0598D26F6D24")] public sealed class PowerConsoleToolWindow : ToolWindowPane, IOleCommandTarget, IPowerConsoleService { /// <summary> /// Get VS IComponentModel service. /// </summary> private IComponentModel ComponentModel { get { return this.GetService<IComponentModel>(typeof(SComponentModel)); } } private IProductUpdateService ProductUpdateService { get { return ComponentModel.GetService<IProductUpdateService>(); } } private IPackageRestoreManager PackageRestoreManager { get { return ComponentModel.GetService<IPackageRestoreManager>(); } } private PowerConsoleWindow PowerConsoleWindow { get { return ComponentModel.GetService<IPowerConsoleWindow>() as PowerConsoleWindow; } } private IVsUIShell VsUIShell { get { return this.GetService<IVsUIShell>(typeof(SVsUIShell)); } } private bool IsToolbarEnabled { get { return _wpfConsole != null && _wpfConsole.Dispatcher.IsStartCompleted && _wpfConsole.Host != null && _wpfConsole.Host.IsCommandEnabled; } } /// <summary> /// Standard constructor for the tool window. /// </summary> public PowerConsoleToolWindow() : base(null) { this.Caption = Resources.ToolWindowTitle; this.BitmapResourceID = 301; this.BitmapIndex = 0; this.ToolBar = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.idToolbar); } protected override void Initialize() { base.Initialize(); OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (mcs != null) { // Get list command for the Feed combo CommandID sourcesListCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidSourcesList); mcs.AddCommand(new OleMenuCommand(SourcesList_Exec, sourcesListCommandID)); // invoke command for the Feed combo CommandID sourcesCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidSources); mcs.AddCommand(new OleMenuCommand(Sources_Exec, sourcesCommandID)); // get default project command CommandID projectsListCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidProjectsList); mcs.AddCommand(new OleMenuCommand(ProjectsList_Exec, projectsListCommandID)); // invoke command for the Default project combo CommandID projectsCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidProjects); mcs.AddCommand(new OleMenuCommand(Projects_Exec, projectsCommandID)); // clear console command CommandID clearHostCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidClearHost); mcs.AddCommand(new OleMenuCommand(ClearHost_Exec, clearHostCommandID)); // terminate command execution command CommandID stopHostCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidStopHost); mcs.AddCommand(new OleMenuCommand(StopHost_Exec, stopHostCommandID)); } } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We really don't want exceptions from the console to bring down VS")] public override void OnToolWindowCreated() { // Register key bindings to use in the editor var windowFrame = (IVsWindowFrame)Frame; Guid cmdUi = VSConstants.GUID_TextEditorFactory; windowFrame.SetGuidProperty((int)__VSFPROPID.VSFPROPID_InheritKeyBindings, ref cmdUi); // pause for a tiny moment to let the tool window open before initializing the host var timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromMilliseconds(10); timer.Tick += (o, e) => { // all exceptions from the timer thread should be caught to avoid crashing VS try { LoadConsoleEditor(); timer.Stop(); } catch (Exception x) { ExceptionHelper.WriteToActivityLog(x); } }; timer.Start(); base.OnToolWindowCreated(); } protected override void OnClose() { base.OnClose(); if (_wpfConsole != null) { _wpfConsole.Dispose(); } } /// <summary> /// This override allows us to forward these messages to the editor instance as well /// </summary> /// <param name="m"></param> /// <returns></returns> protected override bool PreProcessMessage(ref System.Windows.Forms.Message m) { IVsWindowPane vsWindowPane = this.VsTextView as IVsWindowPane; if (vsWindowPane != null) { MSG[] pMsg = new MSG[1]; pMsg[0].hwnd = m.HWnd; pMsg[0].message = (uint)m.Msg; pMsg[0].wParam = m.WParam; pMsg[0].lParam = m.LParam; return vsWindowPane.TranslateAccelerator(pMsg) == 0; } return base.PreProcessMessage(ref m); } /// <summary> /// Override to forward to editor or handle accordingly if supported by this tool window. /// </summary> int IOleCommandTarget.QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { // examine buttons within our toolbar if (pguidCmdGroup == GuidList.guidNuGetCmdSet) { bool isEnabled = IsToolbarEnabled; if (isEnabled) { bool isStopButton = (prgCmds[0].cmdID == 0x0600); // 0x0600 is the Command ID of the Stop button, defined in .vsct // when command is executing: enable stop button and disable the rest // when command is not executing: disable the stop button and enable the rest isEnabled = !isStopButton ^ WpfConsole.Dispatcher.IsExecutingCommand; } if (isEnabled) { prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED); } else { prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED); } return VSConstants.S_OK; } int hr = OleCommandFilter.OLECMDERR_E_NOTSUPPORTED; if (this.VsTextView != null) { IOleCommandTarget cmdTarget = (IOleCommandTarget)VsTextView; hr = cmdTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } if (hr == OleCommandFilter.OLECMDERR_E_NOTSUPPORTED || hr == OleCommandFilter.OLECMDERR_E_UNKNOWNGROUP) { IOleCommandTarget target = this.GetService(typeof(IOleCommandTarget)) as IOleCommandTarget; if (target != null) { hr = target.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } } return hr; } /// <summary> /// Override to forward to editor or handle accordingly if supported by this tool window. /// </summary> int IOleCommandTarget.Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { int hr = OleCommandFilter.OLECMDERR_E_NOTSUPPORTED; if (this.VsTextView != null) { IOleCommandTarget cmdTarget = (IOleCommandTarget)VsTextView; hr = cmdTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } if (hr == OleCommandFilter.OLECMDERR_E_NOTSUPPORTED || hr == OleCommandFilter.OLECMDERR_E_UNKNOWNGROUP) { IOleCommandTarget target = this.GetService(typeof(IOleCommandTarget)) as IOleCommandTarget; if (target != null) { hr = target.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } } return hr; } private void SourcesList_Exec(object sender, EventArgs e) { OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs; if (args != null) { if (args.InValue != null || args.OutValue == IntPtr.Zero) { throw new ArgumentException("Invalid argument", "e"); } Marshal.GetNativeVariantForObject(PowerConsoleWindow.PackageSources, args.OutValue); } } /// <summary> /// Called to retrieve current combo item name or to select a new item. /// </summary> private void Sources_Exec(object sender, EventArgs e) { OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs; if (args != null) { if (args.InValue != null && args.InValue is int) // Selected a feed { int index = (int)args.InValue; if (index >= 0 && index < PowerConsoleWindow.PackageSources.Length) { PowerConsoleWindow.ActivePackageSource = PowerConsoleWindow.PackageSources[index]; } } else if (args.OutValue != IntPtr.Zero) // Query selected feed name { string displayName = PowerConsoleWindow.ActivePackageSource ?? string.Empty; Marshal.GetNativeVariantForObject(displayName, args.OutValue); } } } private void ProjectsList_Exec(object sender, EventArgs e) { OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs; if (args != null) { if (args.InValue != null || args.OutValue == IntPtr.Zero) { throw new ArgumentException("Invalid argument", "e"); } // get project list here Marshal.GetNativeVariantForObject(PowerConsoleWindow.AvailableProjects, args.OutValue); } } /// <summary> /// Called to retrieve current combo item name or to select a new item. /// </summary> private void Projects_Exec(object sender, EventArgs e) { OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs; if (args != null) { if (args.InValue != null && args.InValue is int) { // Selected a default projects int index = (int)args.InValue; if (index >= 0 && index < PowerConsoleWindow.AvailableProjects.Length) { PowerConsoleWindow.SetDefaultProjectIndex(index); } } else if (args.OutValue != IntPtr.Zero) { string displayName = PowerConsoleWindow.DefaultProject ?? string.Empty; Marshal.GetNativeVariantForObject(displayName, args.OutValue); } } } /// <summary> /// ClearHost command handler. /// </summary> private void ClearHost_Exec(object sender, EventArgs e) { if (WpfConsole != null) { WpfConsole.Dispatcher.ClearConsole(); } } private void StopHost_Exec(object sender, EventArgs e) { if (WpfConsole != null) { WpfConsole.Host.Abort(); } } private HostInfo ActiveHostInfo { get { return PowerConsoleWindow.ActiveHostInfo; } } private void LoadConsoleEditor() { if (WpfConsole != null) { // allow the console to start writing output WpfConsole.StartWritingOutput(); FrameworkElement consolePane = WpfConsole.Content as FrameworkElement; ConsoleParentPane.AddConsoleEditor(consolePane); // WPF doesn't handle input focus automatically in this scenario. We // have to set the focus manually, otherwise the editor is displayed but // not focused and not receiving keyboard inputs until clicked. if (consolePane != null) { PendingMoveFocus(consolePane); } } } /// <summary> /// Set pending focus to a console pane. At the time of setting active host, /// the pane (UIElement) is usually not loaded yet and can't receive focus. /// In this case, we need to set focus in its Loaded event. /// </summary> /// <param name="consolePane"></param> private void PendingMoveFocus(FrameworkElement consolePane) { if (consolePane.IsLoaded && consolePane.IsConnectedToPresentationSource()) { PendingFocusPane = null; MoveFocus(consolePane); } else { PendingFocusPane = consolePane; } } private FrameworkElement _pendingFocusPane; private FrameworkElement PendingFocusPane { get { return _pendingFocusPane; } set { if (_pendingFocusPane != null) { _pendingFocusPane.Loaded -= PendingFocusPane_Loaded; } _pendingFocusPane = value; if (_pendingFocusPane != null) { _pendingFocusPane.Loaded += PendingFocusPane_Loaded; } } } private void PendingFocusPane_Loaded(object sender, RoutedEventArgs e) { MoveFocus(PendingFocusPane); PendingFocusPane = null; } private void MoveFocus(FrameworkElement consolePane) { // TAB focus into editor (consolePane.Focus() does not work due to editor layouts) consolePane.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)); // Try start the console session now. This needs to be after the console // pane getting focus to avoid incorrect initial editor layout. StartConsoleSession(consolePane); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We really don't want exceptions from the console to bring down VS")] private void StartConsoleSession(FrameworkElement consolePane) { if (WpfConsole != null && WpfConsole.Content == consolePane && WpfConsole.Host != null) { try { if (WpfConsole.Dispatcher.IsStartCompleted) { OnDispatcherStartCompleted(); // if the dispatcher was started before we reach here, // it means the dispatcher has been in read-only mode (due to _startedWritingOutput = false). // enable key input now. WpfConsole.Dispatcher.AcceptKeyInput(); } else { WpfConsole.Dispatcher.StartCompleted += (sender, args) => OnDispatcherStartCompleted(); WpfConsole.Dispatcher.StartWaitingKey += OnDispatcherStartWaitingKey; WpfConsole.Dispatcher.Start(); } } catch (Exception x) { // hide the text "initialize host" when an error occurs. ConsoleParentPane.NotifyInitializationCompleted(); WpfConsole.WriteLine(x.GetBaseException().ToString()); ExceptionHelper.WriteToActivityLog(x); } } else { ConsoleParentPane.NotifyInitializationCompleted(); } } private void OnDispatcherStartWaitingKey(object sender, EventArgs args) { WpfConsole.Dispatcher.StartWaitingKey -= OnDispatcherStartWaitingKey; // we want to hide the text "initialize host..." when waiting for key input ConsoleParentPane.NotifyInitializationCompleted(); } private void OnDispatcherStartCompleted() { WpfConsole.Dispatcher.StartWaitingKey -= OnDispatcherStartWaitingKey; ConsoleParentPane.NotifyInitializationCompleted(); // force the UI to update the toolbar VsUIShell.UpdateCommandUI(0 /* false = update UI asynchronously */); NuGetEventTrigger.Instance.TriggerEvent(NuGetEvent.PackageManagerConsoleLoaded); } private IWpfConsole _wpfConsole; /// <summary> /// Get the WpfConsole of the active host. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private IWpfConsole WpfConsole { get { if (_wpfConsole == null) { _wpfConsole = ActiveHostInfo.WpfConsole; } return _wpfConsole; } } private IVsTextView _vsTextView; /// <summary> /// Get the VsTextView of current WpfConsole if exists. /// </summary> private IVsTextView VsTextView { get { if (_vsTextView == null && _wpfConsole != null) { _vsTextView = (IVsTextView)(WpfConsole.VsTextView); } return _vsTextView; } } private ConsoleContainer _consoleParentPane; /// <summary> /// Get the parent pane of console panes. This serves as the Content of this tool window. /// </summary> private ConsoleContainer ConsoleParentPane { get { if (_consoleParentPane == null) { _consoleParentPane = new ConsoleContainer(ProductUpdateService, PackageRestoreManager); } return _consoleParentPane; } } public override object Content { get { return this.ConsoleParentPane; } set { base.Content = value; } } #region IPowerConsoleService Region public event EventHandler ExecuteEnd; private ITextSnapshot _snapshot; private int _previousPosition; public bool Execute(string command, object[] inputs) { if (ConsoleStatus.IsBusy) { VSOutputConsole.WriteLine(Resources.PackageManagerConsoleBusy); throw new NotSupportedException(Resources.PackageManagerConsoleBusy); } if (!String.IsNullOrEmpty(command)) { WpfConsole.SetExecutionMode(true); // Cast the ToolWindowPane to PowerConsoleToolWindow // Access the IHost from PowerConsoleToolWindow as follows PowerConsoleToolWindow.WpfConsole.Host // Cast IHost to IAsyncHost // Also, register for IAsyncHost.ExecutedEnd and return only when the command is completed IPrivateWpfConsole powerShellConsole = (IPrivateWpfConsole)WpfConsole; IHost host = powerShellConsole.Host; var asynchost = host as IAsyncHost; if (asynchost != null) { asynchost.ExecuteEnd += PowerConsoleCommand_ExecuteEnd; } // Here, we store the snapshot of the powershell Console output text buffer // Snapshot has reference to the buffer and the current length of the buffer // And, upon execution of the command, (check the commandexecuted handler) // the changes to the buffer is identified and copied over to the VS output window if (powerShellConsole.InputLineStart != null && powerShellConsole.InputLineStart.Value.Snapshot != null) { _snapshot = powerShellConsole.InputLineStart.Value.Snapshot; } // We should write the command to the console just to imitate typical user action before executing it // Asserts get fired otherwise. Also, the log is displayed in a disorderly fashion powerShellConsole.WriteLine(command); return host.Execute(powerShellConsole, command, null); } return false; } private void PowerConsoleCommand_ExecuteEnd(object sender, EventArgs e) { // Flush the change in console text buffer onto the output window for testability // If the VSOutputConsole could not be obtained, just ignore if (VSOutputConsole != null && _snapshot != null) { if (_previousPosition < _snapshot.Length) { VSOutputConsole.WriteLine(_snapshot.GetText(_previousPosition, (_snapshot.Length - _previousPosition))); } _previousPosition = _snapshot.Length; } (sender as IAsyncHost).ExecuteEnd -= PowerConsoleCommand_ExecuteEnd; WpfConsole.SetExecutionMode(false); // This does NOT imply that the command succeeded. It just indicates that the console is ready for input now VSOutputConsole.WriteLine(Resources.PackageManagerConsoleCommandExecuted); ExecuteEnd.Raise(this, EventArgs.Empty); } private IConsole _vsOutputConsole = null; private IConsole VSOutputConsole { get { if (_vsOutputConsole == null) { IOutputConsoleProvider outputConsoleProvider = ServiceLocator.GetInstance<IOutputConsoleProvider>(); if (null != outputConsoleProvider) { _vsOutputConsole = outputConsoleProvider.CreateOutputConsole(requirePowerShellHost: false); } } return _vsOutputConsole; } } private IConsoleStatus _consoleStatus; private IConsoleStatus ConsoleStatus { get { if (_consoleStatus == null) { _consoleStatus = ServiceLocator.GetInstance<IConsoleStatus>(); Debug.Assert(_consoleStatus != null); } return _consoleStatus; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MultiplyAddSubtractSingle() { var test = new AlternatingTernaryOpTest__MultiplyAddSubtractSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class AlternatingTernaryOpTest__MultiplyAddSubtractSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] inArray3, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Single, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public Vector128<Single> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(AlternatingTernaryOpTest__MultiplyAddSubtractSingle testClass) { var result = Fma.MultiplyAddSubtract(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(AlternatingTernaryOpTest__MultiplyAddSubtractSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) fixed (Vector128<Single>* pFld3 = &_fld3) { var result = Fma.MultiplyAddSubtract( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)), Sse.LoadVector128((Single*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Single[] _data3 = new Single[Op3ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private static Vector128<Single> _clsVar3; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private Vector128<Single> _fld3; private DataTable _dataTable; static AlternatingTernaryOpTest__MultiplyAddSubtractSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public AlternatingTernaryOpTest__MultiplyAddSubtractSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, _data3, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Fma.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Fma.MultiplyAddSubtract( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Fma.MultiplyAddSubtract( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Fma.MultiplyAddSubtract( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplyAddSubtract), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplyAddSubtract), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Fma).GetMethod(nameof(Fma.MultiplyAddSubtract), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Fma.MultiplyAddSubtract( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Single>* pClsVar2 = &_clsVar2) fixed (Vector128<Single>* pClsVar3 = &_clsVar3) { var result = Fma.MultiplyAddSubtract( Sse.LoadVector128((Single*)(pClsVar1)), Sse.LoadVector128((Single*)(pClsVar2)), Sse.LoadVector128((Single*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray3Ptr); var result = Fma.MultiplyAddSubtract(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var op3 = Sse.LoadVector128((Single*)(_dataTable.inArray3Ptr)); var result = Fma.MultiplyAddSubtract(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var op3 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray3Ptr)); var result = Fma.MultiplyAddSubtract(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new AlternatingTernaryOpTest__MultiplyAddSubtractSingle(); var result = Fma.MultiplyAddSubtract(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new AlternatingTernaryOpTest__MultiplyAddSubtractSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) fixed (Vector128<Single>* pFld3 = &test._fld3) { var result = Fma.MultiplyAddSubtract( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)), Sse.LoadVector128((Single*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Fma.MultiplyAddSubtract(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) fixed (Vector128<Single>* pFld3 = &_fld3) { var result = Fma.MultiplyAddSubtract( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)), Sse.LoadVector128((Single*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Fma.MultiplyAddSubtract(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Fma.MultiplyAddSubtract( Sse.LoadVector128((Single*)(&test._fld1)), Sse.LoadVector128((Single*)(&test._fld2)), Sse.LoadVector128((Single*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, Vector128<Single> op3, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] inArray3 = new Single[Op3ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] inArray3 = new Single[Op3ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] secondOp, Single[] thirdOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i += 2) { if (BitConverter.SingleToInt32Bits(MathF.Round((firstOp[i] * secondOp[i]) - thirdOp[i], 3)) != BitConverter.SingleToInt32Bits(MathF.Round(result[i], 3))) { succeeded = false; break; } if (BitConverter.SingleToInt32Bits(MathF.Round((firstOp[i + 1] * secondOp[i + 1]) + thirdOp[i + 1], 3)) != BitConverter.SingleToInt32Bits(MathF.Round(result[i + 1], 3))) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplyAddSubtract)}<Single>(Vector128<Single>, Vector128<Single>, Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using Prism.Windows.AppModel; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Windows.ApplicationModel.Resources; using Windows.UI.Xaml; using Windows.UI.Xaml.Navigation; namespace Prism.Windows.Navigation { /// <summary> /// The FrameNavigationService interface is used for navigating across the pages of your Windows Store app. /// The FrameNavigationService class, uses a class that implements the IFrameFacade interface to provide page navigation. /// </summary> public class FrameNavigationService : INavigationService { private const string LastNavigationParameterKey = "LastNavigationParameter"; private const string LastNavigationPageKey = "LastNavigationPageKey"; private readonly IFrameFacade _frame; private readonly Func<string, Type> _navigationResolver; private readonly ISessionStateService _sessionStateService; /// <summary> /// Initializes a new instance of the <see cref="FrameNavigationService"/> class. /// </summary> /// <param name="frame">The frame.</param> /// <param name="navigationResolver">The navigation resolver.</param> /// <param name="sessionStateService">The session state service.</param> public FrameNavigationService(IFrameFacade frame, Func<string, Type> navigationResolver, ISessionStateService sessionStateService) { _frame = frame; _navigationResolver = navigationResolver; _sessionStateService = sessionStateService; if (frame != null) { _frame.NavigatingFrom += OnFrameNavigatingFrom; _frame.NavigatedTo += OnFrameNavigatedTo; } } /// <summary> /// Navigates to the page with the specified page token, passing the specified parameter. /// </summary> /// <param name="pageToken">The page token.</param> /// <param name="parameter">The parameter.</param> /// <returns>Returns <c>true</c> if the navigation succeeds: otherwise, <c>false</c>.</returns> public bool Navigate(string pageToken, object parameter) { Type pageType = _navigationResolver(pageToken); if (pageType == null) { var resourceLoader = ResourceLoader.GetForCurrentView(Constants.InfrastructureResourceMapId); var error = string.Format(CultureInfo.CurrentCulture, resourceLoader.GetString("FrameNavigationServiceUnableResolveMessage"), pageToken); throw new ArgumentException(error, nameof(pageToken)); } object lastNavigationParameter; _sessionStateService.SessionState.TryGetValue(LastNavigationParameterKey, out lastNavigationParameter); object lastPageTypeFullName; if (!_sessionStateService.SessionState.TryGetValue(LastNavigationPageKey, out lastPageTypeFullName)) lastPageTypeFullName = string.Empty; if ((string)lastPageTypeFullName != pageType.FullName || !AreEquals(lastNavigationParameter, parameter)) { return _frame.Navigate(pageType, parameter); } return false; } /// <summary> /// Goes to the previous page in the navigation stack. /// </summary> public void GoBack() { _frame.GoBack(); } /// <summary> /// Determines whether the navigation service can navigate to the previous page or not. /// </summary> /// <returns> /// <c>true</c> if the navigation service can go back; otherwise, <c>false</c>. /// </returns> public bool CanGoBack() { return _frame.CanGoBack; } /// <summary> /// Goes to the next page in the navigation stack. /// </summary> public void GoForward() { _frame.GoForward(); } /// <summary> /// Determines whether the navigation service can navigate to the next page or not. /// </summary> /// <returns> /// <c>true</c> if the navigation service can go forward; otherwise, <c>false</c>. /// </returns> public bool CanGoForward() { return _frame.CanGoForward(); } /// <summary> /// Clears the navigation history. /// </summary> public void ClearHistory() { _frame.SetNavigationState("1,0"); } public void RemoveFirstPage(string pageToken = null, object parameter = null) { PageStackEntry page; if (pageToken != null) { var pageType = _navigationResolver(pageToken); if (parameter != null) { page = _frame.BackStack.FirstOrDefault(x => x.SourcePageType == pageType && x.Parameter.Equals(parameter)); } else { page = _frame.BackStack.FirstOrDefault(x => x.SourcePageType == pageType); } } else { page = _frame.BackStack.FirstOrDefault(); } if (page != null) { _frame.BackStack.Remove(page); } } public void RemoveLastPage(string pageToken = null, object parameter = null) { PageStackEntry page; if (pageToken != null) { var pageType = _navigationResolver(pageToken); if (parameter != null) { page = _frame.BackStack.LastOrDefault(x => x.SourcePageType == pageType && x.Parameter.Equals(parameter)); } else { page = _frame.BackStack.LastOrDefault(x => x.SourcePageType == pageType); } } else { page = _frame.BackStack.LastOrDefault(); } if (page != null) { _frame.BackStack.Remove(page); } } public void RemoveAllPages(string pageToken = null, object parameter = null) { if (pageToken != null) { IEnumerable<PageStackEntry> pages; var pageType = _navigationResolver(pageToken); if (parameter != null) { pages = _frame.BackStack.Where(x => x.SourcePageType == pageType && x.Parameter.Equals(parameter)); } else { pages = _frame.BackStack.Where(x => x.SourcePageType == pageType); } foreach (var page in pages) { _frame.BackStack.Remove(page); } } else { _frame.BackStack.Clear(); } } /// <summary> /// Restores the saved navigation. /// </summary> public void RestoreSavedNavigation() { NavigateToCurrentViewModel(new NavigatedToEventArgs() { NavigationMode = NavigationMode.Refresh, Parameter = _sessionStateService.SessionState[LastNavigationParameterKey] }); } /// <summary> /// Used for navigating away from the current view model due to a suspension event, in this way you can execute additional logic to handle suspensions. /// </summary> public void Suspending() { NavigateFromCurrentViewModel(new NavigatingFromEventArgs(), true); } /// <summary> /// This method is triggered after navigating to a view model. It is used to load the view model state that was saved previously. /// </summary> /// <param name="e">The <see cref="NavigatedToEventArgs"/> instance containing the event data.</param> private void NavigateToCurrentViewModel(NavigatedToEventArgs e) { var frameState = _sessionStateService.GetSessionStateForFrame(_frame); var viewModelKey = "ViewModel-" + _frame.BackStackDepth; if (e.NavigationMode == NavigationMode.New) { // Clear existing state for forward navigation when adding a new page/view model to the // navigation stack var nextViewModelKey = viewModelKey; int nextViewModelIndex = _frame.BackStackDepth; while (frameState.Remove(nextViewModelKey)) { nextViewModelIndex++; nextViewModelKey = "ViewModel-" + nextViewModelIndex; } } var newView = _frame.Content as FrameworkElement; if (newView == null) return; var newViewModel = newView.DataContext as INavigationAware; if (newViewModel != null) { Dictionary<string, object> viewModelState; if (frameState.ContainsKey(viewModelKey)) { viewModelState = frameState[viewModelKey] as Dictionary<string, object>; } else { viewModelState = new Dictionary<string, object>(); } newViewModel.OnNavigatedTo(e, viewModelState); frameState[viewModelKey] = viewModelState; } } /// <summary> /// Navigates away from the current viewmodel. /// </summary> /// <param name="e">The <see cref="NavigatingFromEventArgs"/> instance containing the event data.</param> /// <param name="suspending">True if it is navigating away from the viewmodel due to a suspend event.</param> private void NavigateFromCurrentViewModel(NavigatingFromEventArgs e, bool suspending) { var departingView = _frame.Content as FrameworkElement; if (departingView == null) return; var frameState = _sessionStateService.GetSessionStateForFrame(_frame); var departingViewModel = departingView.DataContext as INavigationAware; var viewModelKey = "ViewModel-" + _frame.BackStackDepth; if (departingViewModel != null) { var viewModelState = frameState.ContainsKey(viewModelKey) ? frameState[viewModelKey] as Dictionary<string, object> : null; departingViewModel.OnNavigatingFrom(e, viewModelState, suspending); } } /// <summary> /// Handles the Navigating event of the Frame control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="NavigatingFromEventArgs"/> instance containing the event data.</param> private void OnFrameNavigatingFrom(object sender, NavigatingFromEventArgs e) { NavigateFromCurrentViewModel(e, false); } /// <summary> /// Handles the Navigated event of the Frame control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="NavigatedToEventArgs"/> instance containing the event data.</param> private void OnFrameNavigatedTo(object sender, NavigatedToEventArgs e) { // Update the page type and parameter of the last navigation _sessionStateService.SessionState[LastNavigationPageKey] = _frame.Content.GetType().FullName; _sessionStateService.SessionState[LastNavigationParameterKey] = e.Parameter; NavigateToCurrentViewModel(e); } /// <summary> /// Returns true if both objects are equal. Two objects are equal if they are null or the same string object. /// </summary> /// <param name="obj1">First object to compare.</param> /// <param name="obj2">Second object to compare.</param> /// <returns>Returns <c>true</c> if both parameters are equal; otherwise, <c>false</c>.</returns> private static bool AreEquals(object obj1, object obj2) { if (obj1 != null) { return obj1.Equals(obj2); } return obj2 == null; } } }
using System; using NUnit.Framework; using System.Net.Sockets; using System.IO; using AutoTest.Messages.Serializers; using AutoTest.Messages; using AutoTest.Core.Messaging; namespace AutoTest.Test { [TestFixture] public class SerializerTests { private CustomBinaryFormatter _formatter; [SetUp] public void SetUp() { _formatter = new CustomBinaryFormatter(); } [Test] public void Should_serialize_build_run_message() { var results = new BuildRunResults("Project"); results.AddError(new BuildMessage() { File = "file", LineNumber = 15, LinePosition = 20, ErrorMessage = "Error message" }); results.AddWarning(new BuildMessage() { File = "file2", LineNumber = 35, LinePosition = 40, ErrorMessage = "Error message2" }); results.SetTimeSpent(new TimeSpan(23567)); var message = new BuildRunMessage(results); var output = serializeDeserialize<BuildRunMessage>(message); output.Results.Project.ShouldEqual("Project"); output.Results.TimeSpent.ShouldEqual(new TimeSpan(23567)); output.Results.ErrorCount.ShouldEqual(1); output.Results.Errors[0].File.ShouldEqual("file"); output.Results.Errors[0].LineNumber.ShouldEqual(15); output.Results.Errors[0].LinePosition.ShouldEqual(20); output.Results.Errors[0].ErrorMessage.ShouldEqual("Error message"); output.Results.WarningCount.ShouldEqual(1); output.Results.Warnings[0].File.ShouldEqual("file2"); output.Results.Warnings[0].LineNumber.ShouldEqual(35); output.Results.Warnings[0].LinePosition.ShouldEqual(40); output.Results.Warnings[0].ErrorMessage.ShouldEqual("Error message2"); } [Test] public void Should_serialize_error_message() { var message = new ErrorMessage("erro message"); var output = serializeDeserialize<ErrorMessage>(message); output.Error.ShouldEqual("erro message"); } [Test] public void Should_serialize_information_message() { var message = new InformationMessage("information message"); var output = serializeDeserialize<InformationMessage>(message); output.Message.ShouldEqual("information message"); } [Test] public void Should_serialize_run_finished_message() { var runreport = new RunReport(); runreport.AddBuild("project 1", new TimeSpan(23), true); runreport.AddBuild("project 2", new TimeSpan(12), false); runreport.AddTestRun("project 2", "assembly", new TimeSpan(52), 12, 1, 2); runreport.WasAborted(); var message = new RunFinishedMessage(runreport); var output = serializeDeserialize<RunFinishedMessage>(message); output.Report.NumberOfBuildsSucceeded.ShouldEqual(1); output.Report.NumberOfBuildsFailed.ShouldEqual(1); output.Report.RunActions[0].Project.ShouldEqual("project 1"); output.Report.RunActions[0].Type.ShouldEqual(InformationType.Build); output.Report.RunActions[0].Succeeded.ShouldEqual(true); output.Report.RunActions[0].TimeSpent.ShouldEqual(new TimeSpan(23)); output.Report.RunActions[1].Project.ShouldEqual("project 2"); output.Report.RunActions[1].Type.ShouldEqual(InformationType.Build); output.Report.RunActions[1].Succeeded.ShouldEqual(false); output.Report.RunActions[1].TimeSpent.ShouldEqual(new TimeSpan(12)); output.Report.Aborted.ShouldBeTrue(); output.Report.NumberOfTestsPassed.ShouldEqual(12); output.Report.NumberOfTestsFailed.ShouldEqual(2); output.Report.NumberOfTestsIgnored.ShouldEqual(1); output.Report.RunActions[2].Project.ShouldEqual("project 2"); output.Report.RunActions[2].Assembly.ShouldEqual("assembly"); output.Report.RunActions[2].Type.ShouldEqual(InformationType.TestRun); output.Report.RunActions[2].Succeeded.ShouldEqual(false); output.Report.RunActions[2].TimeSpent.ShouldEqual(new TimeSpan(52)); } [Test] public void Should_serialize_run_information_message() { var message = new RunInformationMessage(InformationType.TestRun, "project 1", "assembly", typeof(RunFinishedMessage)); var output = serializeDeserialize<RunInformationMessage>(message); output.Project.ShouldEqual("project 1"); output.Assembly.ShouldEqual("assembly"); output.Type.ShouldEqual(InformationType.TestRun); output.Runner.ShouldEqual(typeof(RunFinishedMessage)); } [Test] public void Should_serialize_run_started_message() { var files = new ChangedFile[] { new ChangedFile(System.Reflection.Assembly.GetExecutingAssembly().FullName) }; var message = new RunStartedMessage(files); var output = serializeDeserialize<RunStartedMessage>(message); output.Files.Length.ShouldEqual(1); output.Files[0].Name.ShouldEqual(files[0].Name); output.Files[0].FullName.ShouldEqual(files[0].FullName); output.Files[0].Extension.ShouldEqual(files[0].Extension); } [Test] public void Should_serialize_warning_message() { var message = new WarningMessage("warning"); var output = serializeDeserialize<WarningMessage>(message); output.Warning.ShouldEqual("warning"); } [Test] public void Should_serialize_test_run_message() { var testResults = new TestResult[] { new TestResult(TestRunner.NUnit, TestRunStatus.Passed, "Test name", "message", new IStackLine[] { new StackLineMessage("method name", "file", 13) }, 34).SetDisplayName("display name") }; var results = new TestRunResults("project 1", "assembly", false, TestRunner.NUnit, testResults); results.SetTimeSpent(new TimeSpan(12345)); var message = new TestRunMessage(results); var output = serializeDeserialize<TestRunMessage>(message); output.Results.Project.ShouldEqual("project 1"); output.Results.Assembly.ShouldEqual("assembly"); output.Results.IsPartialTestRun.ShouldBeFalse(); output.Results.TimeSpent.ShouldEqual(new TimeSpan(12345)); output.Results.All.Length.ShouldEqual(1); output.Results.All[0].Runner.ShouldEqual(TestRunner.NUnit); output.Results.All[0].Status.ShouldEqual(TestRunStatus.Passed); output.Results.All[0].Name.ShouldEqual("Test name"); output.Results.All[0].DisplayName.ShouldEqual("display name"); output.Results.All[0].Message.ShouldEqual("message"); output.Results.All[0].StackTrace[0].Method.ShouldEqual("method name"); output.Results.All[0].StackTrace[0].File.ShouldEqual("file"); output.Results.All[0].StackTrace[0].LineNumber.ShouldEqual(13); output.Results.All[0].TimeSpent.TotalMilliseconds.ShouldEqual(34); } [Test] public void Should_serialize_file_change_message() { var file = new ChangedFile(System.Reflection.Assembly.GetExecutingAssembly().FullName); var message = new FileChangeMessage(); message.AddFile(file); var output = serializeDeserialize<FileChangeMessage>(message); output.Files.Length.ShouldEqual(1); output.Files[0].Name.ShouldEqual(file.Name); output.Files[0].FullName.ShouldEqual(file.FullName); output.Files[0].Extension.ShouldEqual(file.Extension); } [Test] public void Should_serialize_file_external_command_message() { var message = new ExternalCommandMessage("a sender", "a command"); var output = serializeDeserialize<ExternalCommandMessage>(message); output.Sender.ShouldEqual("a sender"); output.Command.ShouldEqual("a command"); } [Test] public void Should_serialize_live_status_message() { var message = new LiveTestStatusMessage("assembly1", "currenttest", 10, 5, new LiveTestStatus[] { new LiveTestStatus("", new TestResult(TestRunner.Any, TestRunStatus.Failed, "")) }, new LiveTestStatus[] { new LiveTestStatus("", new TestResult(TestRunner.Any, TestRunStatus.Failed, "")) }); var output = serializeDeserialize<LiveTestStatusMessage>(message); output.CurrentAssembly.ShouldEqual("assembly1"); output.CurrentTest.ShouldEqual("currenttest"); output.TotalNumberOfTests.ShouldEqual(10); output.TestsCompleted.ShouldEqual(5); output.FailedTests.Length.ShouldEqual(1); output.FailedButNowPassingTests.Length.ShouldEqual(1); } [Test] public void Should_serialize_live_status() { var message = new LiveTestStatus("assembly1", new TestResult(TestRunner.Any, TestRunStatus.Failed, "Test1")); var output = serializeDeserialize<LiveTestStatus>(message); output.Assembly.ShouldEqual("assembly1"); output.Test.Name.ShouldEqual("Test1"); } [Test] public void Should_serializeabort_message() { var message = new AbortMessage("some string"); var output = serializeDeserialize(message); output.Reason.ShouldEqual("some string"); } [Test] public void Should_serialize_Cache_message() { var message = new CacheMessages(); message.AddError(new CacheBuildMessage("project1", new BuildMessage() { ErrorMessage = "message", File = "file", LineNumber = 1, LinePosition = 2 })); message.RemoveError(new CacheBuildMessage("project1", new BuildMessage() { ErrorMessage = "message to remove", File = "file", LineNumber = 1, LinePosition = 2 })); message.AddError(new CacheBuildMessage("project2", new BuildMessage() { ErrorMessage = "message2", File = "file2", LineNumber = 1, LinePosition = 2 })); message.AddWarning(new CacheBuildMessage("project3", new BuildMessage() { ErrorMessage = "warning message", File = "warning file", LineNumber = 3, LinePosition = 4 })); message.RemoveWarning(new CacheBuildMessage("project3", new BuildMessage() { ErrorMessage = "warning message to remove", File = "warning file", LineNumber = 3, LinePosition = 4 })); var failed = new TestResult(TestRunner.Any, TestRunStatus.Failed, "test name"); failed.Message = "message"; failed.StackTrace = new StackLineMessage[] { new StackLineMessage("stackmethod", "stack file", 5) }; message.AddFailed(new CacheTestMessage("assembly1", failed)); var failed2 = new TestResult(TestRunner.Any, TestRunStatus.Failed, "test name"); failed2.Message = "message"; failed2.StackTrace = new StackLineMessage[] { new StackLineMessage("stackmethod", "stack file", 5) }; message.AddFailed(new CacheTestMessage("assembly2", failed2)); var ignored = new TestResult(TestRunner.Any, TestRunStatus.Ignored, "test name ignored"); ignored.Message = "message ignored"; ignored.StackTrace = new StackLineMessage[] { new StackLineMessage("stackmethod ignored", "", 6) }; message.AddIgnored(new CacheTestMessage("assembly2", ignored)); ignored = new TestResult(TestRunner.Any, TestRunStatus.Ignored, "test name ignored"); ignored.Message = "message ignored to remove"; ignored.StackTrace = new StackLineMessage[] { new StackLineMessage("stackmethod ignored", "", 6) }; message.RemoveTest(new CacheTestMessage("assembly2", ignored)); var output = serializeDeserialize(message); Assert.AreEqual(2, output.ErrorsToAdd.Length); Assert.AreEqual("project1", output.ErrorsToAdd[0].Project); Assert.AreEqual("message", output.ErrorsToAdd[0].BuildItem.ErrorMessage); Assert.AreEqual("file", output.ErrorsToAdd[0].BuildItem.File); Assert.AreEqual(1, output.ErrorsToAdd[0].BuildItem.LineNumber); Assert.AreEqual(2, output.ErrorsToAdd[0].BuildItem.LinePosition); Assert.AreEqual(1, output.ErrorsToRemove.Length); Assert.AreEqual("message to remove", output.ErrorsToRemove[0].BuildItem.ErrorMessage); Assert.AreEqual(1, output.WarningsToAdd.Length); Assert.AreEqual("project3", output.WarningsToAdd[0].Project); Assert.AreEqual("warning message", output.WarningsToAdd[0].BuildItem.ErrorMessage); Assert.AreEqual("warning file", output.WarningsToAdd[0].BuildItem.File); Assert.AreEqual(3, output.WarningsToAdd[0].BuildItem.LineNumber); Assert.AreEqual(4, output.WarningsToAdd[0].BuildItem.LinePosition); Assert.AreEqual(1, output.WarningsToRemove.Length); Assert.AreEqual("warning message to remove", output.WarningsToRemove[0].BuildItem.ErrorMessage); Assert.AreEqual(2, output.FailedToAdd.Length); Assert.AreEqual("assembly1", output.FailedToAdd[0].Assembly); Assert.AreEqual(TestRunStatus.Failed, output.FailedToAdd[0].Test.Status); Assert.AreEqual("test name", output.FailedToAdd[0].Test.Name); Assert.AreEqual("message", output.FailedToAdd[0].Test.Message); Assert.AreEqual("stackmethod", output.FailedToAdd[0].Test.StackTrace[0].Method); Assert.AreEqual("stack file", output.FailedToAdd[0].Test.StackTrace[0].File); Assert.AreEqual(5, output.FailedToAdd[0].Test.StackTrace[0].LineNumber); Assert.AreEqual(1, output.IgnoredToAdd.Length); Assert.AreEqual("assembly2", output.IgnoredToAdd[0].Assembly); Assert.AreEqual(TestRunStatus.Ignored, output.IgnoredToAdd[0].Test.Status); Assert.AreEqual("test name ignored", output.IgnoredToAdd[0].Test.Name); Assert.AreEqual("message ignored", output.IgnoredToAdd[0].Test.Message); Assert.AreEqual("stackmethod ignored", output.IgnoredToAdd[0].Test.StackTrace[0].Method); Assert.AreEqual("", output.IgnoredToAdd[0].Test.StackTrace[0].File); Assert.AreEqual(6, output.IgnoredToAdd[0].Test.StackTrace[0].LineNumber); Assert.AreEqual(1, output.TestsToRemove.Length); Assert.AreEqual("message ignored to remove", output.TestsToRemove[0].Test.Message); } [Test] public void Should_serialize_Cache_message2() { var message = new CacheMessages(); message.AddWarning(new CacheBuildMessage("project3", new BuildMessage() { ErrorMessage = "warning message", File = "warning file", LineNumber = 3, LinePosition = 4 })); var failed = new TestResult(TestRunner.Any, TestRunStatus.Failed, "AutoTest.Test.Core.Messaging.MessageConsumers.ProjectChangeConsumerTest.Should_run_tests"); failed.Message = "Rhino.Mocks.Exceptions.ExpectationViolationException : ITestRunner.RunTests(any); Expected #1, Actual #0."; failed.StackTrace = new StackLineMessage[] { new StackLineMessage("Rhino.Mocks.RhinoMocksExtensions.AssertWasCalled[T](T mock, Action`1 action, Action`1 setupConstraints)", "", 0), new StackLineMessage("AutoTest.Test.Core.Messaging.MessageConsumers.ProjectChangeConsumerTest.Should_run_tests()", @"c:\Users\ack\src\AutoTest.Net\src\AutoTest.Test\Core\Messaging\MessageConsumers\ProjectChangeConsumerTest.cs", 122) }; message.AddFailed(new CacheTestMessage(@"C:\Users\ack\src\AutoTest.Net\src\AutoTest.Test\bin\Debug\AutoTest.Test.dll", failed)); failed = new TestResult(TestRunner.Any, TestRunStatus.Failed, "AutoTest.Test.Core.Messaging.MessageConsumers.ProjectChangeConsumerTest.Should_run_builds"); failed.Message = "Rhino.Mocks.Exceptions.ExpectationViolationException : IBuildRunner.RunBuild(\"C:\\Users\\ack\\src\\AutoTest.Net\\src\\AutoTest.Test\\bin\\Debug\\someProject.csproj\", \"C:\\Users\\ack\\src\\AutoTest.Net\\src\\AutoTest.Test\\bin\\Debug\\AutoTest.Test.dll\"); Expected #1, Actual #0."; failed.StackTrace = new StackLineMessage[] { new StackLineMessage("Rhino.Mocks.RhinoMocksExtensions.AssertWasCalled[T](T mock, Action`1 action, Action`1 setupConstraints)", "", 0), new StackLineMessage("Rhino.Mocks.RhinoMocksExtensions.AssertWasCalled[T](T mock, Action`1 action)", "", 0), new StackLineMessage("AutoTest.Test.Core.Messaging.MessageConsumers.ProjectChangeConsumerTest.Should_run_builds()", @"c:\Users\ack\src\AutoTest.Net\src\AutoTest.Test\Core\Messaging\MessageConsumers\ProjectChangeConsumerTest.cs", 91) }; message.AddFailed(new CacheTestMessage(@"C:\Users\ack\src\AutoTest.Net\src\AutoTest.Test\bin\Debug\AutoTest.Test.dll", failed)); failed = new TestResult(TestRunner.Any, TestRunStatus.Failed, "AutoTest.Test.Core.Messaging.MessageConsumers.ProjectChangeConsumerTest.Should_pre_process_run_information"); failed.Message = "Rhino.Mocks.Exceptions.ExpectationViolationException : IPreProcessTestruns.PreProcess(any); Expected #1, Actual #0."; failed.StackTrace = new StackLineMessage[] { new StackLineMessage("Rhino.Mocks.RhinoMocksExtensions.AssertWasCalled[T](T mock, Action`1 action, Action`1 setupConstraints)", "", 0), new StackLineMessage("AutoTest.Test.Core.Messaging.MessageConsumers.ProjectChangeConsumerTest.Should_pre_process_run_information()", @"c:\Users\ack\src\AutoTest.Net\src\AutoTest.Test\Core\Messaging\MessageConsumers\ProjectChangeConsumerTest.cs", 160) }; message.AddFailed(new CacheTestMessage(@"C:\Users\ack\src\AutoTest.Net\src\AutoTest.Test\bin\Debug\AutoTest.Test.dll", failed)); var output = serializeDeserialize(message); Assert.IsNotNull(output); } [Test] public void Should_serialize_chache_test_message() { var ignored = new TestResult(TestRunner.Any, TestRunStatus.Ignored, "test name ignored"); ignored.Message = "message ignored"; ignored.StackTrace = new StackLineMessage[] { new StackLineMessage("stackmethod ignored", "stack file ignored", 6) }; var message = new CacheTestMessage("assembly", ignored); var output = serializeDeserialize(message); Assert.AreEqual("assembly", output.Assembly); Assert.AreEqual(TestRunStatus.Ignored, output.Test.Status); Assert.AreEqual("test name ignored", output.Test.Name); Assert.AreEqual("message ignored", output.Test.Message); Assert.AreEqual("stackmethod ignored", output.Test.StackTrace[0].Method); Assert.AreEqual("stack file ignored", output.Test.StackTrace[0].File); Assert.AreEqual(6, output.Test.StackTrace[0].LineNumber); } [Test] public void Should_serialize_chache_build_message() { var item = new BuildMessage() { ErrorMessage = "message", File = "file", LineNumber = 1, LinePosition = 2 }; var message = new CacheBuildMessage("project", item); var output = serializeDeserialize(message); Assert.AreEqual("project", output.Project); Assert.AreEqual("message", output.BuildItem.ErrorMessage); Assert.AreEqual("file", output.BuildItem.File); Assert.AreEqual(1, output.BuildItem.LineNumber); Assert.AreEqual(2, output.BuildItem.LinePosition); } private T serializeDeserialize<T>(T message) { using (var memStream = new MemoryStream()) { _formatter.Serialize(memStream, message); memStream.Seek(0, SeekOrigin.Begin); return (T) _formatter.Deserialize(memStream); } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Management.Automation; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.PowerShell.EditorServices.Services; using Microsoft.PowerShell.EditorServices.Services.PowerShell; using Microsoft.PowerShell.EditorServices.Services.PowerShell.Runspace; using Microsoft.PowerShell.EditorServices.Services.PowerShell.Utility; using Microsoft.PowerShell.EditorServices.Services.Symbols; using Microsoft.PowerShell.EditorServices.Services.TextDocument; using Microsoft.PowerShell.EditorServices.Utility; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; namespace Microsoft.PowerShell.EditorServices.Handlers { // TODO: Use ABCs. internal class PsesCompletionHandler : ICompletionHandler, ICompletionResolveHandler { const int DefaultWaitTimeoutMilliseconds = 5000; private readonly ILogger _logger; private readonly IRunspaceContext _runspaceContext; private readonly IInternalPowerShellExecutionService _executionService; private readonly WorkspaceService _workspaceService; private CompletionResults _mostRecentCompletions; private int _mostRecentRequestLine; private int _mostRecentRequestOffest; private string _mostRecentRequestFile; private CompletionCapability _capability; private readonly Guid _id = Guid.NewGuid(); Guid ICanBeIdentifiedHandler.Id => _id; public PsesCompletionHandler( ILoggerFactory factory, IRunspaceContext runspaceContext, IInternalPowerShellExecutionService executionService, WorkspaceService workspaceService) { _logger = factory.CreateLogger<PsesCompletionHandler>(); _runspaceContext = runspaceContext; _executionService = executionService; _workspaceService = workspaceService; } public CompletionRegistrationOptions GetRegistrationOptions(CompletionCapability capability, ClientCapabilities clientCapabilities) => new CompletionRegistrationOptions { DocumentSelector = LspUtils.PowerShellDocumentSelector, ResolveProvider = true, TriggerCharacters = new[] { ".", "-", ":", "\\", "$" } }; public async Task<CompletionList> Handle(CompletionParams request, CancellationToken cancellationToken) { int cursorLine = request.Position.Line + 1; int cursorColumn = request.Position.Character + 1; ScriptFile scriptFile = _workspaceService.GetFile(request.TextDocument.Uri); if (cancellationToken.IsCancellationRequested) { _logger.LogDebug("Completion request canceled for file: {0}", request.TextDocument.Uri); return Array.Empty<CompletionItem>(); } CompletionResults completionResults = await GetCompletionsInFileAsync( scriptFile, cursorLine, cursorColumn).ConfigureAwait(false); if (completionResults == null) { return Array.Empty<CompletionItem>(); } CompletionItem[] completionItems = new CompletionItem[completionResults.Completions.Length]; for (int i = 0; i < completionItems.Length; i++) { completionItems[i] = CreateCompletionItem(completionResults.Completions[i], completionResults.ReplacedRange, i + 1); } return completionItems; } public static bool CanResolve(CompletionItem value) { return value.Kind == CompletionItemKind.Function; } // Handler for "completionItem/resolve". In VSCode this is fired when a completion item is highlighted in the completion list. public async Task<CompletionItem> Handle(CompletionItem request, CancellationToken cancellationToken) { // We currently only support this request for anything that returns a CommandInfo: functions, cmdlets, aliases. if (request.Kind != CompletionItemKind.Function) { return request; } // No details means the module hasn't been imported yet and Intellisense shouldn't import the module to get this info. if (request.Detail is null) { return request; } // Get the documentation for the function CommandInfo commandInfo = await CommandHelpers.GetCommandInfoAsync( request.Label, _runspaceContext.CurrentRunspace, _executionService).ConfigureAwait(false); if (commandInfo != null) { request = request with { Documentation = await CommandHelpers.GetCommandSynopsisAsync(commandInfo, _executionService).ConfigureAwait(false) }; } // Send back the updated CompletionItem return request; } public void SetCapability(CompletionCapability capability, ClientCapabilities clientCapabilities) { _capability = capability; } /// <summary> /// Gets completions for a statement contained in the given /// script file at the specified line and column position. /// </summary> /// <param name="scriptFile"> /// The script file in which completions will be gathered. /// </param> /// <param name="lineNumber"> /// The 1-based line number at which completions will be gathered. /// </param> /// <param name="columnNumber"> /// The 1-based column number at which completions will be gathered. /// </param> /// <returns> /// A CommandCompletion instance completions for the identified statement. /// </returns> public async Task<CompletionResults> GetCompletionsInFileAsync( ScriptFile scriptFile, int lineNumber, int columnNumber) { Validate.IsNotNull(nameof(scriptFile), scriptFile); // Get the offset at the specified position. This method // will also validate the given position. int fileOffset = scriptFile.GetOffsetAtPosition( lineNumber, columnNumber); CommandCompletion commandCompletion = null; using (var cts = new CancellationTokenSource(DefaultWaitTimeoutMilliseconds)) { commandCompletion = await AstOperations.GetCompletionsAsync( scriptFile.ScriptAst, scriptFile.ScriptTokens, fileOffset, _executionService, _logger, cts.Token).ConfigureAwait(false); } if (commandCompletion == null) { return new CompletionResults(); } try { CompletionResults completionResults = CompletionResults.Create( scriptFile, commandCompletion); // save state of most recent completion _mostRecentCompletions = completionResults; _mostRecentRequestFile = scriptFile.Id; _mostRecentRequestLine = lineNumber; _mostRecentRequestOffest = columnNumber; return completionResults; } catch (ArgumentException e) { // Bad completion results could return an invalid // replacement range, catch that here _logger.LogError( $"Caught exception while trying to create CompletionResults:\n\n{e.ToString()}"); return new CompletionResults(); } } private static CompletionItem CreateCompletionItem( CompletionDetails completionDetails, BufferRange completionRange, int sortIndex) { string detailString = null; string documentationString = null; string completionText = completionDetails.CompletionText; InsertTextFormat insertTextFormat = InsertTextFormat.PlainText; switch (completionDetails.CompletionType) { case CompletionType.Type: case CompletionType.Namespace: case CompletionType.ParameterValue: case CompletionType.Method: case CompletionType.Property: detailString = completionDetails.ToolTipText; break; case CompletionType.Variable: case CompletionType.ParameterName: // Look for type encoded in the tooltip for parameters and variables. // Display PowerShell type names in [] to be consistent with PowerShell syntax // and how the debugger displays type names. var matches = Regex.Matches(completionDetails.ToolTipText, @"^(\[.+\])"); if ((matches.Count > 0) && (matches[0].Groups.Count > 1)) { detailString = matches[0].Groups[1].Value; } // The comparison operators (-eq, -not, -gt, etc) are unfortunately fall into ParameterName // but they don't have a type associated to them. This allows those tooltips to show up. else if (!string.IsNullOrEmpty(completionDetails.ToolTipText)) { detailString = completionDetails.ToolTipText; } break; case CompletionType.Command: // For Commands, let's extract the resolved command or the path for an exe // from the ToolTipText - if there is any ToolTipText. if (completionDetails.ToolTipText != null) { // Fix for #240 - notepad++.exe in tooltip text caused regex parser to throw. string escapedToolTipText = Regex.Escape(completionDetails.ToolTipText); // Don't display ToolTipText if it is the same as the ListItemText. // Reject command syntax ToolTipText - it's too much to display as a detailString. if (!completionDetails.ListItemText.Equals( completionDetails.ToolTipText, StringComparison.OrdinalIgnoreCase) && !Regex.IsMatch(completionDetails.ToolTipText, @"^\s*" + escapedToolTipText + @"\s+\[")) { detailString = completionDetails.ToolTipText; } } break; case CompletionType.Folder: // Insert a final "tab stop" as identified by $0 in the snippet provided for completion. // For folder paths, we take the path returned by PowerShell e.g. 'C:\Program Files' and insert // the tab stop marker before the closing quote char e.g. 'C:\Program Files$0'. // This causes the editing cursor to be placed *before* the final quote after completion, // which makes subsequent path completions work. See this part of the LSP spec for details: // https://microsoft.github.io/language-server-protocol/specification#textDocument_completion // Since we want to use a "tab stop" we need to escape a few things for Textmate to render properly. if (EndsWithQuote(completionText)) { var sb = new StringBuilder(completionDetails.CompletionText) .Replace(@"\", @"\\") .Replace(@"}", @"\}") .Replace(@"$", @"\$"); completionText = sb.Insert(sb.Length - 1, "$0").ToString(); insertTextFormat = InsertTextFormat.Snippet; } break; } // Force the client to maintain the sort order in which the // original completion results were returned. We just need to // make sure the default order also be the lexicographical order // which we do by prefixing the ListItemText with a leading 0's // four digit index. var sortText = $"{sortIndex:D4}{completionDetails.ListItemText}"; return new CompletionItem { InsertText = completionText, InsertTextFormat = insertTextFormat, Label = completionDetails.ListItemText, Kind = MapCompletionKind(completionDetails.CompletionType), Detail = detailString, Documentation = documentationString, SortText = sortText, FilterText = completionDetails.CompletionText, TextEdit = new TextEdit { NewText = completionText, Range = new Range { Start = new Position { Line = completionRange.Start.Line - 1, Character = completionRange.Start.Column - 1 }, End = new Position { Line = completionRange.End.Line - 1, Character = completionRange.End.Column - 1 } } } }; } private static CompletionItemKind MapCompletionKind(CompletionType completionType) { switch (completionType) { case CompletionType.Command: return CompletionItemKind.Function; case CompletionType.Property: return CompletionItemKind.Property; case CompletionType.Method: return CompletionItemKind.Method; case CompletionType.Variable: case CompletionType.ParameterName: return CompletionItemKind.Variable; case CompletionType.File: return CompletionItemKind.File; case CompletionType.Folder: return CompletionItemKind.Folder; default: return CompletionItemKind.Text; } } private static bool EndsWithQuote(string text) { if (string.IsNullOrEmpty(text)) { return false; } char lastChar = text[text.Length - 1]; return lastChar == '"' || lastChar == '\''; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using AuthorizationServer.Areas.HelpPage.ModelDescriptions; using AuthorizationServer.Areas.HelpPage.Models; namespace AuthorizationServer.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
//============================================================================= // System : Code Colorizer Library // File : CodeColorizer.cs // Author : Jonathan de Halleux, (c) 2003 // Updated : 11/21/2006 // Compiler: Microsoft Visual C# // // This is used to cache regular expressions to improve performance. The // original Code Project article by Jonathan can be found at: // http://www.codeproject.com/csharp/highlightcs.asp. // // Modifications by Eric Woodruff ([email protected]) 11/2006: // // Removed the RegexOptions.Compiled option as it doesn't appear to // improve performance all that much in average use. // // Modified to use a generic Dictionary<string, Regex> for the collection. // // Made the class internal and sealed as it serves no purpose outside of // the colorizer. // //============================================================================= using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Xml; namespace ColorizerLibrary { /// <summary> /// Dictionary associating string to Regex /// </summary> /// <remarks>This implementation uses a /// <see cref="Dictionary{TValue, KValue}" /> to store the Regex /// objects.</remarks> internal sealed class RegexDictionary { private Dictionary<string, Regex> dictionary; /// <summary> /// Default constructor. /// </summary> internal RegexDictionary() { dictionary = new Dictionary<string, Regex>(); } #region Private Methods /// <summary> /// This returns the key name based on the IDs of the two specified /// nodes. /// </summary> /// <param name="node1">The first node</param> /// <param name="node2">The second node</param> /// <overloads>There are two overloads for this method</overloads> private static string KeyName(XmlNode node1, XmlNode node2) { XmlNode attr1, attr2; if(node1 == null) throw new ArgumentNullException("node1"); if(node2 == null) throw new ArgumentNullException("node2"); attr1 = node1.Attributes["id"]; attr2 = node2.Attributes["id"]; if(attr1 == null) throw new ArgumentException("node1 has no 'id' attribute"); if(attr2 == null) throw new ArgumentException("node2 has no 'id' attribute"); return attr1.Value + "." + attr2.Value; } /// <summary> /// This returns the key name based on the IDs of the three specified /// nodes. /// </summary> /// <param name="node1">The first node</param> /// <param name="node2">The second node</param> /// <param name="node3">The third node</param> private static string KeyName(XmlNode node1, XmlNode node2, XmlNode node3) { XmlNode attr1, attr2, attr3; if(node1 == null) throw new ArgumentNullException("node1"); if(node2 == null) throw new ArgumentNullException("node2"); if(node3 == null) throw new ArgumentNullException("node3"); attr1 = node1.Attributes["id"]; attr2 = node2.Attributes["id"]; attr3 = node3.Attributes["id"]; if(attr1 == null) throw new ArgumentException("node1 has no 'id' attribute"); if(attr2 == null) throw new ArgumentException("node2 has no 'id' attribute"); if(attr3 == null) throw new ArgumentException("node3 has no 'id' attribute"); return attr1.Value + "." + attr2.Value + "." + attr3.Value; } /// <summary> /// Retrieve the regular expression options from the language node /// </summary> /// <param name="languageNode">langue name</param> /// <returns>RegexOptions enumeration combination</returns> private static RegexOptions GetRegexOptions(XmlNode languageNode) { RegexOptions regOp = RegexOptions.Multiline; // Check if case sensitive... XmlNode caseNode = languageNode.Attributes["not-case-sensitive"]; if(caseNode != null && caseNode.Value == "yes") regOp |= RegexOptions.IgnoreCase; return regOp; } #endregion #region Key add and retrieve methods /// <summary> /// Add a regex depending on two nodes /// </summary> /// <param name="languageNode">The language node</param> /// <param name="subNode">The sub-node</param> /// <param name="sRegExp">The regular expression string</param> /// <exception cref="ArgumentNullException">This is thrown if a node /// parameter is null or the regular expression is null.</exception> /// <exception cref="ArgumentException">This is thrown if a node /// parameter does not have an 'id' attribute or if the regular /// expression could not be created.</exception> /// <overloads>There are two overloads for this method</overloads> internal void AddKey(XmlNode languageNode, XmlNode subNode, string sRegExp) { Regex regExp = new Regex(sRegExp, RegexDictionary.GetRegexOptions(languageNode)); if(regExp == null) throw new ArgumentException( "Could not create regular expression"); dictionary.Add(RegexDictionary.KeyName(languageNode, subNode), regExp); } /// <summary> /// Add a regex depending on three nodes /// </summary> /// <param name="languageNode">The language node</param> /// <param name="subNode">The first sub-node</param> /// <param name="subNode2">The second sub-node</param> /// <param name="sRegExp">The regular expression string</param> /// <exception cref="ArgumentNullException">This is thrown if a node /// parameter is null or the regular expression is null.</exception> /// <exception cref="ArgumentException">This is thrown if a node /// parameter does not have an 'id' attribute or if the regular /// expression could not be created.</exception> internal void AddKey(XmlNode languageNode, XmlNode subNode, XmlNode subNode2, string sRegExp) { Regex regExp = new Regex(sRegExp, RegexDictionary.GetRegexOptions(languageNode)); if(regExp == null) throw new ArgumentException( "Could not create regular expression"); dictionary.Add(RegexDictionary.KeyName(languageNode, subNode, subNode2), regExp); } /// <summary> /// Retrieves the regular expression out of 2 nodes /// </summary> /// <param name="languageNode">The language node</param> /// <param name="subNode">The sub-node</param> /// <returns>The regular expression</returns> /// <exception cref="ArgumentNullException">This is thrown if a node /// parameter is null or the regular expression is null.</exception> /// <exception cref="ArgumentException">This is thrown if a node /// parameter does not have an 'id' attribute.</exception> internal Regex GetKey(XmlNode languageNode, XmlNode subNode) { return dictionary[RegexDictionary.KeyName(languageNode, subNode)]; } /// <summary> /// Retrieves the regular expression out of 3 nodes /// </summary> /// <param name="languageNode">The language node</param> /// <param name="subNode">The first sub-node</param> /// <param name="subNode2">The second sub-node</param> /// <returns>The regular expression</returns> /// <exception cref="ArgumentNullException">This is thrown if a node /// parameter is null or the regular expression is null.</exception> /// <exception cref="ArgumentException">This is thrown if a node /// parameter does not have an 'id' attribute.</exception> internal Regex GetKey(XmlNode languageNode, XmlNode subNode, XmlNode subNode2) { return dictionary[RegexDictionary.KeyName(languageNode, subNode, subNode2)]; } #endregion } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at [email protected] // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Globalization; using System.Reflection; using Subtext.Framework.Properties; namespace UnitTests.Subtext { /// <summary> /// Helper class to simplify common reflection tasks. /// </summary> public sealed class ReflectionHelper { private ReflectionHelper() { } /// <summary> /// Returns the value of the private member specified. /// </summary> /// <param name="fieldName">Name of the member.</param> /// /// <param name="type">Type of the member.</param> public static T GetStaticFieldValue<T>(string fieldName, Type type) { FieldInfo field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Static); if(field != null) { return (T)field.GetValue(type); } return default(T); } /// <summary> /// Returns the value of the private member specified. /// </summary> /// <param name="propertyName">Name of the member.</param> /// /// <param name="type">Type of the member.</param> public static T GetStaticPropertyValue<T>(string propertyName, Type type) { PropertyInfo property = type.GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Static); if(property != null) { return (T)property.GetValue(type, null); } return default(T); } /// <summary> /// Returns the value of the private member specified. /// </summary> /// <param name="fieldName">Name of the member.</param> /// <param name="typeName"></param> public static T GetStaticFieldValue<T>(string fieldName, string typeName) { Type type = Type.GetType(typeName, true); FieldInfo field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Static); if(field != null) { return (T)field.GetValue(type); } return default(T); } /// <summary> /// Sets the value of the private static member. /// </summary> /// <param name="fieldName"></param> /// <param name="type"></param> /// <param name="value"></param> public static void SetStaticFieldValue<T>(string fieldName, Type type, T value) { FieldInfo field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Static); if(field == null) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.ReflectionArgument_CouldNotFindsStaticField, fieldName)); } field.SetValue(null, value); } /// <summary> /// Sets the value of the private static member. /// </summary> /// <param name="fieldName"></param> /// <param name="typeName"></param> /// <param name="value"></param> public static void SetStaticFieldValue<T>(string fieldName, string typeName, T value) { Type type = Type.GetType(typeName, true); FieldInfo field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Static); if(field == null) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.ReflectionArgument_CouldNotFindsStaticField, fieldName)); } field.SetValue(null, value); } /// <summary> /// Returns the value of the private member specified. /// </summary> /// <param name="fieldName">Name of the member.</param> /// <param name="source">The object that contains the member.</param> public static T GetPrivateInstanceFieldValue<T>(string fieldName, object source) { FieldInfo field = source.GetType().GetField(fieldName, BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance); if(field != null) { return (T)field.GetValue(source); } return default(T); } /// <summary> /// Returns the value of the private member specified. /// </summary> /// <param name="memberName">Name of the member.</param> /// <param name="source">The object that contains the member.</param> /// <param name="value">The value to set the member to.</param> public static void SetPrivateInstanceFieldValue(string memberName, object source, object value) { FieldInfo field = source.GetType().GetField(memberName, BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance); if(field == null) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.ReflectionArgument_CouldNotFindInstanceField, memberName)); } field.SetValue(source, value); } public static object Instantiate(string typeName) { return Instantiate(typeName, null, null); } public static object Instantiate(string typeName, Type[] constructorArgumentTypes, params object[] constructorParameterValues) { return Instantiate(Type.GetType(typeName, true), constructorArgumentTypes, constructorParameterValues); } public static object Instantiate(Type type, Type[] constructorArgumentTypes, params object[] constructorParameterValues) { ConstructorInfo constructor = type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, constructorArgumentTypes, null); return constructor.Invoke(constructorParameterValues); } /// <summary> /// Invokes a non-public static method. /// </summary> /// <typeparam name="TReturn"></typeparam> /// <param name="type"></param> /// <param name="methodName"></param> /// <param name="parameters"></param> /// <returns></returns> public static TReturn InvokeNonPublicMethod<TReturn>(Type type, string methodName, params object[] parameters) { Type[] paramTypes = Array.ConvertAll(parameters, o => o.GetType()); MethodInfo method = type.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static, null, paramTypes, null); if(method == null) { throw new ArgumentException( string.Format(CultureInfo.InvariantCulture, Resources.ReflectionArgument_CouldNotFindMethod, methodName), "method"); } return (TReturn)method.Invoke(null, parameters); } public static void InvokeNonPublicMethod(object source, string methodName, params object[] parameters) { Type[] paramTypes = Array.ConvertAll(parameters, o => o.GetType()); MethodInfo method = source.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, paramTypes, null); if(method == null) { throw new ArgumentException( string.Format(CultureInfo.InvariantCulture, Resources.ReflectionArgument_CouldNotFindMethod, methodName), "method"); } method.Invoke(source, parameters); } public static TReturn InvokeNonPublicMethod<TReturn>(object source, string methodName, params object[] parameters) { Type[] paramTypes = Array.ConvertAll(parameters, o => o.GetType()); MethodInfo method = source.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, paramTypes, null); if(method == null) { throw new ArgumentException( string.Format(CultureInfo.InvariantCulture, Resources.ReflectionArgument_CouldNotFindMethod, methodName), "method"); } return (TReturn)method.Invoke(source, parameters); } public static TReturn InvokeProperty<TReturn>(object source, string propertyName) { PropertyInfo propertyInfo = source.GetType().GetProperty(propertyName); if(propertyInfo == null) { throw new ArgumentException( string.Format(CultureInfo.InvariantCulture, Resources.ReflectionArgument_CouldNotFindProperty, propertyName), "propertyName"); } return (TReturn)propertyInfo.GetValue(source, null); } public static TReturn InvokeNonPublicProperty<TReturn>(object source, string propertyName) { PropertyInfo propertyInfo = source.GetType().GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance, null, typeof(TReturn), new Type[0], null); if(propertyInfo == null) { throw new ArgumentException( string.Format(CultureInfo.InvariantCulture, Resources.ReflectionArgument_CouldNotFindProperty, propertyName), "propertyName"); } return (TReturn)propertyInfo.GetValue(source, null); } public static object InvokeNonPublicProperty(object source, string propertyName) { PropertyInfo propertyInfo = source.GetType().GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance); if(propertyInfo == null) { throw new ArgumentException( string.Format(CultureInfo.InvariantCulture, Resources.ReflectionArgument_CouldNotFindProperty, propertyName), "propertyName"); } return propertyInfo.GetValue(source, null); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Beatmaps; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Drawables; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; using osu.Framework.Audio; using osu.Framework.Audio.Sample; using osu.Framework.Audio.Track; using osu.Framework.Bindables; using osu.Framework.Graphics.Cursor; using osu.Framework.Graphics.Textures; using osu.Framework.Input; using osu.Framework.Input.Events; using osu.Framework.IO.Stores; using osu.Game.Configuration; using osu.Game.Graphics.Cursor; using osu.Game.Input.Handlers; using osu.Game.Overlays; using osu.Game.Replays; using osu.Game.Rulesets.Configuration; using osu.Game.Rulesets.Scoring; using osu.Game.Scoring; using osu.Game.Screens.Play; using osuTK; namespace osu.Game.Rulesets.UI { /// <summary> /// Displays an interactive ruleset gameplay instance. /// </summary> /// <typeparam name="TObject">The type of HitObject contained by this DrawableRuleset.</typeparam> public abstract class DrawableRuleset<TObject> : DrawableRuleset, IProvideCursor, ICanAttachKeyCounter where TObject : HitObject { public override event Action<JudgementResult> OnNewResult; public override event Action<JudgementResult> OnRevertResult; /// <summary> /// The selected variant. /// </summary> public virtual int Variant => 0; /// <summary> /// The key conversion input manager for this DrawableRuleset. /// </summary> public PassThroughInputManager KeyBindingInputManager; public override double GameplayStartTime => Objects.First().StartTime - 2000; private readonly Lazy<Playfield> playfield; private TextureStore textureStore; private ISampleStore localSampleStore; /// <summary> /// The playfield. /// </summary> public override Playfield Playfield => playfield.Value; private Container overlays; public override Container Overlays => overlays; public override GameplayClock FrameStableClock => frameStabilityContainer.GameplayClock; private bool frameStablePlayback = true; /// <summary> /// Whether to enable frame-stable playback. /// </summary> internal bool FrameStablePlayback { get => frameStablePlayback; set { frameStablePlayback = false; if (frameStabilityContainer != null) frameStabilityContainer.FrameStablePlayback = value; } } /// <summary> /// The beatmap. /// </summary> public readonly Beatmap<TObject> Beatmap; public override IEnumerable<HitObject> Objects => Beatmap.HitObjects; protected IRulesetConfigManager Config { get; private set; } /// <summary> /// The mods which are to be applied. /// </summary> [Cached(typeof(IReadOnlyList<Mod>))] private readonly IReadOnlyList<Mod> mods; private FrameStabilityContainer frameStabilityContainer; private OnScreenDisplay onScreenDisplay; /// <summary> /// Creates a ruleset visualisation for the provided ruleset and beatmap. /// </summary> /// <param name="ruleset">The ruleset being represented.</param> /// <param name="beatmap">The beatmap to create the hit renderer for.</param> /// <param name="mods">The <see cref="Mod"/>s to apply.</param> protected DrawableRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods = null) : base(ruleset) { if (beatmap == null) throw new ArgumentNullException(nameof(beatmap), "Beatmap cannot be null."); if (!(beatmap is Beatmap<TObject> tBeatmap)) throw new ArgumentException($"{GetType()} expected the beatmap to contain hitobjects of type {typeof(TObject)}.", nameof(beatmap)); Beatmap = tBeatmap; this.mods = mods?.ToArray() ?? Array.Empty<Mod>(); RelativeSizeAxes = Axes.Both; KeyBindingInputManager = CreateInputManager(); playfield = new Lazy<Playfield>(CreatePlayfield); IsPaused.ValueChanged += paused => { if (HasReplayLoaded.Value) return; KeyBindingInputManager.UseParentInput = !paused.NewValue; }; } protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) { var dependencies = new DependencyContainer(base.CreateChildDependencies(parent)); var resources = Ruleset.CreateResourceStore(); if (resources != null) { textureStore = new TextureStore(new TextureLoaderStore(new NamespacedResourceStore<byte[]>(resources, "Textures"))); textureStore.AddStore(dependencies.Get<TextureStore>()); dependencies.Cache(textureStore); localSampleStore = dependencies.Get<AudioManager>().GetSampleStore(new NamespacedResourceStore<byte[]>(resources, "Samples")); dependencies.CacheAs<ISampleStore>(new FallbackSampleStore(localSampleStore, dependencies.Get<ISampleStore>())); } onScreenDisplay = dependencies.Get<OnScreenDisplay>(); Config = dependencies.Get<RulesetConfigCache>().GetConfigFor(Ruleset); if (Config != null) { dependencies.Cache(Config); onScreenDisplay?.BeginTracking(this, Config); } return dependencies; } public virtual PlayfieldAdjustmentContainer CreatePlayfieldAdjustmentContainer() => new PlayfieldAdjustmentContainer(); [BackgroundDependencyLoader] private void load(OsuConfigManager config, CancellationToken? cancellationToken) { InternalChildren = new Drawable[] { frameStabilityContainer = new FrameStabilityContainer(GameplayStartTime) { FrameStablePlayback = FrameStablePlayback, Children = new Drawable[] { KeyBindingInputManager .WithChild(CreatePlayfieldAdjustmentContainer() .WithChild(Playfield) ), overlays = new Container { RelativeSizeAxes = Axes.Both } } }, }; if ((ResumeOverlay = CreateResumeOverlay()) != null) { AddInternal(CreateInputManager() .WithChild(CreatePlayfieldAdjustmentContainer() .WithChild(ResumeOverlay))); } applyRulesetMods(mods, config); loadObjects(cancellationToken); } /// <summary> /// Creates and adds drawable representations of hit objects to the play field. /// </summary> private void loadObjects(CancellationToken? cancellationToken) { foreach (TObject h in Beatmap.HitObjects) { cancellationToken?.ThrowIfCancellationRequested(); addHitObject(h); } cancellationToken?.ThrowIfCancellationRequested(); Playfield.PostProcess(); foreach (var mod in mods.OfType<IApplicableToDrawableHitObjects>()) mod.ApplyToDrawableHitObjects(Playfield.AllHitObjects); } public override void RequestResume(Action continueResume) { if (ResumeOverlay != null && (Cursor == null || (Cursor.LastFrameState == Visibility.Visible && Contains(Cursor.ActiveCursor.ScreenSpaceDrawQuad.Centre)))) { ResumeOverlay.GameplayCursor = Cursor; ResumeOverlay.ResumeAction = continueResume; ResumeOverlay.Show(); } else continueResume(); } public override void CancelResume() { // called if the user pauses while the resume overlay is open ResumeOverlay?.Hide(); } /// <summary> /// Creates and adds the visual representation of a <typeparamref name="TObject"/> to this <see cref="DrawableRuleset{TObject}"/>. /// </summary> /// <param name="hitObject">The <typeparamref name="TObject"/> to add the visual representation for.</param> private void addHitObject(TObject hitObject) { var drawableObject = CreateDrawableRepresentation(hitObject); if (drawableObject == null) return; drawableObject.OnNewResult += (_, r) => OnNewResult?.Invoke(r); drawableObject.OnRevertResult += (_, r) => OnRevertResult?.Invoke(r); Playfield.Add(drawableObject); } public override void SetReplayScore(Score replayScore) { if (!(KeyBindingInputManager is IHasReplayHandler replayInputManager)) throw new InvalidOperationException($"A {nameof(KeyBindingInputManager)} which supports replay loading is not available"); var handler = (ReplayScore = replayScore) != null ? CreateReplayInputHandler(replayScore.Replay) : null; replayInputManager.ReplayInputHandler = handler; frameStabilityContainer.ReplayInputHandler = handler; HasReplayLoaded.Value = replayInputManager.ReplayInputHandler != null; if (replayInputManager.ReplayInputHandler != null) replayInputManager.ReplayInputHandler.GamefieldToScreenSpace = Playfield.GamefieldToScreenSpace; if (!ProvidingUserCursor) { // The cursor is hidden by default (see Playfield.load()), but should be shown when there's a replay Playfield.Cursor?.Show(); } } /// <summary> /// Creates a DrawableHitObject from a HitObject. /// </summary> /// <param name="h">The HitObject to make drawable.</param> /// <returns>The DrawableHitObject.</returns> public abstract DrawableHitObject<TObject> CreateDrawableRepresentation(TObject h); public void Attach(KeyCounterDisplay keyCounter) => (KeyBindingInputManager as ICanAttachKeyCounter)?.Attach(keyCounter); /// <summary> /// Creates a key conversion input manager. An exception will be thrown if a valid <see cref="RulesetInputManager{T}"/> is not returned. /// </summary> /// <returns>The input manager.</returns> protected abstract PassThroughInputManager CreateInputManager(); protected virtual ReplayInputHandler CreateReplayInputHandler(Replay replay) => null; /// <summary> /// Creates a Playfield. /// </summary> /// <returns>The Playfield.</returns> protected abstract Playfield CreatePlayfield(); /// <summary> /// Applies the active mods to this DrawableRuleset. /// </summary> /// <param name="mods">The <see cref="Mod"/>s to apply.</param> /// <param name="config">The <see cref="OsuConfigManager"/> to apply.</param> private void applyRulesetMods(IReadOnlyList<Mod> mods, OsuConfigManager config) { if (mods == null) return; foreach (var mod in mods.OfType<IApplicableToDrawableRuleset<TObject>>()) mod.ApplyToDrawableRuleset(this); foreach (var mod in mods.OfType<IReadFromConfig>()) mod.ReadFromConfig(config); } #region IProvideCursor protected override bool OnHover(HoverEvent e) => true; // required for IProvideCursor // only show the cursor when within the playfield, by default. public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => Playfield.ReceivePositionalInputAt(screenSpacePos); CursorContainer IProvideCursor.Cursor => Playfield.Cursor; public override GameplayCursorContainer Cursor => Playfield.Cursor; public bool ProvidingUserCursor => Playfield.Cursor != null && !HasReplayLoaded.Value; #endregion protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); localSampleStore?.Dispose(); if (Config != null) { onScreenDisplay?.StopTracking(this, Config); Config = null; } } } /// <summary> /// Displays an interactive ruleset gameplay instance. /// <remarks> /// This type is required only for adding non-generic type to the draw hierarchy. /// Once IDrawable is a thing, this can also become an interface. /// </remarks> /// </summary> public abstract class DrawableRuleset : CompositeDrawable { /// <summary> /// Invoked when a <see cref="JudgementResult"/> has been applied by a <see cref="DrawableHitObject"/>. /// </summary> public abstract event Action<JudgementResult> OnNewResult; /// <summary> /// Invoked when a <see cref="JudgementResult"/> is being reverted by a <see cref="DrawableHitObject"/>. /// </summary> public abstract event Action<JudgementResult> OnRevertResult; /// <summary> /// Whether a replay is currently loaded. /// </summary> public readonly BindableBool HasReplayLoaded = new BindableBool(); /// <summary> /// Whether the game is paused. Used to block user input. /// </summary> public readonly BindableBool IsPaused = new BindableBool(); /// <summary> /// The playfield. /// </summary> public abstract Playfield Playfield { get; } /// <summary> /// Place to put drawables above hit objects but below UI. /// </summary> public abstract Container Overlays { get; } /// <summary> /// The frame-stable clock which is being used for playfield display. /// </summary> public abstract GameplayClock FrameStableClock { get; } /// <summary>~ /// The associated ruleset. /// </summary> public readonly Ruleset Ruleset; /// <summary> /// Creates a ruleset visualisation for the provided ruleset. /// </summary> /// <param name="ruleset">The ruleset.</param> internal DrawableRuleset(Ruleset ruleset) { Ruleset = ruleset; } /// <summary> /// All the converted hit objects contained by this hit renderer. /// </summary> public abstract IEnumerable<HitObject> Objects { get; } /// <summary> /// The point in time at which gameplay starts, including any required lead-in for display purposes. /// Defaults to two seconds before the first <see cref="HitObject"/>. Override as necessary. /// </summary> public abstract double GameplayStartTime { get; } /// <summary> /// The currently loaded replay. Usually null in the case of a local player. /// </summary> public Score ReplayScore { get; protected set; } /// <summary> /// The cursor being displayed by the <see cref="Playfield"/>. May be null if no cursor is provided. /// </summary> public abstract GameplayCursorContainer Cursor { get; } /// <summary> /// An optional overlay used when resuming gameplay from a paused state. /// </summary> public ResumeOverlay ResumeOverlay { get; protected set; } /// <summary> /// Returns first available <see cref="HitWindows"/> provided by a <see cref="HitObject"/>. /// </summary> [CanBeNull] public HitWindows FirstAvailableHitWindows { get { foreach (var h in Objects) { if (h.HitWindows.WindowFor(HitResult.Miss) > 0) return h.HitWindows; foreach (var n in h.NestedHitObjects) { if (h.HitWindows.WindowFor(HitResult.Miss) > 0) return n.HitWindows; } } return null; } } protected virtual ResumeOverlay CreateResumeOverlay() => null; /// <summary> /// Sets a replay to be used, overriding local input. /// </summary> /// <param name="replayScore">The replay, null for local input.</param> public abstract void SetReplayScore(Score replayScore); /// <summary> /// Invoked when the interactive user requests resuming from a paused state. /// Allows potentially delaying the resume process until an interaction is performed. /// </summary> /// <param name="continueResume">The action to run when resuming is to be completed.</param> public abstract void RequestResume(Action continueResume); /// <summary> /// Invoked when the user requests to pause while the resume overlay is active. /// </summary> public abstract void CancelResume(); } public class BeatmapInvalidForRulesetException : ArgumentException { public BeatmapInvalidForRulesetException(string text) : base(text) { } } /// <summary> /// A sample store which adds a fallback source. /// </summary> /// <remarks> /// This is a temporary implementation to workaround ISampleStore limitations. /// </remarks> public class FallbackSampleStore : ISampleStore { private readonly ISampleStore primary; private readonly ISampleStore secondary; public FallbackSampleStore(ISampleStore primary, ISampleStore secondary) { this.primary = primary; this.secondary = secondary; } public SampleChannel Get(string name) => primary.Get(name) ?? secondary.Get(name); public Task<SampleChannel> GetAsync(string name) => primary.GetAsync(name) ?? secondary.GetAsync(name); public Stream GetStream(string name) => primary.GetStream(name) ?? secondary.GetStream(name); public IEnumerable<string> GetAvailableResources() => throw new NotSupportedException(); public void AddAdjustment(AdjustableProperty type, BindableNumber<double> adjustBindable) => throw new NotSupportedException(); public void RemoveAdjustment(AdjustableProperty type, BindableNumber<double> adjustBindable) => throw new NotSupportedException(); public BindableNumber<double> Volume => throw new NotSupportedException(); public BindableNumber<double> Balance => throw new NotSupportedException(); public BindableNumber<double> Frequency => throw new NotSupportedException(); public BindableNumber<double> Tempo => throw new NotSupportedException(); public IBindable<double> GetAggregate(AdjustableProperty type) => throw new NotSupportedException(); public IBindable<double> AggregateVolume => throw new NotSupportedException(); public IBindable<double> AggregateBalance => throw new NotSupportedException(); public IBindable<double> AggregateFrequency => throw new NotSupportedException(); public IBindable<double> AggregateTempo => throw new NotSupportedException(); public int PlaybackConcurrency { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } public void Dispose() { } } }
// Command-line argument examples: // <exe_name> // - Displays Visual Basic, C#, and JScript compiler settings. // <exe_name> Language CSharp // - Displays the compiler settings for C#. // <exe_name> All // - Displays settings for all configured compilers. // <exe_name> Config Pascal // - Displays settings for configured Pascal language provider, // if one exists. // <exe_name> Extension .vb // - Displays settings for the compiler associated with the .vb // file extension. using System; using System.Globalization; using System.CodeDom; using System.CodeDom.Compiler; using Microsoft.CSharp; using Microsoft.VisualBasic; namespace CodeDomCompilerInfoSample { class CompilerInfoSample { [STAThread] static void Main(string[] args) { String queryCommand = ""; String queryArg = ""; int iNumArguments = args.Length; // Get input command-line arguments. if (iNumArguments > 0) { queryCommand = args[0].ToUpper(CultureInfo.InvariantCulture); if (iNumArguments > 1) { queryArg = args[1]; } } // Determine which method to call. Console.WriteLine(); switch(queryCommand) { case ("LANGUAGE"): // Display compiler information for input language. DisplayCompilerInfoForLanguage(queryArg); break; case ("EXTENSION"): // Display compiler information for input file extension. DisplayCompilerInfoUsingExtension(queryArg); break; case ("CONFIG"): // Display settings for the configured language provider. DisplayCompilerInfoForConfigLanguage(queryArg); break; case ("ALL"): // Display compiler information for all configured // language providers. DisplayAllCompilerInfo(); break; default: // There was no command-line argument, or the // command-line argument was not recognized. // Display the C#, Visual Basic and JScript // compiler information. DisplayCSharpCompilerInfo(); DisplayVBCompilerInfo(); DisplayJScriptCompilerInfo(); break; } } static void DisplayCSharpCompilerInfo() { // Get the provider for Microsoft.CSharp CodeDomProvider provider = new CSharpCodeProvider(); // Display the C# language provider information. Console.WriteLine("CSharp provider is {0}", provider.ToString()); Console.WriteLine(" Provider hash code: {0}", provider.GetHashCode().ToString()); Console.WriteLine(" Default file extension: {0}", provider.FileExtension); Console.WriteLine(); } static void DisplayVBCompilerInfo() { // Get the provider for Microsoft.VisualBasic CodeDomProvider provider = new VBCodeProvider(); // Display the Visual Basic language provider information. Console.WriteLine("Visual Basic provider is {0}", provider.ToString()); Console.WriteLine(" Provider hash code: {0}", provider.GetHashCode().ToString()); Console.WriteLine(" Default file extension: {0}", provider.FileExtension); Console.WriteLine(); } static void DisplayJScriptCompilerInfo() { // Get the provider for JScript. CodeDomProvider provider; try { provider = CodeDomProvider.CreateProvider("js"); // Display the JScript language provider information. Console.WriteLine("JScript language provider is {0}", provider.ToString()); Console.WriteLine(" Provider hash code: {0}", provider.GetHashCode().ToString()); Console.WriteLine(" Default file extension: {0}", provider.FileExtension); Console.WriteLine(); } catch (System.Configuration.ConfigurationException) { // The JScript language provider was not found. Console.WriteLine("There is no configured JScript language provider."); } } static void DisplayCompilerInfoUsingExtension(string fileExtension) { if (fileExtension[0] != '.') { fileExtension = "." + fileExtension; } // Get the language associated with the file extension. if (CodeDomProvider.IsDefinedExtension(fileExtension)) { CodeDomProvider provider; String language = CodeDomProvider.GetLanguageFromExtension(fileExtension); Console.WriteLine("The language \"{0}\" is associated with file extension \"{1}\"", language, fileExtension); Console.WriteLine(); // Next, check for a corresponding language provider. if (CodeDomProvider.IsDefinedLanguage(language)) { provider = CodeDomProvider.CreateProvider(language); // Display information about this language provider. Console.WriteLine("Language provider: {0}", provider.ToString()); Console.WriteLine(); // Get the compiler settings for this language. CompilerInfo langCompilerInfo = CodeDomProvider.GetCompilerInfo(language); CompilerParameters langCompilerConfig = langCompilerInfo.CreateDefaultCompilerParameters(); Console.WriteLine(" Compiler options: {0}", langCompilerConfig.CompilerOptions); Console.WriteLine(" Compiler warning level: {0}", langCompilerConfig.WarningLevel); } } else { // Tell the user that the language provider was not found. Console.WriteLine("There is no language provider associated with input file extension \"{0}\".", fileExtension); } } static void DisplayCompilerInfoForLanguage(string language) { CodeDomProvider provider; // Check for a provider corresponding to the input language. if (CodeDomProvider.IsDefinedLanguage(language)) { provider = CodeDomProvider.CreateProvider(language); // Display information about this language provider. Console.WriteLine("Language provider: {0}", provider.ToString()); Console.WriteLine(); Console.WriteLine(" Default file extension: {0}", provider.FileExtension); Console.WriteLine(); // Get the compiler settings for this language. CompilerInfo langCompilerInfo = CodeDomProvider.GetCompilerInfo(language); CompilerParameters langCompilerConfig = langCompilerInfo.CreateDefaultCompilerParameters(); Console.WriteLine(" Compiler options: {0}", langCompilerConfig.CompilerOptions); Console.WriteLine(" Compiler warning level: {0}", langCompilerConfig.WarningLevel); } else { // Tell the user that the language provider was not found. Console.WriteLine("There is no provider configured for input language \"{0}\".", language); } } static void DisplayCompilerInfoForConfigLanguage(string configLanguage) { CompilerInfo info = CodeDomProvider.GetCompilerInfo(configLanguage); // Check whether there is a provider configured for this language. if (info.IsCodeDomProviderTypeValid) { // Get a provider instance using the configured type information. CodeDomProvider provider; provider = (CodeDomProvider)Activator.CreateInstance(info.CodeDomProviderType); // Display information about this language provider. Console.WriteLine("Language provider: {0}", provider.ToString()); Console.WriteLine(); Console.WriteLine(" Default file extension: {0}", provider.FileExtension); Console.WriteLine(); // Get the compiler settings for this language. CompilerParameters langCompilerConfig = info.CreateDefaultCompilerParameters(); Console.WriteLine(" Compiler options: {0}", langCompilerConfig.CompilerOptions); Console.WriteLine(" Compiler warning level: {0}", langCompilerConfig.WarningLevel); } else { // Tell the user that the language provider was not found. Console.WriteLine("There is no provider configured for input language \"{0}\".", configLanguage); } } static void DisplayAllCompilerInfo() { CompilerInfo [] allCompilerInfo = CodeDomProvider.GetAllCompilerInfo(); foreach (CompilerInfo info in allCompilerInfo) { String defaultLanguage; String defaultExtension; CodeDomProvider provider = info.CreateProvider(); // Display information about this configured provider. Console.WriteLine("Language provider: {0}", provider.ToString()); Console.WriteLine(); Console.WriteLine(" Supported file extension(s):"); foreach(String extension in info.GetExtensions()) { Console.WriteLine(" {0}", extension); } defaultExtension = provider.FileExtension; if (defaultExtension[0] != '.') { defaultExtension = "." + defaultExtension; } Console.WriteLine(" Default file extension: {0}", defaultExtension); Console.WriteLine(); Console.WriteLine(" Supported language(s):"); foreach(String language in info.GetLanguages()) { Console.WriteLine(" {0}", language); } defaultLanguage = CodeDomProvider.GetLanguageFromExtension(defaultExtension); Console.WriteLine(" Default language: {0}", defaultLanguage); Console.WriteLine(); // Get the compiler settings for this provider. CompilerParameters langCompilerConfig = info.CreateDefaultCompilerParameters(); Console.WriteLine(" Compiler options: {0}", langCompilerConfig.CompilerOptions); Console.WriteLine(" Compiler warning level: {0}", langCompilerConfig.WarningLevel); Console.WriteLine(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.IO; using System.Xml.Schema; using Xunit; using Xunit.Abstractions; namespace System.Xml.Tests { // ===================== ValidateAttribute ===================== public class TCValidateAttribute : CXmlSchemaValidatorTestCase { private ITestOutputHelper _output; private ExceptionVerifier _exVerifier; public TCValidateAttribute(ITestOutputHelper output) : base(output) { _output = output; _exVerifier = new ExceptionVerifier("System.Xml", _output); } [Theory] [InlineData(null, "")] [InlineData("attr", null)] public void PassNull_LocalName_NameSpace__Invalid(string localName, string nameSpace) { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement("OneAttributeElement", "", null); try { val.ValidateAttribute(localName, nameSpace, StringGetter("foo"), info); } catch (ArgumentNullException) { return; } Assert.True(false); } [Fact] public void PassNullValueGetter__Invalid() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement("OneAttributeElement", "", null); try { val.ValidateAttribute("attr", "", (XmlValueGetter)null, info); } catch (ArgumentNullException) { return; } Assert.True(false); } [Fact] public void PassNullXmlSchemaInfo__Valid() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement("OneAttributeElement", "", null); val.ValidateAttribute("attr", "", StringGetter("foo"), null); return; } [Theory] [InlineData("RequiredAttribute")] [InlineData("OptionalAttribute")] [InlineData("DefaultAttribute")] [InlineData("FixedAttribute")] [InlineData("FixedRequiredAttribute")] public void Validate_Required_Optional_Default_Fixed_FixedRequired_Attribute(string attrType) { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement(attrType + "Element", "", null); val.ValidateAttribute(attrType, "", StringGetter("foo"), info); Assert.Equal(info.SchemaAttribute.QualifiedName, new XmlQualifiedName(attrType)); Assert.Equal(XmlSchemaValidity.Valid, info.Validity); Assert.Equal(XmlTypeCode.String, info.SchemaType.TypeCode); return; } [Fact] public void ValidateAttributeWithNamespace() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement("NamespaceAttributeElement", "", null); val.ValidateAttribute("attr1", "uri:tempuri", StringGetter("123"), info); Assert.Equal(info.SchemaAttribute.QualifiedName, new XmlQualifiedName("attr1", "uri:tempuri")); Assert.Equal(XmlSchemaValidity.Valid, info.Validity); Assert.Equal(XmlTypeCode.Int, info.SchemaType.TypeCode); return; } [Fact] public void ValidateAnyAttribute() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement("AnyAttributeElement", "", null); val.ValidateAttribute("SomeAttribute", "", StringGetter("foo"), info); Assert.Equal(XmlSchemaValidity.NotKnown, info.Validity); return; } [Fact] public void AskForDefaultAttributesAndValidateThem() { XmlSchemaValidator val = CreateValidator(XSDFILE_200_DEF_ATTRIBUTES); XmlSchemaInfo info = new XmlSchemaInfo(); ArrayList atts = new ArrayList(); val.Initialize(); val.ValidateElement("StressElement", "", null); val.GetUnspecifiedDefaultAttributes(atts); foreach (XmlSchemaAttribute a in atts) { val.ValidateAttribute(a.QualifiedName.Name, a.QualifiedName.Namespace, StringGetter(a.DefaultValue), info); Assert.Equal(info.SchemaAttribute, a); } atts.Clear(); val.GetUnspecifiedDefaultAttributes(atts); Assert.Equal(0, atts.Count); return; } [Fact] public void ValidateTopLevelAttribute() { XmlSchemaValidator val; XmlSchemaSet schemas = new XmlSchemaSet(); XmlSchemaInfo info = new XmlSchemaInfo(); schemas.Add("", Path.Combine(TestData, XSDFILE_200_DEF_ATTRIBUTES)); schemas.Compile(); val = CreateValidator(schemas); val.Initialize(); val.ValidateAttribute("BasicAttribute", "", StringGetter("foo"), info); Assert.Equal(info.SchemaAttribute, schemas.GlobalAttributes[new XmlQualifiedName("BasicAttribute")]); return; } [Fact] public void ValidateSameAttributeTwice() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement("RequiredAttributeElement", "", null); val.ValidateAttribute("RequiredAttribute", "", StringGetter("foo"), info); try { val.ValidateAttribute("RequiredAttribute", "", StringGetter("foo"), info); } catch (XmlSchemaValidationException e) { _exVerifier.IsExceptionOk(e, "Sch_DuplicateAttribute", new string[] { "RequiredAttribute" }); return; } Assert.True(false); } } // ===================== GetUnspecifiedDefaultAttributes ===================== public class TCGetUnspecifiedDefaultAttributes : CXmlSchemaValidatorTestCase { private ITestOutputHelper _output; public TCGetUnspecifiedDefaultAttributes(ITestOutputHelper output) : base(output) { _output = output; } [Fact] public void PassNull__Invalid() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); XmlSchemaInfo info = new XmlSchemaInfo(); val.Initialize(); val.ValidateElement("OneAttributeElement", "", null); try { val.GetUnspecifiedDefaultAttributes(null); } catch (ArgumentNullException) { return; } Assert.True(false); } [Fact] public void CallTwice() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); ArrayList atts = new ArrayList(); val.Initialize(); val.ValidateElement("MixedAttributesElement", "", null); val.GetUnspecifiedDefaultAttributes(atts); CheckDefaultAttributes(atts, new string[] { "def1", "def2" }); atts.Clear(); val.GetUnspecifiedDefaultAttributes(atts); CheckDefaultAttributes(atts, new string[] { "def1", "def2" }); return; } [Fact] public void NestBetweenValidateAttributeCalls() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); ArrayList atts = new ArrayList(); val.Initialize(); val.ValidateElement("MixedAttributesElement", "", null); val.GetUnspecifiedDefaultAttributes(atts); CheckDefaultAttributes(atts, new string[] { "def1", "def2" }); val.ValidateAttribute("req1", "", StringGetter("foo"), null); atts.Clear(); val.GetUnspecifiedDefaultAttributes(atts); CheckDefaultAttributes(atts, new string[] { "def1", "def2" }); val.ValidateAttribute("req2", "", StringGetter("foo"), null); atts.Clear(); val.GetUnspecifiedDefaultAttributes(atts); CheckDefaultAttributes(atts, new string[] { "def1", "def2" }); return; } [Fact] public void CallAfterGetExpectedAttributes() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); ArrayList atts = new ArrayList(); val.Initialize(); val.ValidateElement("MixedAttributesElement", "", null); val.ValidateAttribute("req1", "", StringGetter("foo"), null); val.GetExpectedAttributes(); val.GetUnspecifiedDefaultAttributes(atts); CheckDefaultAttributes(atts, new string[] { "def1", "def2" }); return; } [Fact] public void CallAfterValidatingSomeDefaultAttributes() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); ArrayList atts = new ArrayList(); val.Initialize(); val.ValidateElement("MixedAttributesElement", "", null); val.ValidateAttribute("def1", "", StringGetter("foo"), null); val.GetUnspecifiedDefaultAttributes(atts); CheckDefaultAttributes(atts, new string[] { "def2" }); val.ValidateAttribute("def2", "", StringGetter("foo"), null); atts.Clear(); val.GetUnspecifiedDefaultAttributes(atts); CheckDefaultAttributes(atts, new string[] { }); return; } [Fact] public void CallOnElementWithFixedAttribute() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); ArrayList atts = new ArrayList(); val.Initialize(); val.ValidateElement("FixedAttributeElement", "", null); val.GetUnspecifiedDefaultAttributes(atts); CheckDefaultAttributes(atts, new string[] { "FixedAttribute" }); return; } [Fact] public void v6a() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); ArrayList atts = new ArrayList(); val.Initialize(); val.ValidateElement("FixedRequiredAttributeElement", "", null); val.GetUnspecifiedDefaultAttributes(atts); CheckDefaultAttributes(atts, new string[] { }); return; } private void CheckDefaultAttributes(ArrayList actual, string[] expected) { int nFound; Assert.Equal(actual.Count, expected.Length); foreach (string str in expected) { nFound = 0; foreach (XmlSchemaAttribute attr in actual) { if (attr.QualifiedName.Name == str) nFound++; } Assert.Equal(1, nFound); } } } // ===================== ValidateEndOfAttributes ===================== public class TCValidateEndOfAttributes : CXmlSchemaValidatorTestCase { private ITestOutputHelper _output; private ExceptionVerifier _exVerifier; public TCValidateEndOfAttributes(ITestOutputHelper output) : base(output) { _output = output; _exVerifier = new ExceptionVerifier("System.Xml", _output); } [Fact] public void CallOnELementWithNoAttributes() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); val.Initialize(); val.ValidateElement("NoAttributesElement", "", null); val.ValidateEndOfAttributes(null); return; } [Fact] public void CallAfterValidationOfAllAttributes() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); val.Initialize(); val.ValidateElement("MixedAttributesElement", "", null); foreach (string attr in new string[] { "req1", "req2", "def1", "def2" }) val.ValidateAttribute(attr, "", StringGetter("foo"), null); val.ValidateEndOfAttributes(null); return; } [Theory] [InlineData("OptionalAttribute")] [InlineData("FixedAttribute")] public void CallWithoutValidationOf_Optional_Fixed_Attributes(string attrType) { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); val.Initialize(); val.ValidateElement(attrType + "Element", "", null); val.ValidateEndOfAttributes(null); return; } [Theory] [InlineData(true)] [InlineData(false)] public void CallWithoutValidationOfDefaultAttributesGetUnspecifiedDefault_Called_NotCalled(bool call) { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); ArrayList atts = new ArrayList(); val.Initialize(); val.ValidateElement("DefaultAttributeElement", "", null); if (call) val.GetUnspecifiedDefaultAttributes(atts); val.ValidateEndOfAttributes(null); return; } [Fact] public void CallWithoutValidationOfRequiredAttribute() { XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_ATTRIBUTE); ArrayList atts = new ArrayList(); val.Initialize(); val.ValidateElement("RequiredAttributeElement", "", null); try { val.ValidateEndOfAttributes(null); } catch (XmlSchemaValidationException e) { _exVerifier.IsExceptionOk(e, "Sch_MissRequiredAttribute", new string[] { "RequiredAttribute" }); return; } Assert.True(false); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //Testing simple math on local vars and fields - mul #pragma warning disable 0414 using System; internal class lclfldmul { //user-defined class that overloads operator * public class numHolder { private int _i_num; private uint _ui_num; private long _l_num; private ulong _ul_num; private float _f_num; private double _d_num; private decimal _m_num; public numHolder(int i_num) { _i_num = Convert.ToInt32(i_num); _ui_num = Convert.ToUInt32(i_num); _l_num = Convert.ToInt64(i_num); _ul_num = Convert.ToUInt64(i_num); _f_num = Convert.ToSingle(i_num); _d_num = Convert.ToDouble(i_num); _m_num = Convert.ToDecimal(i_num); } public static int operator *(numHolder a, int b) { return a._i_num * b; } public numHolder(uint ui_num) { _i_num = Convert.ToInt32(ui_num); _ui_num = Convert.ToUInt32(ui_num); _l_num = Convert.ToInt64(ui_num); _ul_num = Convert.ToUInt64(ui_num); _f_num = Convert.ToSingle(ui_num); _d_num = Convert.ToDouble(ui_num); _m_num = Convert.ToDecimal(ui_num); } public static uint operator *(numHolder a, uint b) { return a._ui_num * b; } public numHolder(long l_num) { _i_num = Convert.ToInt32(l_num); _ui_num = Convert.ToUInt32(l_num); _l_num = Convert.ToInt64(l_num); _ul_num = Convert.ToUInt64(l_num); _f_num = Convert.ToSingle(l_num); _d_num = Convert.ToDouble(l_num); _m_num = Convert.ToDecimal(l_num); } public static long operator *(numHolder a, long b) { return a._l_num * b; } public numHolder(ulong ul_num) { _i_num = Convert.ToInt32(ul_num); _ui_num = Convert.ToUInt32(ul_num); _l_num = Convert.ToInt64(ul_num); _ul_num = Convert.ToUInt64(ul_num); _f_num = Convert.ToSingle(ul_num); _d_num = Convert.ToDouble(ul_num); _m_num = Convert.ToDecimal(ul_num); } public static long operator *(numHolder a, ulong b) { return (long)(a._ul_num * b); } public numHolder(float f_num) { _i_num = Convert.ToInt32(f_num); _ui_num = Convert.ToUInt32(f_num); _l_num = Convert.ToInt64(f_num); _ul_num = Convert.ToUInt64(f_num); _f_num = Convert.ToSingle(f_num); _d_num = Convert.ToDouble(f_num); _m_num = Convert.ToDecimal(f_num); } public static float operator *(numHolder a, float b) { return a._f_num * b; } public numHolder(double d_num) { _i_num = Convert.ToInt32(d_num); _ui_num = Convert.ToUInt32(d_num); _l_num = Convert.ToInt64(d_num); _ul_num = Convert.ToUInt64(d_num); _f_num = Convert.ToSingle(d_num); _d_num = Convert.ToDouble(d_num); _m_num = Convert.ToDecimal(d_num); } public static double operator *(numHolder a, double b) { return a._d_num * b; } public numHolder(decimal m_num) { _i_num = Convert.ToInt32(m_num); _ui_num = Convert.ToUInt32(m_num); _l_num = Convert.ToInt64(m_num); _ul_num = Convert.ToUInt64(m_num); _f_num = Convert.ToSingle(m_num); _d_num = Convert.ToDouble(m_num); _m_num = Convert.ToDecimal(m_num); } public static int operator *(numHolder a, decimal b) { return (int)(a._m_num * b); } public static int operator *(numHolder a, numHolder b) { return a._i_num * b._i_num; } } private static int s_i_s_op1 = 3; private static uint s_ui_s_op1 = 3; private static long s_l_s_op1 = 3; private static ulong s_ul_s_op1 = 3; private static float s_f_s_op1 = 3; private static double s_d_s_op1 = 3; private static decimal s_m_s_op1 = 3; private static int s_i_s_op2 = 7; private static uint s_ui_s_op2 = 7; private static long s_l_s_op2 = 7; private static ulong s_ul_s_op2 = 7; private static float s_f_s_op2 = 7; private static double s_d_s_op2 = 7; private static decimal s_m_s_op2 = 7; private static numHolder s_nHldr_s_op2 = new numHolder(7); public static int i_f(String s) { if (s == "op1") return 3; else return 7; } public static uint ui_f(String s) { if (s == "op1") return 3; else return 7; } public static long l_f(String s) { if (s == "op1") return 3; else return 7; } public static ulong ul_f(String s) { if (s == "op1") return 3; else return 7; } public static float f_f(String s) { if (s == "op1") return 3; else return 7; } public static double d_f(String s) { if (s == "op1") return 3; else return 7; } public static decimal m_f(String s) { if (s == "op1") return 3; else return 7; } public static numHolder nHldr_f(String s) { if (s == "op1") return new numHolder(3); else return new numHolder(7); } private class CL { public int i_cl_op1 = 3; public uint ui_cl_op1 = 3; public long l_cl_op1 = 3; public ulong ul_cl_op1 = 3; public float f_cl_op1 = 3; public double d_cl_op1 = 3; public decimal m_cl_op1 = 3; public int i_cl_op2 = 7; public uint ui_cl_op2 = 7; public long l_cl_op2 = 7; public ulong ul_cl_op2 = 7; public float f_cl_op2 = 7; public double d_cl_op2 = 7; public decimal m_cl_op2 = 7; public numHolder nHldr_cl_op2 = new numHolder(7); } private struct VT { public int i_vt_op1; public uint ui_vt_op1; public long l_vt_op1; public ulong ul_vt_op1; public float f_vt_op1; public double d_vt_op1; public decimal m_vt_op1; public int i_vt_op2; public uint ui_vt_op2; public long l_vt_op2; public ulong ul_vt_op2; public float f_vt_op2; public double d_vt_op2; public decimal m_vt_op2; public numHolder nHldr_vt_op2; } public static int Main() { bool passed = true; //initialize class CL cl1 = new CL(); //initialize struct VT vt1; vt1.i_vt_op1 = 3; vt1.ui_vt_op1 = 3; vt1.l_vt_op1 = 3; vt1.ul_vt_op1 = 3; vt1.f_vt_op1 = 3; vt1.d_vt_op1 = 3; vt1.m_vt_op1 = 3; vt1.i_vt_op2 = 7; vt1.ui_vt_op2 = 7; vt1.l_vt_op2 = 7; vt1.ul_vt_op2 = 7; vt1.f_vt_op2 = 7; vt1.d_vt_op2 = 7; vt1.m_vt_op2 = 7; vt1.nHldr_vt_op2 = new numHolder(7); int[] i_arr1d_op1 = { 0, 3 }; int[,] i_arr2d_op1 = { { 0, 3 }, { 1, 1 } }; int[,,] i_arr3d_op1 = { { { 0, 3 }, { 1, 1 } } }; uint[] ui_arr1d_op1 = { 0, 3 }; uint[,] ui_arr2d_op1 = { { 0, 3 }, { 1, 1 } }; uint[,,] ui_arr3d_op1 = { { { 0, 3 }, { 1, 1 } } }; long[] l_arr1d_op1 = { 0, 3 }; long[,] l_arr2d_op1 = { { 0, 3 }, { 1, 1 } }; long[,,] l_arr3d_op1 = { { { 0, 3 }, { 1, 1 } } }; ulong[] ul_arr1d_op1 = { 0, 3 }; ulong[,] ul_arr2d_op1 = { { 0, 3 }, { 1, 1 } }; ulong[,,] ul_arr3d_op1 = { { { 0, 3 }, { 1, 1 } } }; float[] f_arr1d_op1 = { 0, 3 }; float[,] f_arr2d_op1 = { { 0, 3 }, { 1, 1 } }; float[,,] f_arr3d_op1 = { { { 0, 3 }, { 1, 1 } } }; double[] d_arr1d_op1 = { 0, 3 }; double[,] d_arr2d_op1 = { { 0, 3 }, { 1, 1 } }; double[,,] d_arr3d_op1 = { { { 0, 3 }, { 1, 1 } } }; decimal[] m_arr1d_op1 = { 0, 3 }; decimal[,] m_arr2d_op1 = { { 0, 3 }, { 1, 1 } }; decimal[,,] m_arr3d_op1 = { { { 0, 3 }, { 1, 1 } } }; int[] i_arr1d_op2 = { 7, 0, 1 }; int[,] i_arr2d_op2 = { { 0, 7 }, { 1, 1 } }; int[,,] i_arr3d_op2 = { { { 0, 7 }, { 1, 1 } } }; uint[] ui_arr1d_op2 = { 7, 0, 1 }; uint[,] ui_arr2d_op2 = { { 0, 7 }, { 1, 1 } }; uint[,,] ui_arr3d_op2 = { { { 0, 7 }, { 1, 1 } } }; long[] l_arr1d_op2 = { 7, 0, 1 }; long[,] l_arr2d_op2 = { { 0, 7 }, { 1, 1 } }; long[,,] l_arr3d_op2 = { { { 0, 7 }, { 1, 1 } } }; ulong[] ul_arr1d_op2 = { 7, 0, 1 }; ulong[,] ul_arr2d_op2 = { { 0, 7 }, { 1, 1 } }; ulong[,,] ul_arr3d_op2 = { { { 0, 7 }, { 1, 1 } } }; float[] f_arr1d_op2 = { 7, 0, 1 }; float[,] f_arr2d_op2 = { { 0, 7 }, { 1, 1 } }; float[,,] f_arr3d_op2 = { { { 0, 7 }, { 1, 1 } } }; double[] d_arr1d_op2 = { 7, 0, 1 }; double[,] d_arr2d_op2 = { { 0, 7 }, { 1, 1 } }; double[,,] d_arr3d_op2 = { { { 0, 7 }, { 1, 1 } } }; decimal[] m_arr1d_op2 = { 7, 0, 1 }; decimal[,] m_arr2d_op2 = { { 0, 7 }, { 1, 1 } }; decimal[,,] m_arr3d_op2 = { { { 0, 7 }, { 1, 1 } } }; numHolder[] nHldr_arr1d_op2 = { new numHolder(7), new numHolder(0), new numHolder(1) }; numHolder[,] nHldr_arr2d_op2 = { { new numHolder(0), new numHolder(7) }, { new numHolder(1), new numHolder(1) } }; numHolder[,,] nHldr_arr3d_op2 = { { { new numHolder(0), new numHolder(7) }, { new numHolder(1), new numHolder(1) } } }; int[,] index = { { 0, 0 }, { 1, 1 } }; { int i_l_op1 = 3; int i_l_op2 = 7; uint ui_l_op2 = 7; long l_l_op2 = 7; ulong ul_l_op2 = 7; float f_l_op2 = 7; double d_l_op2 = 7; decimal m_l_op2 = 7; numHolder nHldr_l_op2 = new numHolder(7); if ((i_l_op1 * i_l_op2 != i_l_op1 * ui_l_op2) || (i_l_op1 * ui_l_op2 != i_l_op1 * l_l_op2) || (i_l_op1 * l_l_op2 != i_l_op1 * (int)ul_l_op2) || (i_l_op1 * (int)ul_l_op2 != i_l_op1 * f_l_op2) || (i_l_op1 * f_l_op2 != i_l_op1 * d_l_op2) || ((decimal)(i_l_op1 * d_l_op2) != i_l_op1 * m_l_op2) || (i_l_op1 * m_l_op2 != i_l_op1 * i_l_op2) || (i_l_op1 * i_l_op2 != 21)) { Console.WriteLine("testcase 1 failed"); passed = false; } if ((i_l_op1 * s_i_s_op2 != i_l_op1 * s_ui_s_op2) || (i_l_op1 * s_ui_s_op2 != i_l_op1 * s_l_s_op2) || (i_l_op1 * s_l_s_op2 != i_l_op1 * (int)s_ul_s_op2) || (i_l_op1 * (int)s_ul_s_op2 != i_l_op1 * s_f_s_op2) || (i_l_op1 * s_f_s_op2 != i_l_op1 * s_d_s_op2) || ((decimal)(i_l_op1 * s_d_s_op2) != i_l_op1 * s_m_s_op2) || (i_l_op1 * s_m_s_op2 != i_l_op1 * s_i_s_op2) || (i_l_op1 * s_i_s_op2 != 21)) { Console.WriteLine("testcase 2 failed"); passed = false; } if ((s_i_s_op1 * i_l_op2 != s_i_s_op1 * ui_l_op2) || (s_i_s_op1 * ui_l_op2 != s_i_s_op1 * l_l_op2) || (s_i_s_op1 * l_l_op2 != s_i_s_op1 * (int)ul_l_op2) || (s_i_s_op1 * (int)ul_l_op2 != s_i_s_op1 * f_l_op2) || (s_i_s_op1 * f_l_op2 != s_i_s_op1 * d_l_op2) || ((decimal)(s_i_s_op1 * d_l_op2) != s_i_s_op1 * m_l_op2) || (s_i_s_op1 * m_l_op2 != s_i_s_op1 * i_l_op2) || (s_i_s_op1 * i_l_op2 != 21)) { Console.WriteLine("testcase 3 failed"); passed = false; } if ((s_i_s_op1 * s_i_s_op2 != s_i_s_op1 * s_ui_s_op2) || (s_i_s_op1 * s_ui_s_op2 != s_i_s_op1 * s_l_s_op2) || (s_i_s_op1 * s_l_s_op2 != s_i_s_op1 * (int)s_ul_s_op2) || (s_i_s_op1 * (int)s_ul_s_op2 != s_i_s_op1 * s_f_s_op2) || (s_i_s_op1 * s_f_s_op2 != s_i_s_op1 * s_d_s_op2) || ((decimal)(s_i_s_op1 * s_d_s_op2) != s_i_s_op1 * s_m_s_op2) || (s_i_s_op1 * s_m_s_op2 != s_i_s_op1 * s_i_s_op2) || (s_i_s_op1 * s_i_s_op2 != 21)) { Console.WriteLine("testcase 4 failed"); passed = false; } } { uint ui_l_op1 = 3; int i_l_op2 = 7; uint ui_l_op2 = 7; long l_l_op2 = 7; ulong ul_l_op2 = 7; float f_l_op2 = 7; double d_l_op2 = 7; decimal m_l_op2 = 7; numHolder nHldr_l_op2 = new numHolder(7); if ((ui_l_op1 * i_l_op2 != ui_l_op1 * ui_l_op2) || (ui_l_op1 * ui_l_op2 != ui_l_op1 * l_l_op2) || ((ulong)(ui_l_op1 * l_l_op2) != ui_l_op1 * ul_l_op2) || (ui_l_op1 * ul_l_op2 != ui_l_op1 * f_l_op2) || (ui_l_op1 * f_l_op2 != ui_l_op1 * d_l_op2) || ((decimal)(ui_l_op1 * d_l_op2) != ui_l_op1 * m_l_op2) || (ui_l_op1 * m_l_op2 != ui_l_op1 * i_l_op2) || (ui_l_op1 * i_l_op2 != 21)) { Console.WriteLine("testcase 5 failed"); passed = false; } if ((ui_l_op1 * s_i_s_op2 != ui_l_op1 * s_ui_s_op2) || (ui_l_op1 * s_ui_s_op2 != ui_l_op1 * s_l_s_op2) || ((ulong)(ui_l_op1 * s_l_s_op2) != ui_l_op1 * s_ul_s_op2) || (ui_l_op1 * s_ul_s_op2 != ui_l_op1 * s_f_s_op2) || (ui_l_op1 * s_f_s_op2 != ui_l_op1 * s_d_s_op2) || ((decimal)(ui_l_op1 * s_d_s_op2) != ui_l_op1 * s_m_s_op2) || (ui_l_op1 * s_m_s_op2 != ui_l_op1 * s_i_s_op2) || (ui_l_op1 * s_i_s_op2 != 21)) { Console.WriteLine("testcase 6 failed"); passed = false; } if ((s_ui_s_op1 * i_l_op2 != s_ui_s_op1 * ui_l_op2) || (s_ui_s_op1 * ui_l_op2 != s_ui_s_op1 * l_l_op2) || ((ulong)(s_ui_s_op1 * l_l_op2) != s_ui_s_op1 * ul_l_op2) || (s_ui_s_op1 * ul_l_op2 != s_ui_s_op1 * f_l_op2) || (s_ui_s_op1 * f_l_op2 != s_ui_s_op1 * d_l_op2) || ((decimal)(s_ui_s_op1 * d_l_op2) != s_ui_s_op1 * m_l_op2) || (s_ui_s_op1 * m_l_op2 != s_ui_s_op1 * i_l_op2) || (s_ui_s_op1 * i_l_op2 != 21)) { Console.WriteLine("testcase 7 failed"); passed = false; } if ((s_ui_s_op1 * s_i_s_op2 != s_ui_s_op1 * s_ui_s_op2) || (s_ui_s_op1 * s_ui_s_op2 != s_ui_s_op1 * s_l_s_op2) || ((ulong)(s_ui_s_op1 * s_l_s_op2) != s_ui_s_op1 * s_ul_s_op2) || (s_ui_s_op1 * s_ul_s_op2 != s_ui_s_op1 * s_f_s_op2) || (s_ui_s_op1 * s_f_s_op2 != s_ui_s_op1 * s_d_s_op2) || ((decimal)(s_ui_s_op1 * s_d_s_op2) != s_ui_s_op1 * s_m_s_op2) || (s_ui_s_op1 * s_m_s_op2 != s_ui_s_op1 * s_i_s_op2) || (s_ui_s_op1 * s_i_s_op2 != 21)) { Console.WriteLine("testcase 8 failed"); passed = false; } } { long l_l_op1 = 3; int i_l_op2 = 7; uint ui_l_op2 = 7; long l_l_op2 = 7; ulong ul_l_op2 = 7; float f_l_op2 = 7; double d_l_op2 = 7; decimal m_l_op2 = 7; numHolder nHldr_l_op2 = new numHolder(7); if ((l_l_op1 * i_l_op2 != l_l_op1 * ui_l_op2) || (l_l_op1 * ui_l_op2 != l_l_op1 * l_l_op2) || (l_l_op1 * l_l_op2 != l_l_op1 * (long)ul_l_op2) || (l_l_op1 * (long)ul_l_op2 != l_l_op1 * f_l_op2) || (l_l_op1 * f_l_op2 != l_l_op1 * d_l_op2) || ((decimal)(l_l_op1 * d_l_op2) != l_l_op1 * m_l_op2) || (l_l_op1 * m_l_op2 != l_l_op1 * i_l_op2) || (l_l_op1 * i_l_op2 != 21)) { Console.WriteLine("testcase 9 failed"); passed = false; } if ((l_l_op1 * s_i_s_op2 != l_l_op1 * s_ui_s_op2) || (l_l_op1 * s_ui_s_op2 != l_l_op1 * s_l_s_op2) || (l_l_op1 * s_l_s_op2 != l_l_op1 * (long)s_ul_s_op2) || (l_l_op1 * (long)s_ul_s_op2 != l_l_op1 * s_f_s_op2) || (l_l_op1 * s_f_s_op2 != l_l_op1 * s_d_s_op2) || ((decimal)(l_l_op1 * s_d_s_op2) != l_l_op1 * s_m_s_op2) || (l_l_op1 * s_m_s_op2 != l_l_op1 * s_i_s_op2) || (l_l_op1 * s_i_s_op2 != 21)) { Console.WriteLine("testcase 10 failed"); passed = false; } if ((s_l_s_op1 * i_l_op2 != s_l_s_op1 * ui_l_op2) || (s_l_s_op1 * ui_l_op2 != s_l_s_op1 * l_l_op2) || (s_l_s_op1 * l_l_op2 != s_l_s_op1 * (long)ul_l_op2) || (s_l_s_op1 * (long)ul_l_op2 != s_l_s_op1 * f_l_op2) || (s_l_s_op1 * f_l_op2 != s_l_s_op1 * d_l_op2) || ((decimal)(s_l_s_op1 * d_l_op2) != s_l_s_op1 * m_l_op2) || (s_l_s_op1 * m_l_op2 != s_l_s_op1 * i_l_op2) || (s_l_s_op1 * i_l_op2 != 21)) { Console.WriteLine("testcase 11 failed"); passed = false; } if ((s_l_s_op1 * s_i_s_op2 != s_l_s_op1 * s_ui_s_op2) || (s_l_s_op1 * s_ui_s_op2 != s_l_s_op1 * s_l_s_op2) || (s_l_s_op1 * s_l_s_op2 != s_l_s_op1 * (long)s_ul_s_op2) || (s_l_s_op1 * (long)s_ul_s_op2 != s_l_s_op1 * s_f_s_op2) || (s_l_s_op1 * s_f_s_op2 != s_l_s_op1 * s_d_s_op2) || ((decimal)(s_l_s_op1 * s_d_s_op2) != s_l_s_op1 * s_m_s_op2) || (s_l_s_op1 * s_m_s_op2 != s_l_s_op1 * s_i_s_op2) || (s_l_s_op1 * s_i_s_op2 != 21)) { Console.WriteLine("testcase 12 failed"); passed = false; } } { ulong ul_l_op1 = 3; int i_l_op2 = 7; uint ui_l_op2 = 7; long l_l_op2 = 7; ulong ul_l_op2 = 7; float f_l_op2 = 7; double d_l_op2 = 7; decimal m_l_op2 = 7; numHolder nHldr_l_op2 = new numHolder(7); if ((ul_l_op1 * (ulong)i_l_op2 != ul_l_op1 * ui_l_op2) || (ul_l_op1 * ui_l_op2 != ul_l_op1 * (ulong)l_l_op2) || (ul_l_op1 * (ulong)l_l_op2 != ul_l_op1 * ul_l_op2) || (ul_l_op1 * ul_l_op2 != ul_l_op1 * f_l_op2) || (ul_l_op1 * f_l_op2 != ul_l_op1 * d_l_op2) || ((decimal)(ul_l_op1 * d_l_op2) != ul_l_op1 * m_l_op2) || (ul_l_op1 * m_l_op2 != ul_l_op1 * (ulong)i_l_op2) || (ul_l_op1 * (ulong)i_l_op2 != 21)) { Console.WriteLine("testcase 13 failed"); passed = false; } if ((ul_l_op1 * (ulong)s_i_s_op2 != ul_l_op1 * s_ui_s_op2) || (ul_l_op1 * s_ui_s_op2 != ul_l_op1 * (ulong)s_l_s_op2) || (ul_l_op1 * (ulong)s_l_s_op2 != ul_l_op1 * s_ul_s_op2) || (ul_l_op1 * s_ul_s_op2 != ul_l_op1 * s_f_s_op2) || (ul_l_op1 * s_f_s_op2 != ul_l_op1 * s_d_s_op2) || ((decimal)(ul_l_op1 * s_d_s_op2) != ul_l_op1 * s_m_s_op2) || (ul_l_op1 * s_m_s_op2 != ul_l_op1 * (ulong)s_i_s_op2) || (ul_l_op1 * (ulong)s_i_s_op2 != 21)) { Console.WriteLine("testcase 14 failed"); passed = false; } if ((s_ul_s_op1 * (ulong)i_l_op2 != s_ul_s_op1 * ui_l_op2) || (s_ul_s_op1 * ui_l_op2 != s_ul_s_op1 * (ulong)l_l_op2) || (s_ul_s_op1 * (ulong)l_l_op2 != s_ul_s_op1 * ul_l_op2) || (s_ul_s_op1 * ul_l_op2 != s_ul_s_op1 * f_l_op2) || (s_ul_s_op1 * f_l_op2 != s_ul_s_op1 * d_l_op2) || ((decimal)(s_ul_s_op1 * d_l_op2) != s_ul_s_op1 * m_l_op2) || (s_ul_s_op1 * m_l_op2 != s_ul_s_op1 * (ulong)i_l_op2) || (s_ul_s_op1 * (ulong)i_l_op2 != 21)) { Console.WriteLine("testcase 15 failed"); passed = false; } if ((s_ul_s_op1 * (ulong)s_i_s_op2 != s_ul_s_op1 * s_ui_s_op2) || (s_ul_s_op1 * s_ui_s_op2 != s_ul_s_op1 * (ulong)s_l_s_op2) || (s_ul_s_op1 * (ulong)s_l_s_op2 != s_ul_s_op1 * s_ul_s_op2) || (s_ul_s_op1 * s_ul_s_op2 != s_ul_s_op1 * s_f_s_op2) || (s_ul_s_op1 * s_f_s_op2 != s_ul_s_op1 * s_d_s_op2) || ((decimal)(s_ul_s_op1 * s_d_s_op2) != s_ul_s_op1 * s_m_s_op2) || (s_ul_s_op1 * s_m_s_op2 != s_ul_s_op1 * (ulong)s_i_s_op2) || (s_ul_s_op1 * (ulong)s_i_s_op2 != 21)) { Console.WriteLine("testcase 16 failed"); passed = false; } } { float f_l_op1 = 3; int i_l_op2 = 7; uint ui_l_op2 = 7; long l_l_op2 = 7; ulong ul_l_op2 = 7; float f_l_op2 = 7; double d_l_op2 = 7; decimal m_l_op2 = 7; numHolder nHldr_l_op2 = new numHolder(7); if ((f_l_op1 * i_l_op2 != f_l_op1 * ui_l_op2) || (f_l_op1 * ui_l_op2 != f_l_op1 * l_l_op2) || (f_l_op1 * l_l_op2 != f_l_op1 * ul_l_op2) || (f_l_op1 * ul_l_op2 != f_l_op1 * f_l_op2) || (f_l_op1 * f_l_op2 != f_l_op1 * d_l_op2) || (f_l_op1 * d_l_op2 != f_l_op1 * (float)m_l_op2) || (f_l_op1 * (float)m_l_op2 != f_l_op1 * i_l_op2) || (f_l_op1 * i_l_op2 != 21)) { Console.WriteLine("testcase 17 failed"); passed = false; } if ((f_l_op1 * s_i_s_op2 != f_l_op1 * s_ui_s_op2) || (f_l_op1 * s_ui_s_op2 != f_l_op1 * s_l_s_op2) || (f_l_op1 * s_l_s_op2 != f_l_op1 * s_ul_s_op2) || (f_l_op1 * s_ul_s_op2 != f_l_op1 * s_f_s_op2) || (f_l_op1 * s_f_s_op2 != f_l_op1 * s_d_s_op2) || (f_l_op1 * s_d_s_op2 != f_l_op1 * (float)s_m_s_op2) || (f_l_op1 * (float)s_m_s_op2 != f_l_op1 * s_i_s_op2) || (f_l_op1 * s_i_s_op2 != 21)) { Console.WriteLine("testcase 18 failed"); passed = false; } if ((s_f_s_op1 * i_l_op2 != s_f_s_op1 * ui_l_op2) || (s_f_s_op1 * ui_l_op2 != s_f_s_op1 * l_l_op2) || (s_f_s_op1 * l_l_op2 != s_f_s_op1 * ul_l_op2) || (s_f_s_op1 * ul_l_op2 != s_f_s_op1 * f_l_op2) || (s_f_s_op1 * f_l_op2 != s_f_s_op1 * d_l_op2) || (s_f_s_op1 * d_l_op2 != s_f_s_op1 * (float)m_l_op2) || (s_f_s_op1 * (float)m_l_op2 != s_f_s_op1 * i_l_op2) || (s_f_s_op1 * i_l_op2 != 21)) { Console.WriteLine("testcase 19 failed"); passed = false; } if ((s_f_s_op1 * s_i_s_op2 != s_f_s_op1 * s_ui_s_op2) || (s_f_s_op1 * s_ui_s_op2 != s_f_s_op1 * s_l_s_op2) || (s_f_s_op1 * s_l_s_op2 != s_f_s_op1 * s_ul_s_op2) || (s_f_s_op1 * s_ul_s_op2 != s_f_s_op1 * s_f_s_op2) || (s_f_s_op1 * s_f_s_op2 != s_f_s_op1 * s_d_s_op2) || (s_f_s_op1 * s_d_s_op2 != s_f_s_op1 * (float)s_m_s_op2) || (s_f_s_op1 * (float)s_m_s_op2 != s_f_s_op1 * s_i_s_op2) || (s_f_s_op1 * s_i_s_op2 != 21)) { Console.WriteLine("testcase 20 failed"); passed = false; } } { double d_l_op1 = 3; int i_l_op2 = 7; uint ui_l_op2 = 7; long l_l_op2 = 7; ulong ul_l_op2 = 7; float f_l_op2 = 7; double d_l_op2 = 7; decimal m_l_op2 = 7; numHolder nHldr_l_op2 = new numHolder(7); if ((d_l_op1 * i_l_op2 != d_l_op1 * ui_l_op2) || (d_l_op1 * ui_l_op2 != d_l_op1 * l_l_op2) || (d_l_op1 * l_l_op2 != d_l_op1 * ul_l_op2) || (d_l_op1 * ul_l_op2 != d_l_op1 * f_l_op2) || (d_l_op1 * f_l_op2 != d_l_op1 * d_l_op2) || (d_l_op1 * d_l_op2 != d_l_op1 * (double)m_l_op2) || (d_l_op1 * (double)m_l_op2 != d_l_op1 * i_l_op2) || (d_l_op1 * i_l_op2 != 21)) { Console.WriteLine("testcase 21 failed"); passed = false; } if ((d_l_op1 * s_i_s_op2 != d_l_op1 * s_ui_s_op2) || (d_l_op1 * s_ui_s_op2 != d_l_op1 * s_l_s_op2) || (d_l_op1 * s_l_s_op2 != d_l_op1 * s_ul_s_op2) || (d_l_op1 * s_ul_s_op2 != d_l_op1 * s_f_s_op2) || (d_l_op1 * s_f_s_op2 != d_l_op1 * s_d_s_op2) || (d_l_op1 * s_d_s_op2 != d_l_op1 * (double)s_m_s_op2) || (d_l_op1 * (double)s_m_s_op2 != d_l_op1 * s_i_s_op2) || (d_l_op1 * s_i_s_op2 != 21)) { Console.WriteLine("testcase 22 failed"); passed = false; } if ((s_d_s_op1 * i_l_op2 != s_d_s_op1 * ui_l_op2) || (s_d_s_op1 * ui_l_op2 != s_d_s_op1 * l_l_op2) || (s_d_s_op1 * l_l_op2 != s_d_s_op1 * ul_l_op2) || (s_d_s_op1 * ul_l_op2 != s_d_s_op1 * f_l_op2) || (s_d_s_op1 * f_l_op2 != s_d_s_op1 * d_l_op2) || (s_d_s_op1 * d_l_op2 != s_d_s_op1 * (double)m_l_op2) || (s_d_s_op1 * (double)m_l_op2 != s_d_s_op1 * i_l_op2) || (s_d_s_op1 * i_l_op2 != 21)) { Console.WriteLine("testcase 23 failed"); passed = false; } if ((s_d_s_op1 * s_i_s_op2 != s_d_s_op1 * s_ui_s_op2) || (s_d_s_op1 * s_ui_s_op2 != s_d_s_op1 * s_l_s_op2) || (s_d_s_op1 * s_l_s_op2 != s_d_s_op1 * s_ul_s_op2) || (s_d_s_op1 * s_ul_s_op2 != s_d_s_op1 * s_f_s_op2) || (s_d_s_op1 * s_f_s_op2 != s_d_s_op1 * s_d_s_op2) || (s_d_s_op1 * s_d_s_op2 != s_d_s_op1 * (double)s_m_s_op2) || (s_d_s_op1 * (double)s_m_s_op2 != s_d_s_op1 * s_i_s_op2) || (s_d_s_op1 * s_i_s_op2 != 21)) { Console.WriteLine("testcase 24 failed"); passed = false; } } { decimal m_l_op1 = 3; int i_l_op2 = 7; uint ui_l_op2 = 7; long l_l_op2 = 7; ulong ul_l_op2 = 7; float f_l_op2 = 7; double d_l_op2 = 7; decimal m_l_op2 = 7; numHolder nHldr_l_op2 = new numHolder(7); if ((m_l_op1 * i_l_op2 != m_l_op1 * ui_l_op2) || (m_l_op1 * ui_l_op2 != m_l_op1 * l_l_op2) || (m_l_op1 * l_l_op2 != m_l_op1 * ul_l_op2) || (m_l_op1 * ul_l_op2 != m_l_op1 * (decimal)f_l_op2) || (m_l_op1 * (decimal)f_l_op2 != m_l_op1 * (decimal)d_l_op2) || (m_l_op1 * (decimal)d_l_op2 != m_l_op1 * m_l_op2) || (m_l_op1 * m_l_op2 != m_l_op1 * i_l_op2) || (m_l_op1 * i_l_op2 != 21)) { Console.WriteLine("testcase 25 failed"); passed = false; } if ((m_l_op1 * s_i_s_op2 != m_l_op1 * s_ui_s_op2) || (m_l_op1 * s_ui_s_op2 != m_l_op1 * s_l_s_op2) || (m_l_op1 * s_l_s_op2 != m_l_op1 * s_ul_s_op2) || (m_l_op1 * s_ul_s_op2 != m_l_op1 * (decimal)s_f_s_op2) || (m_l_op1 * (decimal)s_f_s_op2 != m_l_op1 * (decimal)s_d_s_op2) || (m_l_op1 * (decimal)s_d_s_op2 != m_l_op1 * s_m_s_op2) || (m_l_op1 * s_m_s_op2 != m_l_op1 * s_i_s_op2) || (m_l_op1 * s_i_s_op2 != 21)) { Console.WriteLine("testcase 26 failed"); passed = false; } if ((s_m_s_op1 * i_l_op2 != s_m_s_op1 * ui_l_op2) || (s_m_s_op1 * ui_l_op2 != s_m_s_op1 * l_l_op2) || (s_m_s_op1 * l_l_op2 != s_m_s_op1 * ul_l_op2) || (s_m_s_op1 * ul_l_op2 != s_m_s_op1 * (decimal)f_l_op2) || (s_m_s_op1 * (decimal)f_l_op2 != s_m_s_op1 * (decimal)d_l_op2) || (s_m_s_op1 * (decimal)d_l_op2 != s_m_s_op1 * m_l_op2) || (s_m_s_op1 * m_l_op2 != s_m_s_op1 * i_l_op2) || (s_m_s_op1 * i_l_op2 != 21)) { Console.WriteLine("testcase 27 failed"); passed = false; } if ((s_m_s_op1 * s_i_s_op2 != s_m_s_op1 * s_ui_s_op2) || (s_m_s_op1 * s_ui_s_op2 != s_m_s_op1 * s_l_s_op2) || (s_m_s_op1 * s_l_s_op2 != s_m_s_op1 * s_ul_s_op2) || (s_m_s_op1 * s_ul_s_op2 != s_m_s_op1 * (decimal)s_f_s_op2) || (s_m_s_op1 * (decimal)s_f_s_op2 != s_m_s_op1 * (decimal)s_d_s_op2) || (s_m_s_op1 * (decimal)s_d_s_op2 != s_m_s_op1 * s_m_s_op2) || (s_m_s_op1 * s_m_s_op2 != s_m_s_op1 * s_i_s_op2) || (s_m_s_op1 * s_i_s_op2 != 21)) { Console.WriteLine("testcase 28 failed"); passed = false; } } if (!passed) { Console.WriteLine("FAILED"); return 1; } else { Console.WriteLine("PASSED"); return 100; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.RemoveUnnecessaryImports; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType { internal abstract partial class AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax> { private class MoveTypeEditor : Editor { public MoveTypeEditor( TService service, State state, string fileName, CancellationToken cancellationToken) : base(service, state, fileName, cancellationToken) { } /// <summary> /// Given a document and a type contained in it, moves the type /// out to its own document. The new document's name typically /// is the type name, or is at least based on the type name. /// </summary> /// <remarks> /// The algorithm for this, is as follows: /// 1. Fork the original document that contains the type to be moved. /// 2. Keep the type, required namespace containers and using statements. /// remove everything else from the forked document. /// 3. Add this forked document to the solution. /// 4. Finally, update the original document and remove the type from it. /// </remarks> internal override async Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync() { var solution = SemanticDocument.Document.Project.Solution; // Fork, update and add as new document. var projectToBeUpdated = SemanticDocument.Document.Project; var newDocumentId = DocumentId.CreateNewId(projectToBeUpdated.Id, FileName); var documentWithMovedType = await AddNewDocumentWithSingleTypeDeclarationAndImportsAsync(newDocumentId).ConfigureAwait(false); var solutionWithNewDocument = documentWithMovedType.Project.Solution; // Get the original source document again, from the latest forked solution. var sourceDocument = solutionWithNewDocument.GetDocument(SemanticDocument.Document.Id); // update source document to add partial modifiers to type chain // and/or remove type declaration from original source document. var solutionWithBothDocumentsUpdated = await RemoveTypeFromSourceDocumentAsync( sourceDocument, documentWithMovedType).ConfigureAwait(false); return ImmutableArray.Create<CodeActionOperation>(new ApplyChangesOperation(solutionWithBothDocumentsUpdated)); } /// <summary> /// Forks the source document, keeps required type, namespace containers /// and adds it the solution. /// </summary> /// <param name="newDocumentId">id for the new document to be added</param> /// <returns>the new solution which contains a new document with the type being moved</returns> private async Task<Document> AddNewDocumentWithSingleTypeDeclarationAndImportsAsync( DocumentId newDocumentId) { var document = SemanticDocument.Document; Debug.Assert(document.Name != FileName, $"New document name is same as old document name:{FileName}"); var root = SemanticDocument.Root; var projectToBeUpdated = document.Project; var documentEditor = await DocumentEditor.CreateAsync(document, CancellationToken).ConfigureAwait(false); // Make the type chain above this new type partial. Also, remove any // attributes from the containing partial types. We don't want to create // duplicate attributes on things. AddPartialModifiersToTypeChain( documentEditor, removeAttributesAndComments: true, removeTypeInheritance: true); // remove things that are not being moved, from the forked document. var membersToRemove = GetMembersToRemove(root); foreach (var member in membersToRemove) { documentEditor.RemoveNode(member, SyntaxRemoveOptions.KeepNoTrivia); } var modifiedRoot = documentEditor.GetChangedRoot(); modifiedRoot = await AddFinalNewLineIfDesired(document, modifiedRoot).ConfigureAwait(false); // add an empty document to solution, so that we'll have options from the right context. var solutionWithNewDocument = projectToBeUpdated.Solution.AddDocument( newDocumentId, FileName, text: string.Empty, folders: document.Folders); // update the text for the new document solutionWithNewDocument = solutionWithNewDocument.WithDocumentSyntaxRoot(newDocumentId, modifiedRoot, PreservationMode.PreserveIdentity); // get the updated document, give it the minimal set of imports that the type // inside it needs. var service = document.GetLanguageService<IRemoveUnnecessaryImportsService>(); var newDocument = solutionWithNewDocument.GetDocument(newDocumentId); newDocument = await service.RemoveUnnecessaryImportsAsync(newDocument, CancellationToken).ConfigureAwait(false); return newDocument; } /// <summary> /// Add a trailing newline if we don't already have one if that's what the user's /// preference is. /// </summary> private async Task<SyntaxNode> AddFinalNewLineIfDesired(Document document, SyntaxNode modifiedRoot) { var options = await document.GetOptionsAsync(CancellationToken).ConfigureAwait(false); var insertFinalNewLine = options.GetOption(FormattingOptions.InsertFinalNewLine); if (insertFinalNewLine) { var endOfFileToken = ((ICompilationUnitSyntax)modifiedRoot).EndOfFileToken; var previousToken = endOfFileToken.GetPreviousToken(includeZeroWidth: true, includeSkipped: true); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); if (endOfFileToken.LeadingTrivia.IsEmpty() && !previousToken.TrailingTrivia.Any(syntaxFacts.IsEndOfLineTrivia)) { var generator = SyntaxGenerator.GetGenerator(document); var endOfLine = generator.EndOfLine(options.GetOption(FormattingOptions.NewLine)); return modifiedRoot.ReplaceToken( previousToken, previousToken.WithAppendedTrailingTrivia(endOfLine)); } } return modifiedRoot; } /// <summary> /// update the original document and remove the type that was moved. /// perform other fix ups as necessary. /// </summary> /// <returns>an updated solution with the original document fixed up as appropriate.</returns> private async Task<Solution> RemoveTypeFromSourceDocumentAsync( Document sourceDocument, Document documentWithMovedType) { var documentEditor = await DocumentEditor.CreateAsync(sourceDocument, CancellationToken).ConfigureAwait(false); // Make the type chain above the type we're moving 'partial'. // However, keep all the attributes on these types as theses are the // original attributes and we don't want to mess with them. AddPartialModifiersToTypeChain(documentEditor, removeAttributesAndComments: false, removeTypeInheritance: false); documentEditor.RemoveNode(State.TypeNode, SyntaxRemoveOptions.KeepUnbalancedDirectives); var updatedDocument = documentEditor.GetChangedDocument(); // Now, remove any imports that we no longer need *if* they were used in the new // file with the moved type. Essentially, those imports were here just to serve // that new type and we should remove them. If we have *other* imports that // other file does not use *and* we do not use, we'll still keep those around. // Those may be important to the user for code they're about to write, and we // don't want to interfere with them by removing them. var service = sourceDocument.GetLanguageService<IRemoveUnnecessaryImportsService>(); var syntaxFacts = sourceDocument.GetLanguageService<ISyntaxFactsService>(); var rootWithMovedType = await documentWithMovedType.GetSyntaxRootAsync(CancellationToken).ConfigureAwait(false); var movedImports = rootWithMovedType.DescendantNodes() .Where(syntaxFacts.IsUsingOrExternOrImport) .ToImmutableArray(); Func<SyntaxNode, bool> predicate = n => movedImports.Contains(i => i.IsEquivalentTo(n)); updatedDocument = await service.RemoveUnnecessaryImportsAsync( updatedDocument, predicate, CancellationToken).ConfigureAwait(false); return updatedDocument.Project.Solution; } /// <summary> /// Traverses the syntax tree of the forked document and /// collects a list of nodes that are not being moved. /// This list of nodes are then removed from the forked copy. /// </summary> /// <param name="root">root, of the syntax tree of forked document</param> /// <returns>list of syntax nodes, to be removed from the forked copy.</returns> private ISet<SyntaxNode> GetMembersToRemove(SyntaxNode root) { var spine = new HashSet<SyntaxNode>(); // collect the parent chain of declarations to keep. spine.AddRange(State.TypeNode.GetAncestors()); // get potential namespace, types and members to remove. var removableCandidates = root .DescendantNodes(n => spine.Contains(n)) .Where(n => FilterToTopLevelMembers(n, State.TypeNode)).ToSet(); // diff candidates with items we want to keep. removableCandidates.ExceptWith(spine); #if DEBUG // None of the nodes we're removing should also have any of their parent // nodes removed. If that happened we could get a crash by first trying to remove // the parent, then trying to remove the child. foreach (var node in removableCandidates) { foreach (var ancestor in node.GetAncestors()) { Debug.Assert(!removableCandidates.Contains(ancestor)); } } #endif return removableCandidates; } private static bool FilterToTopLevelMembers(SyntaxNode node, SyntaxNode typeNode) { // We never filter out the actual node we're trying to keep around. if (node == typeNode) { return false; } return node is TTypeDeclarationSyntax || node is TMemberDeclarationSyntax || node is TNamespaceDeclarationSyntax; } /// <summary> /// if a nested type is being moved, this ensures its containing type is partial. /// </summary> private void AddPartialModifiersToTypeChain( DocumentEditor documentEditor, bool removeAttributesAndComments, bool removeTypeInheritance) { var semanticFacts = State.SemanticDocument.Document.GetLanguageService<ISemanticFactsService>(); var typeChain = State.TypeNode.Ancestors().OfType<TTypeDeclarationSyntax>(); foreach (var node in typeChain) { var symbol = (ITypeSymbol)State.SemanticDocument.SemanticModel.GetDeclaredSymbol(node, CancellationToken); if (!semanticFacts.IsPartial(symbol, CancellationToken)) { documentEditor.SetModifiers(node, documentEditor.Generator.GetModifiers(node) | DeclarationModifiers.Partial); } if (removeAttributesAndComments) { documentEditor.RemoveAllAttributes(node); documentEditor.RemoveAllComments(node); } if (removeTypeInheritance) { documentEditor.RemoveAllTypeInheritance(node); } } documentEditor.ReplaceNode(State.TypeNode, (currentNode, generator) => { var currentTypeNode = (TTypeDeclarationSyntax)currentNode; // Trim leading whitespace from the type so we don't have excessive // leading blank lines. return RemoveLeadingWhitespace(currentTypeNode); }); } private TTypeDeclarationSyntax RemoveLeadingWhitespace( TTypeDeclarationSyntax currentTypeNode) { var syntaxFacts = State.SemanticDocument.Document.GetLanguageService<ISyntaxFactsService>(); var leadingTrivia = currentTypeNode.GetLeadingTrivia(); var afterWhitespace = leadingTrivia.SkipWhile( t => syntaxFacts.IsWhitespaceTrivia(t) || syntaxFacts.IsEndOfLineTrivia(t)); var withoutLeadingWhitespace = currentTypeNode.WithLeadingTrivia(afterWhitespace); return withoutLeadingWhitespace.ReplaceToken( withoutLeadingWhitespace.GetFirstToken(), withoutLeadingWhitespace.GetFirstToken().WithAdditionalAnnotations(Formatter.Annotation)); } } } }
/******************************************************************************* * Copyright 2009-2015 Amazon Services. 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://aws.amazon.com/apache2.0 * 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. ******************************************************************************* * Marketplace Web Service Products * API Version: 2011-10-01 * Library Version: 2015-09-01 * Generated: Thu Sep 10 06:52:19 PDT 2015 */ using MarketplaceWebServiceProducts.Model; using System; using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Linq; namespace MarketplaceWebServiceProducts { /// <summary> /// Runnable sample code to demonstrate usage of the C# client. /// /// To use, import the client source as a console application, /// and mark this class as the startup object. Then, replace /// parameters below with sensible values and run. /// </summary> public class MarketplaceWebServiceProductsSample { string mswAuth = "amzn.mws.a6a6c2d9-6772-4770-feb6-6f980a690e29"; string seller = "A2Z4SMPGO6SQTC"; string marketplace = "ATVPDKIKX0DER"; public static void Main(string[] args) { // TODO: Set the below configuration variables before attempting to run // Developer AWS access key string accessKey = "AKIAI6BSCXQFMX4KESMQ"; // Developer AWS secret key string secretKey = "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"; // The client application name string appName = "Vialinker"; // The client application version string appVersion = "1.0"; // The endpoint for region service and version (see developer guide) // ex: https://mws.amazonservices.com string serviceURL = "https://mws.amazonservices.com"; // Create a configuration object MarketplaceWebServiceProductsConfig config = new MarketplaceWebServiceProductsConfig(); config.ServiceURL = serviceURL; // Set other client connection configurations here if needed // Create the client itself MarketplaceWebServiceProducts client = new MarketplaceWebServiceProductsClient(appName, appVersion, accessKey, secretKey, config); MarketplaceWebServiceProductsSample sample = new MarketplaceWebServiceProductsSample(client); // Uncomment the operation you'd like to test here // TODO: Modify the request created in the Invoke method to be valid try { IMWSResponse response = null; // response = sample.InvokeGetCompetitivePricingForASIN(); // response = sample.InvokeGetCompetitivePricingForSKU(); // response = sample.InvokeGetLowestOfferListingsForASIN(); // response = sample.InvokeGetLowestOfferListingsForSKU(); // response = sample.InvokeGetLowestPricedOffersForASIN(); // response = sample.InvokeGetLowestPricedOffersForSKU(); // response = sample.InvokeGetMatchingProduct(); // response = sample.InvokeGetMatchingProductForId(); // response = sample.InvokeGetMyPriceForASIN(); // response = sample.InvokeGetMyPriceForSKU(); // response = sample.InvokeGetProductCategoriesForASIN(); // response = sample.InvokeGetProductCategoriesForSKU(); // response = sample.InvokeGetServiceStatus(); response = sample.InvokeListMatchingProducts(); Console.WriteLine("Response:"); ResponseHeaderMetadata rhmd = response.ResponseHeaderMetadata; // We recommend logging the request id and timestamp of every call. Console.WriteLine("RequestId: " + rhmd.RequestId); Console.WriteLine("Timestamp: " + rhmd.Timestamp); string responseXml = response.ToXML(); responseXml = responseXml.Replace(" xmlns=\"http://mws.amazonservices.com/schema/Products/2011-10-01\"", ""); WriteToTextFile(responseXml); Console.WriteLine(responseXml); Console.ReadKey(); } catch (MarketplaceWebServiceProductsException ex) { // Exception properties are important for diagnostics. ResponseHeaderMetadata rhmd = ex.ResponseHeaderMetadata; Console.WriteLine("Service Exception:"); if (rhmd != null) { Console.WriteLine("RequestId: " + rhmd.RequestId); Console.WriteLine("Timestamp: " + rhmd.Timestamp); } Console.WriteLine("Message: " + ex.Message); Console.WriteLine("StatusCode: " + ex.StatusCode); Console.WriteLine("ErrorCode: " + ex.ErrorCode); Console.WriteLine("ErrorType: " + ex.ErrorType); throw ex; } } private static string GetAmazonItemListLINQ(string responseData) { XElement xmlDoc = XElement.Parse(responseData); return "Working"; } private static void WriteToTextFile(string responseData) { string aa = ""; int i = 1; List<AmazonItem> GetAmazonItemLists = new List<AmazonItem>(); foreach (AmazonItem ai in GetAmazonItemLists) { aa += i + ". Product Information"; aa += "ASIN: " + ai.ASIN; foreach (AmazonItemInfo aii in ai.AII) { aa += "\r\nTitle: " + aii.Title; aa += "\r\nManufacturer: " + aii.Manufacturer; aa += "\r\nModel: " + aii.Model; aa += "\r\nPublisher: " + aii.Publisher; aa += "\r\nProduct Type: " + aii.ProductType; aa += "\r\nProduct Group: " + aii.ProductGroup; aa += "\r\nPart Number: " + aii.PartNumber; aa += "\r\nQuantity: " + aii.Quantity; aa += "\r\nSample Image: " + aii.SampleImage; aa += "\r\nList Price: " + aii.ListPrice + " " + aii.CurrencyCode; aa += "\r\n----------------------------------------------------------------------------------\r\n\r\n"; } i++; } System.IO.StreamWriter file = new System.IO.StreamWriter("d:\\xml_data.txt"); file.WriteLine(aa); file.Close(); //End } private readonly MarketplaceWebServiceProducts client; public MarketplaceWebServiceProductsSample(MarketplaceWebServiceProducts client) { this.client = client; } public GetCompetitivePricingForASINResponse InvokeGetCompetitivePricingForASIN() { // Create a request. GetCompetitivePricingForASINRequest request = new GetCompetitivePricingForASINRequest(); string sellerId = "example"; request.SellerId = sellerId; string mwsAuthToken = "example"; request.MWSAuthToken = mwsAuthToken; string marketplaceId = "example"; request.MarketplaceId = marketplaceId; ASINListType asinList = new ASINListType(); request.ASINList = asinList; return this.client.GetCompetitivePricingForASIN(request); } public GetCompetitivePricingForSKUResponse InvokeGetCompetitivePricingForSKU() { // Create a request. GetCompetitivePricingForSKURequest request = new GetCompetitivePricingForSKURequest(); string sellerId = "example"; request.SellerId = sellerId; string mwsAuthToken = "example"; request.MWSAuthToken = mwsAuthToken; string marketplaceId = "example"; request.MarketplaceId = marketplaceId; SellerSKUListType sellerSKUList = new SellerSKUListType(); request.SellerSKUList = sellerSKUList; return this.client.GetCompetitivePricingForSKU(request); } public GetLowestOfferListingsForASINResponse InvokeGetLowestOfferListingsForASIN() { // Create a request. GetLowestOfferListingsForASINRequest request = new GetLowestOfferListingsForASINRequest(); string sellerId = "example"; request.SellerId = sellerId; string mwsAuthToken = "example"; request.MWSAuthToken = mwsAuthToken; string marketplaceId = "example"; request.MarketplaceId = marketplaceId; ASINListType asinList = new ASINListType(); request.ASINList = asinList; string itemCondition = "example"; request.ItemCondition = itemCondition; bool excludeMe = true; request.ExcludeMe = excludeMe; return this.client.GetLowestOfferListingsForASIN(request); } public GetLowestOfferListingsForSKUResponse InvokeGetLowestOfferListingsForSKU() { // Create a request. GetLowestOfferListingsForSKURequest request = new GetLowestOfferListingsForSKURequest(); string sellerId = "example"; request.SellerId = sellerId; string mwsAuthToken = "example"; request.MWSAuthToken = mwsAuthToken; string marketplaceId = "example"; request.MarketplaceId = marketplaceId; SellerSKUListType sellerSKUList = new SellerSKUListType(); request.SellerSKUList = sellerSKUList; string itemCondition = "example"; request.ItemCondition = itemCondition; bool excludeMe = true; request.ExcludeMe = excludeMe; return this.client.GetLowestOfferListingsForSKU(request); } public GetLowestPricedOffersForASINResponse InvokeGetLowestPricedOffersForASIN() { // Create a request. GetLowestPricedOffersForASINRequest request = new GetLowestPricedOffersForASINRequest(); string sellerId = "example"; request.SellerId = sellerId; string mwsAuthToken = "example"; request.MWSAuthToken = mwsAuthToken; string marketplaceId = "example"; request.MarketplaceId = marketplaceId; string asin = "example"; request.ASIN = asin; string itemCondition = "example"; request.ItemCondition = itemCondition; return this.client.GetLowestPricedOffersForASIN(request); } public GetLowestPricedOffersForSKUResponse InvokeGetLowestPricedOffersForSKU() { // Create a request. GetLowestPricedOffersForSKURequest request = new GetLowestPricedOffersForSKURequest(); string sellerId = "example"; request.SellerId = sellerId; string mwsAuthToken = "example"; request.MWSAuthToken = mwsAuthToken; string marketplaceId = "example"; request.MarketplaceId = marketplaceId; string sellerSKU = "example"; request.SellerSKU = sellerSKU; string itemCondition = "example"; request.ItemCondition = itemCondition; return this.client.GetLowestPricedOffersForSKU(request); } public GetMatchingProductResponse InvokeGetMatchingProduct() { // Create a request. GetMatchingProductRequest request = new GetMatchingProductRequest(); string sellerId = "example"; request.SellerId = sellerId; string mwsAuthToken = "example"; request.MWSAuthToken = mwsAuthToken; string marketplaceId = "example"; request.MarketplaceId = marketplaceId; ASINListType asinList = new ASINListType(); request.ASINList = asinList; return this.client.GetMatchingProduct(request); } public GetMatchingProductForIdResponse InvokeGetMatchingProductForId() { // Create a request. GetMatchingProductForIdRequest request = new GetMatchingProductForIdRequest(); string sellerId = "example"; request.SellerId = sellerId; string mwsAuthToken = "example"; request.MWSAuthToken = mwsAuthToken; string marketplaceId = "example"; request.MarketplaceId = marketplaceId; string idType = "example"; request.IdType = idType; IdListType idList = new IdListType(); request.IdList = idList; return this.client.GetMatchingProductForId(request); } public GetMyPriceForASINResponse InvokeGetMyPriceForASIN() { // Create a request. GetMyPriceForASINRequest request = new GetMyPriceForASINRequest(); string sellerId = "example"; request.SellerId = sellerId; string mwsAuthToken = "example"; request.MWSAuthToken = mwsAuthToken; string marketplaceId = "example"; request.MarketplaceId = marketplaceId; ASINListType asinList = new ASINListType(); request.ASINList = asinList; return this.client.GetMyPriceForASIN(request); } public GetMyPriceForSKUResponse InvokeGetMyPriceForSKU() { // Create a request. GetMyPriceForSKURequest request = new GetMyPriceForSKURequest(); string sellerId = "example"; request.SellerId = sellerId; string mwsAuthToken = "example"; request.MWSAuthToken = mwsAuthToken; string marketplaceId = "example"; request.MarketplaceId = marketplaceId; SellerSKUListType sellerSKUList = new SellerSKUListType(); request.SellerSKUList = sellerSKUList; return this.client.GetMyPriceForSKU(request); } public GetProductCategoriesForASINResponse InvokeGetProductCategoriesForASIN() { // Create a request. GetProductCategoriesForASINRequest request = new GetProductCategoriesForASINRequest(); string sellerId = "example"; request.SellerId = sellerId; string mwsAuthToken = "example"; request.MWSAuthToken = mwsAuthToken; string marketplaceId = "example"; request.MarketplaceId = marketplaceId; string asin = "example"; request.ASIN = asin; return this.client.GetProductCategoriesForASIN(request); } public GetProductCategoriesForSKUResponse InvokeGetProductCategoriesForSKU() { // Create a request. GetProductCategoriesForSKURequest request = new GetProductCategoriesForSKURequest(); string sellerId = "example"; request.SellerId = sellerId; string mwsAuthToken = "example"; request.MWSAuthToken = mwsAuthToken; string marketplaceId = "example"; request.MarketplaceId = marketplaceId; string sellerSKU = "example"; request.SellerSKU = sellerSKU; return this.client.GetProductCategoriesForSKU(request); } public GetServiceStatusResponse InvokeGetServiceStatus() { // Create a request. GetServiceStatusRequest request = new GetServiceStatusRequest(); string sellerId = "example"; request.SellerId = sellerId; string mwsAuthToken = "example"; request.MWSAuthToken = mwsAuthToken; return this.client.GetServiceStatus(request); } public ListMatchingProductsResponse InvokeListMatchingProducts() { // Create a request. ListMatchingProductsRequest request = new ListMatchingProductsRequest(); //string sellerId = "example"; request.SellerId = seller; //string mwsAuthToken = "example"; request.MWSAuthToken = mswAuth; //string marketplaceId = "example"; request.MarketplaceId = marketplace; string query = "mobile"; request.Query = query; //string queryContextId = "example"; //request.QueryContextId = queryContextId; return this.client.ListMatchingProducts(request); } } public class AmazonItem { public string ASIN { get; set; } public List<AmazonItemInfo> AII { get; set; } } public class AmazonItemInfo { public string Title { get; set; } public string Manufacturer { get; set; } public string Model { get; set; } public string Publisher { get; set; } public string ProductType { get; set; } public string ProductGroup { get; set; } public string PartNumber { get; set; } public string Quantity { get; set; } public string SampleImage { get; set; } public string ListPrice { get; set; } public string CurrencyCode { get; set; } } }
/* Copyright (c) 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #region Using directives #define USE_TRACING using System; using System.IO; using System.IO.Compression; using System.Net; using System.Collections.Generic; using System.Globalization; using System.ComponentModel; using System.Threading; using System.Collections.Specialized; #endregion ///////////////////////////////////////////////////////////////////// // <summary>contains support classes to work with // the resumable upload protocol. // </summary> //////////////////////////////////////////////////////////////////// namespace Google.GData.Client.ResumableUpload { internal class AsyncResumableUploadData : AsyncData { private Authenticator authenticator; private string contentType; private AbstractEntry entry; private string slug; public AsyncResumableUploadData(AsyncDataHandler handler, Authenticator authenticator, Uri uriToUse, Stream payload, string contentType, string slug, string httpMethod, SendOrPostCallback callback, object userData) : base(uriToUse, null, userData, callback) { this.DataHandler = handler; this.authenticator = authenticator; this.contentType = contentType; this.DataStream = payload; this.slug = slug; this.HttpVerb = httpMethod; } public AsyncResumableUploadData(AsyncDataHandler handler, Authenticator authenticator, AbstractEntry payload, string httpMethod, SendOrPostCallback callback, object userData) : base(null, null, userData, callback) { this.DataHandler = handler; this.authenticator = authenticator; this.entry = payload; this.HttpVerb = httpMethod; } public string ContentType { get { return this.contentType; } } public Authenticator Authentication { get { return this.authenticator; } } public AbstractEntry Entry { get { return this.entry; } } public string Slug { get { return this.slug; } } } /// <summary> /// this class handles the Resumable Upload protocol /// </summary> public class ResumableUploader : AsyncDataHandler { // chunksize in Megabytes private int chunkSize; private long lastChunk = 0; // the index of the last chunk uploaded private static long MB = 1024000; /// <summary> /// The relationship value to be used to find the resumable /// </summary> public static string CreateMediaRelation = "http://schemas.google.com/g/2005#resumable-create-media"; public static string EditMediaRelation = "http://schemas.google.com/g/2005#resumable-edit-media"; private delegate void WorkerResumableUploadHandler(AsyncResumableUploadData data, AsyncOperation asyncOp, SendOrPostCallback completionMethodDelegate); /// <summary> /// Default constructor. Uses the default chunksize of 25 megabyte /// </summary> /// <returns></returns> public ResumableUploader() : this(25) { } /// <summary> /// ResumableUploader constructor. /// </summary> /// <param name="chunkSize">the upload chunksize in Megabytes, needs to be greater than 0</param> /// <returns></returns> public ResumableUploader(int chunkSize) { if (chunkSize < 1) throw new ArgumentException("chunkSize needs to be > 0"); this.chunkSize = chunkSize; } /// <summary> /// returns the resumable edit media Uri for a given entry /// </summary> /// <param name="entry"></param> /// <returns></returns> public static Uri GetResumableEditUri(AtomLinkCollection links) { // scan the link collection AtomLink link = links.FindService(EditMediaRelation, null); return link == null ? null : new Uri(link.AbsoluteUri); } /// <summary> /// returns the resumabled create media Uri for a given entry /// </summary> /// <param name="entry"></param> /// <returns></returns> public static Uri GetResumableCreateUri(AtomLinkCollection links) { // scan the link collection AtomLink link = links.FindService(CreateMediaRelation, null); return link == null ? null : new Uri(link.AbsoluteUri); } /// <summary> /// Uploads an entry, including it's media to the uri given inside the entry. /// </summary> /// <param name="authentication">The authentication information to be used</param> /// <param name="payload">The entry to be uploaded. This is a complete entry, including the metadata. /// This will create a new entry on the service</param> /// <returns></returns> public WebResponse Insert(Authenticator authentication, AbstractEntry payload) { return Insert(authentication, payload, null); } /// <summary> /// Uploads just the media media to the uri given. /// </summary> /// <param name="resumableUploadUri"></param> /// <param name="authentication">The authentication information to be used</param> /// <param name="payload">The media to uploaded.</param> /// <param name="contentType">The type of the content, e.g. text/html</param> /// <returns></returns> public WebResponse Insert(Authenticator authentication, Uri resumableUploadUri, Stream payload, string contentType, string slug) { return Insert(authentication, resumableUploadUri, payload, contentType, slug, null); } private WebResponse Insert(Authenticator authentication, AbstractEntry payload, AsyncData data) { WebResponse r = null; Uri initialUri = ResumableUploader.GetResumableCreateUri(payload.Links); if (initialUri == null) throw new ArgumentException("payload did not contain a resumabled create media Uri"); Uri resumeUri = InitiateUpload(initialUri, authentication, payload); using (Stream s = payload.MediaSource.GetDataStream()) { r = UploadStream(HttpMethods.Post, resumeUri, authentication, s, payload.MediaSource.ContentType, data); } return r; } private WebResponse Insert(Authenticator authentication, Uri resumableUploadUri, Stream payload, string contentType, string slug, AsyncData data) { Uri resumeUri = InitiateUpload(resumableUploadUri, authentication, contentType, null, GetStreamLength(payload)); return UploadStream(HttpMethods.Post, resumeUri, authentication, payload, contentType, data); } public void InsertAsync(Authenticator authentication, Uri resumableUploadUri, Stream payload, string contentType, string slug, object userData) { AsyncResumableUploadData data = new AsyncResumableUploadData(this, authentication, resumableUploadUri, payload, contentType, slug, HttpMethods.Post, this.ProgressReportDelegate, userData); WorkerResumableUploadHandler workerDelegate = new WorkerResumableUploadHandler(AsyncInsertWorker); this.AsyncStarter(data, workerDelegate, userData); } public void InsertAsync(Authenticator authentication, AbstractEntry payload, object userData) { AsyncResumableUploadData data = new AsyncResumableUploadData(this, authentication, payload, HttpMethods.Post, this.ProgressReportDelegate, userData); WorkerResumableUploadHandler workerDelegate = new WorkerResumableUploadHandler(AsyncInsertWorker); this.AsyncStarter(data, workerDelegate, userData); } /// <summary> /// askes the server about the current status /// </summary> /// <param name="authentication"></param> /// <param name="targetUri"></param> /// <returns></returns> public static long QueryStatus(Authenticator authentication, Uri targetUri) { HttpWebRequest request = authentication.CreateHttpWebRequest(HttpMethods.Post, targetUri); long result = -1; // add a range header string contentRange = String.Format("bytes */*"); request.Headers.Add(HttpRequestHeader.ContentRange, contentRange); request.ContentLength = 0; HttpWebResponse response = request.GetResponse() as HttpWebResponse; // now parse the header string range = response.Headers["Range"]; string []parts = range.Split('-'); if (parts.Length > 1 && parts[1] != null) { result = long.Parse(parts[1]); } return result; } /// <summary> /// worker method for the the resumable insert /// </summary> /// <param name="data"></param> /// <param name="asyncOp"></param> /// <param name="completionMethodDelegate"></param> /// <returns></returns> private void AsyncInsertWorker(AsyncResumableUploadData data, AsyncOperation asyncOp, SendOrPostCallback completionMethodDelegate) { try { if (data.Entry != null) { using (var response = Insert(data.Authentication, data.Entry, data)) { HandleResponseStream(data, response.GetResponseStream(), -1); } } else { using (var response = Insert(data.Authentication, data.UriToUse, data.DataStream, data.ContentType, data.Slug, data)) { HandleResponseStream(data, response.GetResponseStream(), -1); } } } catch (Exception e) { data.Exception = e; } this.CompletionMethodDelegate(data); } /// <summary> /// Uploads an entry, including it's media to the uri given inside the entry /// </summary> /// <param name="resumableUploadUri"></param> /// <param name="authentication">The authentication information to be used</param> /// <param name="payload">The entry to be uploaded. This is a complete entry, including the metadata. /// This will create a new entry on the service</param> /// <returns></returns> public WebResponse Update(Authenticator authentication, AbstractEntry payload) { return Update(authentication, payload, null); } /// <summary> /// Uploads just the media media to the uri given. /// </summary> /// <param name="resumableUploadUri"></param> /// <param name="authentication">The authentication information to be used</param> /// <param name="payload">The media to uploaded.</param> /// <param name="contentType">The type of the content, e.g. text/html</param> /// <returns></returns> public WebResponse Update(Authenticator authentication, Uri resumableUploadUri, Stream payload, string contentType) { return Update(authentication, resumableUploadUri, payload, contentType, null); } private WebResponse Update(Authenticator authentication, AbstractEntry payload, AsyncData data) { WebResponse r = null; Uri initialUri = ResumableUploader.GetResumableEditUri(payload.Links); if (initialUri == null) throw new ArgumentException("payload did not contain a resumabled edit media Uri"); Uri resumeUri = InitiateUpload(initialUri, authentication, payload); // get the stream using (Stream s = payload.MediaSource.GetDataStream()) { r = UploadStream(HttpMethods.Put, resumeUri, authentication, s, payload.MediaSource.ContentType, data); } return r; } private WebResponse Update(Authenticator authentication, Uri resumableUploadUri, Stream payload, string contentType, AsyncData data) { Uri resumeUri = InitiateUpload(resumableUploadUri, authentication, contentType, null, GetStreamLength(payload)); return UploadStream(HttpMethods.Put, resumeUri, authentication, payload, contentType, data); } public void UpdateAsync(Authenticator authentication, Uri resumableUploadUri, Stream payload, string contentType, object userData) { AsyncResumableUploadData data = new AsyncResumableUploadData(this, authentication, resumableUploadUri, payload, contentType, null, HttpMethods.Put, this.ProgressReportDelegate, userData); WorkerResumableUploadHandler workerDelegate = new WorkerResumableUploadHandler(AsyncUpdateWorker); this.AsyncStarter(data, workerDelegate, userData); } public void UpdateAsync(Authenticator authentication, AbstractEntry payload, object userData) { AsyncResumableUploadData data = new AsyncResumableUploadData(this, authentication, payload, HttpMethods.Put, this.ProgressReportDelegate, userData); WorkerResumableUploadHandler workerDelegate = new WorkerResumableUploadHandler(AsyncUpdateWorker); this.AsyncStarter(data, workerDelegate, userData); } public WebResponse Resume(Authenticator authentication, Uri resumeUri, String httpMethod, Stream payload, string contentType) { return Resume(authentication, resumeUri, httpMethod, payload, contentType, null); } public void ResumeAsync(Authenticator authentication, Uri resumeUri, String httpmethod, Stream payload, string contentType, object userData) { AsyncResumableUploadData data = new AsyncResumableUploadData(this, authentication, resumeUri, payload, contentType, null, httpmethod, this.ProgressReportDelegate, userData); WorkerResumableUploadHandler workerDelegate = new WorkerResumableUploadHandler(AsyncResumeWorker); this.AsyncStarter(data, workerDelegate, userData); } private WebResponse Resume(Authenticator authentication, Uri resumeUri, String httpmethod, Stream payload, string contentType, AsyncData data) { return UploadStream(httpmethod, resumeUri, authentication, payload, contentType, data); } /// <summary> /// worker method for the resume /// </summary> /// <param name="data"></param> /// <param name="asyncOp"></param> /// <param name="completionMethodDelegate"></param> /// <returns></returns> private void AsyncResumeWorker(AsyncResumableUploadData data, AsyncOperation asyncOp, SendOrPostCallback completionMethodDelegate) { try { using (var response = Resume(data.Authentication, data.UriToUse, data.HttpVerb, data.DataStream, data.ContentType, data)) { HandleResponseStream(data, response.GetResponseStream(), -1); } } catch (Exception e) { data.Exception = e; } this.CompletionMethodDelegate(data); } /// <summary> /// worker method for the resumable update /// </summary> /// <param name="data"></param> /// <param name="asyncOp"></param> /// <param name="completionMethodDelegate"></param> /// <returns></returns> private void AsyncUpdateWorker(AsyncResumableUploadData data, AsyncOperation asyncOp, SendOrPostCallback completionMethodDelegate) { try { if (data.Entry != null) { using (var response = Update(data.Authentication, data.Entry, data)) { HandleResponseStream(data, response.GetResponseStream(), -1); } } else { using (var response = Update(data.Authentication, data.UriToUse, data.DataStream, data.ContentType, data)) { HandleResponseStream(data, response.GetResponseStream(), -1); } } } catch (Exception e) { data.Exception = e; } this.CompletionMethodDelegate(data); } /// <summary> /// Note the URI passed in here, is the session URI obtained by InitiateUpload /// </summary> /// <param name="targetUri"></param> /// <param name="authentication"></param> /// <param name="payload"></param> /// <param name="mediaType"></param> public WebResponse UploadStream(string httpMethod, Uri sessionUri, Authenticator authentication, Stream payload, string mediaType, AsyncData data) { HttpWebResponse returnResponse = null; // upload one part at a time int index = 0; bool isDone = false; // if the passed in stream is NOT at the beginning, we assume // that we are resuming try { // calculate a new index, we will resume in chunk sizes if (payload.Position != 0) { index = (int)((double)payload.Position / (this.chunkSize * ResumableUploader.MB)); } } catch (System.NotSupportedException e) { index = 0; } do { HttpWebResponse response; try { response = UploadStreamPart(index, httpMethod, sessionUri, authentication, payload, mediaType, data); if (data != null && CheckIfOperationIsCancelled(data.UserData) == true) { break; } index++; { int status = (int)response.StatusCode; switch (status) { case 308: isDone = false; break; case 200: case 201: isDone = true; returnResponse = response; break; default: throw new ApplicationException("Unexpected return code during resumable upload"); } } } finally { response = null; } } while (isDone == false); return returnResponse; } private HttpWebResponse UploadStreamPart(int partIndex, string httpMethod, Uri sessionUri, Authenticator authentication, Stream payload, string mediaType, AsyncData data) { HttpWebRequest request = authentication.CreateHttpWebRequest(httpMethod, sessionUri); request.AllowWriteStreamBuffering = false; request.Timeout = 600000; // write the data request.ContentType = mediaType; CopyData(payload, request, partIndex, data); HttpWebResponse response = request.GetResponse() as HttpWebResponse; return response; } private long GetStreamLength(Stream s) { long result; try { result = s.Length; } catch (NotSupportedException e) { result = -1; } return result; } ////////////////////////////////////////////////////////////////////// /// <summary>takes our copy of the stream, and puts it into the request stream /// returns FALSE when we are done by reaching the end of the input stream</summary> ////////////////////////////////////////////////////////////////////// protected bool CopyData(Stream input, HttpWebRequest request, int partIndex, AsyncData data) { long chunkCounter = 0; long chunkStart = lastChunk; long chunkSizeMb = this.chunkSize * ResumableUploader.MB; long dataLength; dataLength = GetStreamLength(input); // calculate the range // move the source stream to the correct position input.Seek(chunkStart, SeekOrigin.Begin); // to reduce memory consumption, we read in 256K chunks const int size = 262144; byte[] bytes = new byte[size]; int numBytes; // first calculate the contentlength. We can not modify // headers AFTER we started writing to the stream // Note: we want to read in chunksize*MB, but it might be less // if we have smaller files or are at the last chunk while ((numBytes = input.Read(bytes, 0, size)) > 0) { chunkCounter += numBytes; if (chunkCounter >= chunkSizeMb) break; } request.ContentLength = chunkCounter; long chunkEnd = chunkStart + chunkCounter; // modify the content-range header string contentRange = String.Format("bytes {0}-{1}/{2}", chunkStart, chunkEnd - 1, dataLength > 0 ? dataLength.ToString() : "*"); request.Headers.Add(HttpRequestHeader.ContentRange, contentRange); lastChunk = chunkEnd; // save the last start index, need to add 503 error handling to this // stream it into the real request stream using (Stream req = request.GetRequestStream()) { // move the source stream to the correct position input.Seek(chunkStart, SeekOrigin.Begin); chunkCounter = 0; // to reduce memory consumption, we read in 256K chunks while ((numBytes = input.Read(bytes, 0, size)) > 0) { req.Write(bytes, 0, numBytes); chunkCounter += numBytes; // while we are writing along, send notifications out if (data != null) { if (CheckIfOperationIsCancelled(data.UserData) == true) { break; } else if (data.Delegate != null && data.DataHandler != null) { AsyncOperationProgressEventArgs args; long position = chunkStart + chunkCounter - 1; int percentage = (int)((double)position / dataLength * 100); args = new AsyncOperationProgressEventArgs(dataLength, position, percentage, request.RequestUri, request.Method, data.UserData); data.DataHandler.SendProgressData(data, args); } } if (chunkCounter >= request.ContentLength) break; } } return chunkCounter < chunkSizeMb; } ///////////////////////////////////////////////////////////////////////////// /// <summary> /// retrieves the resumable URI for the rest of the operation. This will initiate the /// communication with resumable upload server by posting against the starting URI /// </summary> /// <param name="resumableUploadUri"></param> /// <param name="authentication"></param> /// <param name="entry"></param> /// <returns>The uri to be used for the rest of the operation</returns> public Uri InitiateUpload(Uri resumableUploadUri, Authenticator authentication, string contentType, string slug, long contentLength) { HttpWebRequest request = PrepareRequest(resumableUploadUri, authentication, slug, contentType, contentLength); WebResponse response = request.GetResponse(); return new Uri(response.Headers["Location"]); } /// <summary> /// retrieves the resumable URI for the rest of the operation. This will initiate the /// communication with resumable upload server by posting against the starting URI /// </summary> /// <param name="resumableUploadUri"></param> /// <param name="authentication"></param> /// <param name="entry"></param> /// <returns>The uri to be used for the rest of the operation</returns> public Uri InitiateUpload(Uri resumableUploadUri, Authenticator authentication, AbstractEntry entry) { HttpWebRequest request = PrepareRequest(resumableUploadUri, authentication, entry.MediaSource.Name, entry.MediaSource.ContentType, entry.MediaSource.ContentLength); IVersionAware v = entry as IVersionAware; if (v != null) { // need to add the version header to the request request.Headers.Add(GDataGAuthRequestFactory.GDataVersion, v.ProtocolMajor.ToString() + "." + v.ProtocolMinor.ToString()); } ISupportsEtag e = entry as ISupportsEtag; if (e != null && Utilities.IsWeakETag(e) == false) { request.Headers.Add(GDataRequestFactory.IfMatch, e.Etag); } Stream outputStream = request.GetRequestStream(); entry.SaveToXml(outputStream); outputStream.Close(); /// this is the contenttype for the xml post request.ContentType = GDataRequestFactory.DefaultContentType; WebResponse response = request.GetResponse(); return new Uri(response.Headers["Location"]); } private HttpWebRequest PrepareRequest(Uri target, Authenticator authentication, string slug, string contentType, long contentLength) { HttpWebRequest request = authentication.CreateHttpWebRequest(HttpMethods.Post, target); request.Headers.Add(GDataRequestFactory.SlugHeader + ": " + slug); request.Headers.Add(GDataRequestFactory.ContentOverrideHeader + ": " + contentType); if (contentLength != -1) { request.Headers.Add(GDataRequestFactory.ContentLengthOverrideHeader + ": " + contentLength); } return request; } /// <summary> /// starts the async job /// </summary> /// <param name="data"></param> /// <param name="userData"></param> /// <param name="workerDelegate"></param> /// <returns></returns> private void AsyncStarter(AsyncResumableUploadData data, WorkerResumableUploadHandler workerDelegate, Object userData) { AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(userData); data.Operation = asyncOp; AddUserDataToDictionary(userData, asyncOp); // Start the asynchronous operation. workerDelegate.BeginInvoke( data, asyncOp, this.CompletionMethodDelegate, null, null); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.Network.Fluent.Models; namespace Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update { using Microsoft.Azure.Management.Network.Fluent.NetworkSecurityGroup.Update; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResourceActions; /// <summary> /// The stage of the network rule description allowing the destination address to be specified. /// Note: network security rule must specify a non empty value for exactly one of: /// DestinationAddressPrefixes, DestinationAddressPrefix, DestinationApplicationSecurityGroups. /// </summary> public interface IWithDestinationAddressOrSecurityGroup { /// <summary> /// Specifies the traffic destination address range to which this rule applies. /// </summary> /// <param name="cidr">An IP address range expressed in the CIDR notation.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate ToAddress(string cidr); /// <summary> /// Specifies the traffic destination address prefixes to which this rule applies. /// </summary> /// <param name="addresses">IP address prefixes in CIDR notation or IP addresses.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate ToAddresses(params string[] addresses); /// <summary> /// Makes the rule apply to any traffic destination address. /// </summary> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate ToAnyAddress(); /// <summary> /// Sets the application security group specified as destination. /// </summary> /// <param name="id">Application security group id.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate WithDestinationApplicationSecurityGroup(string id); } /// <summary> /// The stage of the network rule description allowing the destination port(s) to be specified. /// </summary> public interface IWithDestinationPort { /// <summary> /// Makes this rule apply to any destination port. /// </summary> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate ToAnyPort(); /// <summary> /// Specifies the destination port to which this rule applies. /// </summary> /// <param name="port">The destination port number.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate ToPort(int port); /// <summary> /// Specifies the destination port range to which this rule applies. /// </summary> /// <param name="from">The starting port number.</param> /// <param name="to">The ending port number.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate ToPortRange(int from, int to); /// <summary> /// Specifies the destination port ranges to which this rule applies. /// </summary> /// <param name="ranges">The destination port ranges.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate ToPortRanges(params string[] ranges); } /// <summary> /// The stage of the network rule description allowing the direction and the access type to be specified. /// </summary> public interface IWithDirectionAccess { /// <summary> /// Allows inbound traffic. /// </summary> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate AllowInbound(); /// <summary> /// Allows outbound traffic. /// </summary> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate AllowOutbound(); /// <summary> /// Blocks inbound traffic. /// </summary> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate DenyInbound(); /// <summary> /// Blocks outbound traffic. /// </summary> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate DenyOutbound(); } /// <summary> /// The stage of the security rule description allowing the protocol that the rule applies to to be specified. /// </summary> public interface IWithProtocol { /// <summary> /// Makes this rule apply to any supported protocol. /// </summary> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate WithAnyProtocol(); /// <summary> /// Specifies the protocol that this rule applies to. /// </summary> /// <param name="protocol">One of the supported protocols.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate WithProtocol(SecurityRuleProtocol protocol); } /// <summary> /// The stage of the network rule description allowing the source port(s) to be specified. /// </summary> public interface IWithSourcePort { /// <summary> /// Makes this rule apply to any source port. /// </summary> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate FromAnyPort(); /// <summary> /// Specifies the source port to which this rule applies. /// </summary> /// <param name="port">The source port number.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate FromPort(int port); /// <summary> /// Specifies the source port range to which this rule applies. /// </summary> /// <param name="from">The starting port number.</param> /// <param name="to">The ending port number.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate FromPortRange(int from, int to); /// <summary> /// Specifies the source port ranges to which this rule applies. /// </summary> /// <param name="ranges">The starting port ranges.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate FromPortRanges(params string[] ranges); } /// <summary> /// The stage of the network rule description allowing the source address to be specified. /// Note: network security rule must specify a non empty value for exactly one of: /// SourceAddressPrefixes, SourceAddressPrefix, SourceApplicationSecurityGroups. /// </summary> public interface IWithSourceAddressOrSecurityGroup { /// <summary> /// Specifies the traffic source address prefix to which this rule applies. /// </summary> /// <param name="cidr">An IP address prefix expressed in the CIDR notation.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate FromAddress(string cidr); /// <summary> /// Specifies the traffic source address prefixes to which this rule applies. /// </summary> /// <param name="addresses">IP address prefixes in CIDR notation or IP addresses.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate FromAddresses(params string[] addresses); /// <summary> /// Specifies that the rule applies to any traffic source address. /// </summary> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate FromAnyAddress(); /// <summary> /// Sets the application security group specified as source. /// </summary> /// <param name="id">Application security group id.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate WithSourceApplicationSecurityGroup(string id); } /// <summary> /// The entirety of a security rule update as part of a network security group update. /// </summary> public interface IUpdate : Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IWithDirectionAccess, Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IWithSourceAddressOrSecurityGroup, Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IWithSourcePort, Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IWithDestinationAddressOrSecurityGroup, Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IWithDestinationPort, Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IWithProtocol, Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResourceActions.ISettable<Microsoft.Azure.Management.Network.Fluent.NetworkSecurityGroup.Update.IUpdate> { /// <summary> /// Specifies a description for this security rule. /// </summary> /// <param name="description">A text description to associate with this security rule.</param> /// <return>The next stage.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate WithDescription(string description); /// <summary> /// Specifies the priority to assign to this security rule. /// Security rules are applied in the order of their assigned priority. /// </summary> /// <param name="priority">The priority number in the range 100 to 4096.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Network.Fluent.NetworkSecurityRule.Update.IUpdate WithPriority(int priority); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsHttp { using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for HttpSuccess. /// </summary> public static partial class HttpSuccessExtensions { /// <summary> /// Return 200 status code if successful /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void Head200(this IHttpSuccess operations) { operations.Head200Async().GetAwaiter().GetResult(); } /// <summary> /// Return 200 status code if successful /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Head200Async(this IHttpSuccess operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.Head200WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get 200 success /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static bool? Get200(this IHttpSuccess operations) { return operations.Get200Async().GetAwaiter().GetResult(); } /// <summary> /// Get 200 success /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<bool?> Get200Async(this IHttpSuccess operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get200WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put boolean value true returning 200 success /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Put200(this IHttpSuccess operations, bool? booleanValue = default(bool?)) { operations.Put200Async(booleanValue).GetAwaiter().GetResult(); } /// <summary> /// Put boolean value true returning 200 success /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Put200Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Put200WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Patch true Boolean value in request returning 200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Patch200(this IHttpSuccess operations, bool? booleanValue = default(bool?)) { operations.Patch200Async(booleanValue).GetAwaiter().GetResult(); } /// <summary> /// Patch true Boolean value in request returning 200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Patch200Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Patch200WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Post bollean value true in request that returns a 200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Post200(this IHttpSuccess operations, bool? booleanValue = default(bool?)) { operations.Post200Async(booleanValue).GetAwaiter().GetResult(); } /// <summary> /// Post bollean value true in request that returns a 200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Post200Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Post200WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Delete simple boolean value true returns 200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Delete200(this IHttpSuccess operations, bool? booleanValue = default(bool?)) { operations.Delete200Async(booleanValue).GetAwaiter().GetResult(); } /// <summary> /// Delete simple boolean value true returns 200 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Delete200Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Delete200WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put true Boolean value in request returns 201 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Put201(this IHttpSuccess operations, bool? booleanValue = default(bool?)) { operations.Put201Async(booleanValue).GetAwaiter().GetResult(); } /// <summary> /// Put true Boolean value in request returns 201 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Put201Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Put201WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Post true Boolean value in request returns 201 (Created) /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Post201(this IHttpSuccess operations, bool? booleanValue = default(bool?)) { operations.Post201Async(booleanValue).GetAwaiter().GetResult(); } /// <summary> /// Post true Boolean value in request returns 201 (Created) /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Post201Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Post201WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put true Boolean value in request returns 202 (Accepted) /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Put202(this IHttpSuccess operations, bool? booleanValue = default(bool?)) { operations.Put202Async(booleanValue).GetAwaiter().GetResult(); } /// <summary> /// Put true Boolean value in request returns 202 (Accepted) /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Put202Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Put202WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Patch true Boolean value in request returns 202 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Patch202(this IHttpSuccess operations, bool? booleanValue = default(bool?)) { operations.Patch202Async(booleanValue).GetAwaiter().GetResult(); } /// <summary> /// Patch true Boolean value in request returns 202 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Patch202Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Patch202WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Post true Boolean value in request returns 202 (Accepted) /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Post202(this IHttpSuccess operations, bool? booleanValue = default(bool?)) { operations.Post202Async(booleanValue).GetAwaiter().GetResult(); } /// <summary> /// Post true Boolean value in request returns 202 (Accepted) /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Post202Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Post202WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Delete true Boolean value in request returns 202 (accepted) /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Delete202(this IHttpSuccess operations, bool? booleanValue = default(bool?)) { operations.Delete202Async(booleanValue).GetAwaiter().GetResult(); } /// <summary> /// Delete true Boolean value in request returns 202 (accepted) /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Delete202Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Delete202WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Return 204 status code if successful /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void Head204(this IHttpSuccess operations) { operations.Head204Async().GetAwaiter().GetResult(); } /// <summary> /// Return 204 status code if successful /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Head204Async(this IHttpSuccess operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.Head204WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put true Boolean value in request returns 204 (no content) /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Put204(this IHttpSuccess operations, bool? booleanValue = default(bool?)) { operations.Put204Async(booleanValue).GetAwaiter().GetResult(); } /// <summary> /// Put true Boolean value in request returns 204 (no content) /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Put204Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Put204WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Patch true Boolean value in request returns 204 (no content) /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Patch204(this IHttpSuccess operations, bool? booleanValue = default(bool?)) { operations.Patch204Async(booleanValue).GetAwaiter().GetResult(); } /// <summary> /// Patch true Boolean value in request returns 204 (no content) /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Patch204Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Patch204WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Post true Boolean value in request returns 204 (no content) /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Post204(this IHttpSuccess operations, bool? booleanValue = default(bool?)) { operations.Post204Async(booleanValue).GetAwaiter().GetResult(); } /// <summary> /// Post true Boolean value in request returns 204 (no content) /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Post204Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Post204WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Delete true Boolean value in request returns 204 (no content) /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Delete204(this IHttpSuccess operations, bool? booleanValue = default(bool?)) { operations.Delete204Async(booleanValue).GetAwaiter().GetResult(); } /// <summary> /// Delete true Boolean value in request returns 204 (no content) /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Delete204Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Delete204WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Return 404 status code /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void Head404(this IHttpSuccess operations) { operations.Head404Async().GetAwaiter().GetResult(); } /// <summary> /// Return 404 status code /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Head404Async(this IHttpSuccess operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.Head404WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using DotSpatial.Symbology; namespace DotSpatial.Data.Forms { /// <summary> /// DirectoryItems can be either Files or Folders. /// </summary> public class DirectoryItem { #region Fields private Rectangle _box; private Timer _highlightTimer; private bool _isHighlighted; private ItemType _itemType; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="DirectoryItem"/> class. /// </summary> public DirectoryItem() { Configure(null); } /// <summary> /// Initializes a new instance of the <see cref="DirectoryItem"/> class based on the specified path. /// </summary> /// <param name="path">Path of the directoryItem.</param> public DirectoryItem(string path) { Configure(path); } #endregion #region Properties /// <summary> /// Gets or sets the background color for this item. /// </summary> public Color BackColor { get; set; } /// <summary> /// Gets or sets the bounds rectangle. /// </summary> public Rectangle Bounds { get { return _box; } set { _box = value; } } /// <summary> /// Gets a rectangle in control coordinates showing the size of this control /// </summary> public Rectangle ClientRectangle => new Rectangle(0, 0, Width, Height); /// <summary> /// Gets or sets the custom icon that is used if the ItemType is set to custom /// </summary> public Image CustomImage { get; set; } /// <summary> /// Gets or sets the font for this directory item. /// </summary> public Font Font { get; set; } /// <summary> /// Gets or sets the color that should be used for drawing the fonts. /// </summary> public Color FontColor { get; set; } /// <summary> /// Gets or sets the height of this control. /// </summary> public int Height { get { return _box.Height; } set { _box.Height = value; } } /// <summary> /// Gets the icon that should be used. /// </summary> public virtual Image Image { get { switch (_itemType) { case ItemType.Custom: return CustomImage; case ItemType.Folder: return DialogImages.FolderOpen; case ItemType.Image: return DialogImages.FileImage; case ItemType.Line: return DialogImages.FileLine; case ItemType.Point: return DialogImages.FilePoint; case ItemType.Polygon: return DialogImages.FilePolygon; case ItemType.Raster: return DialogImages.FileGrid; } return CustomImage; } } /// <summary> /// Gets or sets a value indicating whether this specific item should be drawn highlighted. /// </summary> public bool IsHighlighted { get { return _isHighlighted; } set { if (_isHighlighted != value) { _isHighlighted = value; if (_isHighlighted) _highlightTimer.Start(); } } } /// <summary> /// Gets or sets a value indicating whether or not a black dotted rectangle will surround this item. /// </summary> public bool IsOutlined { get; set; } /// <summary> /// Gets or sets a value indicating whether this specific item should be drawn highlighted. /// </summary> public bool IsSelected { get; set; } /// <summary> /// Gets or sets the ItemType for this particular directory item. /// </summary> public ItemType ItemType { get { return _itemType; } set { _itemType = value; if (_itemType != ItemType.Custom) ShowImage = true; } } /// <summary> /// Gets or sets the complete path for this directory item. /// </summary> public string Path { get; set; } /// <summary> /// Gets or sets a value indicating whether or not an icon should be drawn. /// </summary> public bool ShowImage { get; set; } /// <summary> /// Gets or sets the string text for this directory item. /// </summary> public string Text { get; set; } /// <summary> /// Gets or sets the integer top of this item. /// </summary> public int Top { get { return _box.Y; } set { _box.Y = value; } } /// <summary> /// Gets or sets the width of this control. /// </summary> public int Width { get { return _box.Width; } set { _box.Width = value; } } #endregion #region Methods /// <summary> /// This method instructs this item to draw itself onto the specified graphics surface. /// </summary> /// <param name="e">A PaintEventArgs that contains the Graphics object needed for drawing.</param> public virtual void Draw(PaintEventArgs e) { Matrix oldMatrix = e.Graphics.Transform; Matrix mat = new Matrix(); mat.Translate(Bounds.Left, Bounds.Top); e.Graphics.Transform = mat; OnDraw(e); e.Graphics.Transform = oldMatrix; } /// <summary> /// This supplies the basic drawing for this one element where the graphics object has been transformed /// based on the position of this item. /// </summary> /// <param name="e">A PaintEventArgs that contains the Graphics object needed for drawing.</param> protected virtual void OnDraw(PaintEventArgs e) { int left = 1; Pen border = Pens.White; Pen innerBorder = Pens.White; Brush fill = Brushes.White; Pen dots = new Pen(Color.Black); bool specialDrawing = false; dots.DashStyle = DashStyle.Dot; if (_isHighlighted && !IsSelected) { border = new Pen(Color.FromArgb(216, 240, 250)); innerBorder = new Pen(Color.FromArgb(248, 252, 254)); fill = new LinearGradientBrush(ClientRectangle, Color.FromArgb(245, 250, 253), Color.FromArgb(232, 245, 253), LinearGradientMode.Vertical); specialDrawing = true; } if (IsSelected && !_isHighlighted) { border = new Pen(Color.FromArgb(153, 222, 253)); innerBorder = new Pen(Color.FromArgb(231, 245, 253)); fill = new LinearGradientBrush(ClientRectangle, Color.FromArgb(241, 248, 253), Color.FromArgb(213, 239, 252), LinearGradientMode.Vertical); specialDrawing = true; } if (IsSelected && _isHighlighted) { border = new Pen(Color.FromArgb(182, 230, 251)); innerBorder = new Pen(Color.FromArgb(242, 249, 253)); fill = new LinearGradientBrush(ClientRectangle, Color.FromArgb(232, 246, 253), Color.FromArgb(196, 232, 250), LinearGradientMode.Vertical); specialDrawing = true; } e.Graphics.FillRectangle(fill, new Rectangle(1, 1, Width - 2, Height - 2)); SymbologyGlobal.DrawRoundedRectangle(e.Graphics, innerBorder, new Rectangle(2, 2, Width - 4, Height - 4)); SymbologyGlobal.DrawRoundedRectangle(e.Graphics, border, new Rectangle(1, 1, Width - 2, Height - 2)); if (IsOutlined) { e.Graphics.DrawRectangle(dots, new Rectangle(2, 2, Width - 4, Height - 4)); } if (ShowImage) { if (Height > 20) { e.Graphics.DrawImage(Image, new Rectangle(1, 1, Height - 2, Height - 2)); } else { e.Graphics.DrawImage(Image, new Rectangle(1, 1, Image.Width, Image.Height)); } left = Height + 2; } Brush b = new SolidBrush(FontColor); e.Graphics.DrawString(Text, Font, b, new PointF(left, 1f)); b.Dispose(); if (specialDrawing) { border.Dispose(); innerBorder.Dispose(); fill.Dispose(); dots.Dispose(); } } private void Configure(string path) { Width = 500; Height = 20; BackColor = Color.White; FontColor = Color.Black; _highlightTimer = new Timer { Interval = 10 }; if (path == null) return; Path = path; string[] directoryParts = path.Split(System.IO.Path.DirectorySeparatorChar); Text = directoryParts[directoryParts.GetUpperBound(0)]; } #endregion } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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 NUnit.Framework; using QuantConnect.Brokerages; namespace QuantConnect.Tests.Brokerages { [TestFixture] public class SymbolPropertiesDatabaseSymbolMapperTests { [TestCaseSource(nameof(BrokerageSymbols))] public void ReturnsCryptoSecurityType(string market, string brokerageSymbol, string leanSymbol) { var mapper = new SymbolPropertiesDatabaseSymbolMapper(market); var symbol = mapper.GetLeanSymbol(brokerageSymbol, SecurityType.Crypto, market); Assert.AreEqual(leanSymbol, symbol.Value); Assert.AreEqual(market, symbol.ID.Market); } [TestCaseSource(nameof(BrokerageSymbols))] public void ReturnsCorrectLeanSymbol(string market, string brokerageSymbol, string leanSymbol) { var mapper = new SymbolPropertiesDatabaseSymbolMapper(market); var symbol = mapper.GetLeanSymbol(brokerageSymbol, SecurityType.Crypto, market); Assert.AreEqual(leanSymbol, symbol.Value); Assert.AreEqual(SecurityType.Crypto, symbol.ID.SecurityType); Assert.AreEqual(market, symbol.ID.Market); } [TestCaseSource(nameof(CryptoSymbols))] public void ReturnsCorrectBrokerageSymbol(Symbol symbol, string brokerageSymbol) { var mapper = new SymbolPropertiesDatabaseSymbolMapper(symbol.ID.Market); Assert.AreEqual(brokerageSymbol, mapper.GetBrokerageSymbol(symbol)); } [TestCaseSource(nameof(CurrencyPairs))] public void ThrowsOnCurrencyPairs(string market, string brokerageSymbol) { var mapper = new SymbolPropertiesDatabaseSymbolMapper(market); Assert.Throws<ArgumentException>(() => mapper.GetBrokerageSecurityType(brokerageSymbol)); } [TestCase(Market.GDAX)] [TestCase(Market.Bitfinex)] [TestCase(Market.Binance)] public void ThrowsOnNullOrEmptySymbols(string market) { var mapper = new SymbolPropertiesDatabaseSymbolMapper(market); string ticker = null; Assert.IsFalse(mapper.IsKnownBrokerageSymbol(ticker)); Assert.Throws<ArgumentException>(() => mapper.GetLeanSymbol(ticker, SecurityType.Crypto, market)); Assert.Throws<ArgumentException>(() => mapper.GetBrokerageSecurityType(ticker)); ticker = ""; Assert.IsFalse(mapper.IsKnownBrokerageSymbol(ticker)); Assert.Throws<ArgumentException>(() => mapper.GetLeanSymbol(ticker, SecurityType.Crypto, market)); Assert.Throws<ArgumentException>(() => mapper.GetBrokerageSecurityType(ticker)); Assert.Throws<ArgumentException>(() => mapper.GetBrokerageSymbol(Symbol.Create(ticker, SecurityType.Crypto, market))); } [TestCaseSource(nameof(UnknownSymbols))] public void ThrowsOnUnknownSymbols(string brokerageSymbol, SecurityType type, string market) { var mapper = new SymbolPropertiesDatabaseSymbolMapper(market); Assert.Throws<ArgumentException>(() => mapper.GetLeanSymbol(brokerageSymbol, type, market)); Assert.Throws<ArgumentException>(() => mapper.GetBrokerageSymbol(Symbol.Create(brokerageSymbol.Replace("-", ""), type, market))); } [TestCaseSource(nameof(UnknownSecurityType))] public void ThrowsOnUnknownSecurityType(string brokerageSymbol, SecurityType type, string market) { var mapper = new SymbolPropertiesDatabaseSymbolMapper(market); Assert.Throws<ArgumentException>(() => mapper.GetLeanSymbol(brokerageSymbol, type, market)); Assert.Throws<ArgumentException>(() => mapper.GetBrokerageSymbol(Symbol.Create(brokerageSymbol.Replace("-", ""), type, market))); } [TestCaseSource(nameof(UnknownMarket))] public void ThrowsOnUnknownMarket(string brokerageSymbol, SecurityType type, string market) { var mapper = new SymbolPropertiesDatabaseSymbolMapper(market); Assert.Throws<ArgumentException>(() => mapper.GetLeanSymbol(brokerageSymbol, type, market)); Assert.Throws<ArgumentException>(() => mapper.GetBrokerageSymbol(Symbol.Create(brokerageSymbol.Replace("-", ""), type, market))); } private static TestCaseData[] BrokerageSymbols => new[] { new TestCaseData(Market.GDAX, "ETH-USD", "ETHUSD"), new TestCaseData(Market.GDAX, "ETH-BTC", "ETHBTC"), new TestCaseData(Market.GDAX, "BTC-USD", "BTCUSD"), new TestCaseData(Market.GDAX, "BTC-USDC", "BTCUSDC"), new TestCaseData(Market.GDAX, "ATOM-USD", "ATOMUSD"), new TestCaseData(Market.Bitfinex, "tBTCUSD", "BTCUSD"), new TestCaseData(Market.Bitfinex, "tBTCUST", "BTCUSDT"), new TestCaseData(Market.Bitfinex, "tETHUSD", "ETHUSD"), new TestCaseData(Market.Bitfinex, "tADAUST", "ADAUSDT"), new TestCaseData(Market.Bitfinex, "tCOMP:USD", "COMPUSD"), new TestCaseData(Market.Bitfinex, "tCOMP:UST", "COMPUSDT"), new TestCaseData(Market.Binance, "ETHUSDT", "ETHUSDT"), new TestCaseData(Market.Binance, "ETHBTC", "ETHBTC"), new TestCaseData(Market.Binance, "BTCUSDT", "BTCUSDT"), new TestCaseData(Market.Binance, "ATOMTUSD", "ATOMTUSD"), new TestCaseData(Market.Binance, "ATOMUSDC", "ATOMUSDC"), new TestCaseData(Market.Binance, "ATOMUSDT", "ATOMUSDT") }; private static TestCaseData[] CryptoSymbols => new[] { new TestCaseData(Symbol.Create("ETHUSD", SecurityType.Crypto, Market.GDAX), "ETH-USD"), new TestCaseData(Symbol.Create("BTCUSD", SecurityType.Crypto, Market.GDAX), "BTC-USD"), new TestCaseData(Symbol.Create("ETHBTC", SecurityType.Crypto, Market.GDAX), "ETH-BTC"), new TestCaseData(Symbol.Create("BTCUSDC", SecurityType.Crypto, Market.GDAX), "BTC-USDC"), new TestCaseData(Symbol.Create("ATOMUSD", SecurityType.Crypto, Market.GDAX), "ATOM-USD"), new TestCaseData(Symbol.Create("BTCUSD", SecurityType.Crypto, Market.Bitfinex), "tBTCUSD"), new TestCaseData(Symbol.Create("BTCUSDT", SecurityType.Crypto, Market.Bitfinex), "tBTCUST"), new TestCaseData(Symbol.Create("ETHUSD", SecurityType.Crypto, Market.Bitfinex), "tETHUSD"), new TestCaseData(Symbol.Create("ADAUSDT", SecurityType.Crypto, Market.Bitfinex), "tADAUST"), new TestCaseData(Symbol.Create("COMPUSD", SecurityType.Crypto, Market.Bitfinex), "tCOMP:USD"), new TestCaseData(Symbol.Create("COMPUSDT", SecurityType.Crypto, Market.Bitfinex), "tCOMP:UST"), new TestCaseData(Symbol.Create("ETHUSDT", SecurityType.Crypto, Market.Binance), "ETHUSDT"), new TestCaseData(Symbol.Create("ETHBTC", SecurityType.Crypto, Market.Binance), "ETHBTC"), new TestCaseData(Symbol.Create("BTCUSDT", SecurityType.Crypto, Market.Binance), "BTCUSDT"), new TestCaseData(Symbol.Create("ATOMTUSD", SecurityType.Crypto, Market.Binance), "ATOMTUSD"), new TestCaseData(Symbol.Create("ATOMUSDC", SecurityType.Crypto, Market.Binance), "ATOMUSDC"), new TestCaseData(Symbol.Create("ATOMUSDT", SecurityType.Crypto, Market.Binance), "ATOMUSDT") }; private static TestCaseData[] CurrencyPairs => new[] { new TestCaseData(Market.GDAX, ""), new TestCaseData(Market.GDAX, "EURUSD"), new TestCaseData(Market.GDAX, "GBP-USD"), new TestCaseData(Market.GDAX, "USD-JPY"), new TestCaseData(Market.Bitfinex, ""), new TestCaseData(Market.Bitfinex, "EURUSD"), new TestCaseData(Market.Bitfinex, "GBP-USD"), new TestCaseData(Market.Bitfinex, "USD-JPY"), new TestCaseData(Market.Binance, ""), new TestCaseData(Market.Binance, "EURUSD"), new TestCaseData(Market.Binance, "GBPUSD"), new TestCaseData(Market.Binance, "USDJPY") }; private static TestCaseData[] UnknownSymbols => new[] { new TestCaseData("AAA-BBB", SecurityType.Crypto, Market.GDAX), new TestCaseData("USD-BTC", SecurityType.Crypto, Market.GDAX), new TestCaseData("EUR-USD", SecurityType.Crypto, Market.GDAX), new TestCaseData("GBP-USD", SecurityType.Crypto, Market.GDAX), new TestCaseData("USD-JPY", SecurityType.Crypto, Market.GDAX), new TestCaseData("BTC-ETH", SecurityType.Crypto, Market.GDAX), new TestCaseData("USDC-BTC", SecurityType.Crypto, Market.GDAX), new TestCaseData("USD-BTC", SecurityType.Crypto, Market.Bitfinex), new TestCaseData("EUR-USD", SecurityType.Crypto, Market.Bitfinex), new TestCaseData("GBP-USD", SecurityType.Crypto, Market.Bitfinex), new TestCaseData("USD-JPY", SecurityType.Crypto, Market.Bitfinex), new TestCaseData("BTC-ETH", SecurityType.Crypto, Market.Bitfinex), new TestCaseData("USDC-BTC", SecurityType.Crypto, Market.Bitfinex), new TestCaseData("AAABBB", SecurityType.Crypto, Market.Binance), new TestCaseData("USDBTC", SecurityType.Crypto, Market.Binance), new TestCaseData("EURUSD", SecurityType.Crypto, Market.Binance), new TestCaseData("GBPUSD", SecurityType.Crypto, Market.Binance), new TestCaseData("USDJPY", SecurityType.Crypto, Market.Binance), new TestCaseData("BTCETH", SecurityType.Crypto, Market.Binance), new TestCaseData("BTCUSD", SecurityType.Crypto, Market.Binance) }; private static TestCaseData[] UnknownSecurityType => new[] { new TestCaseData("BTC-USD", SecurityType.Forex, Market.GDAX) }; private static TestCaseData[] UnknownMarket => new[] { new TestCaseData("ETH-USD", SecurityType.Crypto, Market.USA) }; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Orleans; using Orleans.GrainDirectory; using Orleans.Runtime; using TestGrainInterfaces; using Orleans.Runtime.Configuration; using Xunit; using Xunit.Abstractions; using Tester; // ReSharper disable InconsistentNaming namespace Tests.GeoClusterTests { // We need use ClientWrapper to load a client object in a new app domain. // This allows us to create multiple clients that are connected to different silos. [TestCategory("GeoCluster")] public class GlobalSingleInstanceClusterTests : TestingClusterHost { public GlobalSingleInstanceClusterTests(ITestOutputHelper output) : base(output) { } /// <summary> /// Run all tests on a small configuration (two clusters, one silo each, one client each) /// </summary> /// <returns></returns> [SkippableFact, TestCategory("Functional")] public async Task All_Small() { await Setup_Clusters(false); numGrains = 600; await RunWithTimeout("IndependentCreation", 5000, IndependentCreation); await RunWithTimeout("CreationRace", 10000, CreationRace); await RunWithTimeout("ConflictResolution", 40000, ConflictResolution); } /// <summary> /// Run all tests on a larger configuration (two clusters with 3 or 4 silos, respectively, and two clients each) /// </summary> /// <returns></returns> [SkippableFact] public async Task All_Large() { await Setup_Clusters(true); numGrains = 2000; await RunWithTimeout("IndependentCreation", 20000, IndependentCreation); await RunWithTimeout("CreationRace", 60000, CreationRace); await RunWithTimeout("ConflictResolution", 120000, ConflictResolution); } #region client wrappers public class ClientWrapper : ClientWrapperBase { public static readonly Func<string, int, string, Action<ClientConfiguration>, Action<IClientBuilder>, ClientWrapper> Factory = (name, gwPort, clusterId, configUpdater, clientConfgirator) => new ClientWrapper(name, gwPort, clusterId, configUpdater, clientConfgirator); public ClientWrapper(string name, int gatewayport, string clusterId, Action<ClientConfiguration> customizer, Action<IClientBuilder> clientConfigurator) : base(name, gatewayport, clusterId, customizer, clientConfigurator) { this.systemManagement = this.GrainFactory.GetGrain<IManagementGrain>(0); } public int CallGrain(int i) { var grainRef = this.GrainFactory.GetGrain<IClusterTestGrain>(i); Task<int> toWait = grainRef.SayHelloAsync(); toWait.Wait(); return toWait.GetResult(); } public void InjectMultiClusterConf(params string[] args) { systemManagement.InjectMultiClusterConfiguration(args).GetResult(); } IManagementGrain systemManagement; } #endregion private Random random = new Random(); private int numGrains; private string cluster0; private string cluster1; private ClientWrapper[] clients; private async Task Setup_Clusters(bool largesetup) { await RunWithTimeout("Setup_Clusters", largesetup ? 120000 : 60000, async () => { // use a random global service id for testing purposes var globalserviceid = Guid.NewGuid(); Action<ClusterConfiguration> configurationcustomizer = (ClusterConfiguration c) => { // run the retry process every 5 seconds to keep this test shorter c.Globals.GlobalSingleInstanceRetryInterval = TimeSpan.FromSeconds(5); }; // Create two clusters, each with a single silo. cluster0 = "cluster0"; cluster1 = "cluster1"; NewGeoCluster(globalserviceid, cluster0, (short)(largesetup ? 3 : 1), configurationcustomizer); NewGeoCluster(globalserviceid, cluster1, (short)(largesetup ? 4 : 1), configurationcustomizer); if (!largesetup) { // Create one client per cluster clients = new ClientWrapper[] { NewClient<ClientWrapper>(cluster0, 0, ClientWrapper.Factory), NewClient<ClientWrapper>(cluster1, 0, ClientWrapper.Factory), }; } else { clients = new ClientWrapper[] { NewClient<ClientWrapper>(cluster0, 0, ClientWrapper.Factory), NewClient<ClientWrapper>(cluster1, 0, ClientWrapper.Factory), NewClient<ClientWrapper>(cluster0, 1, ClientWrapper.Factory), NewClient<ClientWrapper>(cluster1, 1, ClientWrapper.Factory), }; } await WaitForLivenessToStabilizeAsync(); // Configure multicluster clients[0].InjectMultiClusterConf(cluster0, cluster1); await WaitForMultiClusterGossipToStabilizeAsync(false); }); } #region Test creation of independent grains private Task IndependentCreation() { int offset = random.Next(); int base_own0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Owned).Count; int base_own1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Owned).Count; int base_requested0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.RequestedOwnership).Count; int base_requested1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.RequestedOwnership).Count; int base_doubtful0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Doubtful).Count; int base_doubtful1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Doubtful).Count; WriteLog("Counts: Cluster 0 => Owned={0} Requested={1} Doubtful={2}", base_own0, base_requested0, base_doubtful0); WriteLog("Counts: Cluster 1 => Owned={0} Requested={1} Doubtful={2}", base_own1, base_requested1, base_doubtful1); WriteLog("Starting parallel creation of {0} grains", numGrains); // Create grains on both clusters, using clients round-robin. Parallel.For(0, numGrains, paralleloptions, i => { int val = clients[i % clients.Count()].CallGrain(offset + i); Assert.Equal(1, val); }); // We expect all requests to resolve, and all created activations are in state OWNED int own0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Owned).Count; int own1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Owned).Count; int doubtful0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Doubtful).Count; int doubtful1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Doubtful).Count; int requested0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.RequestedOwnership).Count; int requested1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.RequestedOwnership).Count; WriteLog("Counts: Cluster 0 => Owned={0} Requested={1} Doubtful={2}", own0, requested0, doubtful0); WriteLog("Counts: Cluster 1 => Owned={0} Requested={1} Doubtful={2}", own1, requested1, doubtful1); // Assert that all grains are in owned state Assert.Equal(numGrains / 2, own0 - base_own0); Assert.Equal(numGrains / 2, own1 - base_own1); Assert.Equal(doubtful0, base_doubtful0); Assert.Equal(doubtful1, base_doubtful1); Assert.Equal(requested0, base_requested0); Assert.Equal(requested1, base_requested1); return Task.CompletedTask; } #endregion #region Creation Race // This test is for the case where two different clusters are racing, // trying to activate the same grain. // This function takes two arguments, a list of client configurations, and an integer. The list of client configurations is used to // create multiple clients that concurrently call the grains in range [0, numGrains). We run the experiment in a series of barriers. // The clients all invoke grain "g", in parallel, and then wait on a signal by the main thread (this function). The main thread, then // wakes up the clients, after which they invoke "g+1", and so on. private Task CreationRace() { WriteLog("Starting ConcurrentCreation"); var offset = random.Next(); // take inventory now so we can exclude pre-existing entries from the validation var baseline = GetGrainActivations(); // We use two objects to coordinate client threads and the main thread. coordWakeup is an object that is used to signal the coordinator // thread. toWait is used to signal client threads. var coordWakeup = new object(); var toWait = new object(); // We keep a list of client threads. var clientThreads = new List<Tuple<Thread, ClientThreadArgs>>(); var rand = new Random(); var results = new List<Tuple<int, int>>[clients.Length]; threadsDone = results.Length; int index = 0; // Create a client thread corresponding to each client // The client thread will execute ThreadFunc function. foreach (var client in clients) { // A client thread takes a list of tupes<int, int> as argument. The list is an ordered sequence of grains to invoke. tuple.item2 // is the grainId. tuple.item1 is never used (this should probably be cleaned up, but I don't want to break anything :). var args = new List<Tuple<int, int>>(); for (int j = 0; j < numGrains; ++j) { var waitTime = rand.Next(16, 100); args.Add(Tuple.Create(waitTime, j)); } // Given a config file, create client starts a client in a new appdomain. We also create a thread on which the client will run. // The thread takes a "ClientThreadArgs" as argument. var thread = new Thread(ThreadFunc) { IsBackground = true, Name = $"{this.GetType()}.{nameof(CreationRace)}" }; var threadFuncArgs = new ClientThreadArgs { client = client, args = args, resultIndex = index, numThreads = clients.Length, coordWakeup = coordWakeup, toWait = toWait, results = results, offset = offset }; clientThreads.Add(Tuple.Create(thread, threadFuncArgs)); index += 1; } // Go through the list of client threads, and start each of the threads with the appropriate arguments. foreach (var threadNArg in clientThreads) { var thread = threadNArg.Item1; var arg = threadNArg.Item2; thread.Start(arg); } // We run numGrains iterations of the experiment. The coordinator thread calls the function "WaitForWorkers" in order to wait // for the client threads to finish concurrent calls to a single grain. for (int i = 0; i < numGrains; ++i) { WaitForWorkers(clients.Length, coordWakeup, toWait); } // Once the clients threads have finished calling the grain the appropriate number of times, we wait for them to write out their results. foreach (var threadNArg in clientThreads) { var thread = threadNArg.Item1; thread.Join(); } var grains = GetGrainActivations(baseline); ValidateClusterRaceResults(results, grains); return Task.CompletedTask; } private volatile int threadsDone; private void ValidateClusterRaceResults(List<Tuple<int, int>>[] results, Dictionary<GrainId, List<IActivationInfo>> grains) { WriteLog("Validating cluster race results"); // there should be the right number of grains AssertEqual(numGrains, grains.Count, "number of grains in directory does not match"); // each grain should have one activation per cluster foreach (var kvp in grains) { GrainId key = kvp.Key; List<IActivationInfo> activations = kvp.Value; Action error = () => { Assert.True(false, string.Format("grain {0} has wrong activations {1}", key, string.Join(",", activations.Select(x => string.Format("{0}={1}", x.SiloAddress, x.RegistrationStatus))))); }; // each grain has one activation per cluster if (activations.Count != 2) error(); // one should be owned and the other cached switch (activations[0].RegistrationStatus) { case GrainDirectoryEntryStatus.Owned: if (activations[1].RegistrationStatus != GrainDirectoryEntryStatus.Cached) error(); break; case GrainDirectoryEntryStatus.Cached: if (activations[1].RegistrationStatus != GrainDirectoryEntryStatus.Owned) error(); break; default: error(); break; } } // For each of the results that get, ensure that we see a sequence of values. foreach (var list in results) Assert.Equal(numGrains, list.Count); for (int i = 0; i < numGrains; ++i) { var vals = new List<int>(); foreach (var list in results) vals.Add(list[i].Item2); vals.Sort(); for (int x = 0; x < results.Length; x++) AssertEqual(x + 1, vals[x], "expect sequence of results, but got " + string.Join(",", vals)); } } #endregion Creation Race #region Conflict Resolution // This test is used to test the case where two different clusters are racing, // trying to activate the same grain, but inter-cluster communication is blocked // so they both activate an instance // and one of them deactivated once communication is unblocked private async Task ConflictResolution() { int offset = random.Next(); int base_own0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Owned).Count; int base_own1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Owned).Count; int base_requested0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.RequestedOwnership).Count; int base_requested1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.RequestedOwnership).Count; int base_doubtful0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Doubtful).Count; int base_doubtful1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Doubtful).Count; int base_cached0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Cached).Count; int base_cached1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Cached).Count; WriteLog("Counts: Cluster 0 => Owned={0} Requested={1} Doubtful={2} Cached={3}", base_own0, base_requested0, base_doubtful0, base_cached0); WriteLog("Counts: Cluster 1 => Owned={0} Requested={1} Doubtful={2} Cached={3}", base_own1, base_requested1, base_doubtful1, base_cached1); // take inventory now so we can exclude pre-existing entries from the validation var baseline = GetGrainActivations(); // Turn off intercluster messaging to simulate a partition. BlockAllClusterCommunication(cluster0, cluster1); BlockAllClusterCommunication(cluster1, cluster0); WriteLog("Starting creation of {0} grains on isolated clusters", numGrains); Parallel.For(0, numGrains, paralleloptions, i => { int res0, res1, res2, res3; if (i % 2 == 1) { res0 = clients[0].CallGrain(offset + i); res1 = clients[1].CallGrain(offset + i); res2 = clients[2 % clients.Length].CallGrain(offset + i); res3 = clients[3 % clients.Length].CallGrain(offset + i); } else { res0 = clients[1].CallGrain(offset + i); res1 = clients[0].CallGrain(offset + i); res2 = clients[0].CallGrain(offset + i); res3 = clients[1].CallGrain(offset + i); } Assert.Equal(1, res0); Assert.Equal(1, res1); Assert.Equal(2, res2); Assert.Equal(2, res3); }); // Validate that all the created grains are in DOUBTFUL, one activation in each cluster. Assert.True(GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Doubtful).Count == numGrains); Assert.True(GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Doubtful).Count == numGrains); WriteLog("Restoring inter-cluster communication"); // Turn on intercluster messaging and wait for the resolution to kick in. UnblockAllClusterCommunication(cluster0); UnblockAllClusterCommunication(cluster1); // Wait for anti-entropy to kick in. // One of the DOUBTFUL activations must be killed, and the other must be converted to OWNED. await Task.Delay(TimeSpan.FromSeconds(7)); WriteLog("Validation of conflict resolution"); int own0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Owned).Count; int own1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Owned).Count; int doubtful0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Doubtful).Count; int doubtful1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Doubtful).Count; int requested0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.RequestedOwnership).Count; int requested1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.RequestedOwnership).Count; int cached0 = GetGrainsInClusterWithStatus(cluster0, GrainDirectoryEntryStatus.Cached).Count; int cached1 = GetGrainsInClusterWithStatus(cluster1, GrainDirectoryEntryStatus.Cached).Count; WriteLog("Counts: Cluster 0 => Owned={0} Requested={1} Doubtful={2} Cached={3}", own0, requested0, doubtful0, cached0); WriteLog("Counts: Cluster 1 => Owned={0} Requested={1} Doubtful={2} Cached={3}", own1, requested1, doubtful1, cached1); AssertEqual(numGrains + base_own0 + base_own1, own0 + own1, "Expecting All are now Owned"); AssertEqual(numGrains, cached0 + cached1 - base_cached0 - base_cached1, "Expecting All Owned have a cached in the other cluster"); AssertEqual(0, doubtful0 + doubtful1 - base_doubtful0 - base_doubtful1, "Expecting No Doubtful"); Assert.Equal(requested0, base_requested0); Assert.Equal(requested1, base_requested1); // each grain should have one activation per cluster var grains = GetGrainActivations(baseline); foreach (var kvp in grains) { GrainId key = kvp.Key; List<IActivationInfo> activations = kvp.Value; Action error = () => { Assert.True(false, string.Format("grain {0} has wrong activations {1}", key, string.Join(",", activations.Select(x => string.Format("{0}={1}", x.SiloAddress, x.RegistrationStatus))))); }; // each grain has one activation per cluster if (activations.Count != 2) error(); // one should be owned and the other cached switch (activations[0].RegistrationStatus) { case GrainDirectoryEntryStatus.Owned: if (activations[1].RegistrationStatus != GrainDirectoryEntryStatus.Cached) error(); break; case GrainDirectoryEntryStatus.Cached: if (activations[1].RegistrationStatus != GrainDirectoryEntryStatus.Owned) error(); break; default: error(); break; } } // ensure that the grain whose DOUBTFUL activation was killed, // now refers to the 'real' remote OWNED activation. for (int i = 0; i < numGrains; i++) { int res0, res1, res2, res3; if (i % 2 == 1) { res0 = clients[0].CallGrain(offset + i); res1 = clients[1].CallGrain(offset + i); res2 = clients[2 % clients.Length].CallGrain(offset + i); res3 = clients[3 % clients.Length].CallGrain(offset + i); } else { res0 = clients[1].CallGrain(offset + i); res1 = clients[0].CallGrain(offset + i); res2 = clients[0].CallGrain(offset + i); res3 = clients[1].CallGrain(offset + i); } //From the previous grain calls, the last value of the counter in each grain was 2. //So here should be sequenced from 3. Assert.Equal(3, res0); Assert.Equal(4, res1); Assert.Equal(5, res2); Assert.Equal(6, res3); } } #endregion #region Helper methods private List<GrainId> GetGrainsInClusterWithStatus(string clusterId, GrainDirectoryEntryStatus? status = null) { List<GrainId> grains = new List<GrainId>(); var silos = Clusters[clusterId].Cluster.GetActiveSilos(); int totalSoFar = 0; foreach (var silo in silos) { var dir = silo.AppDomainTestHook.GetDirectoryForTypeNamesContaining("ClusterTestGrain"); foreach (var grainKeyValue in dir) { GrainId grainId = grainKeyValue.Key; IGrainInfo grainInfo = grainKeyValue.Value; ActivationId actId = grainInfo.Instances.First().Key; IActivationInfo actInfo = grainInfo.Instances[actId]; if (grainId.IsSystemTarget || grainId.IsClient || !grainId.IsGrain) { // Skip system grains, system targets and clients // which never go through cluster-single-instance registration process continue; } if (!status.HasValue || actInfo.RegistrationStatus == status) { grains.Add(grainId); } } WriteLog("Returning: Silo {0} State = {1} Count = {2}", silo.SiloAddress, status.HasValue ? status.Value.ToString() : "ANY", (grains.Count - totalSoFar)); totalSoFar = grains.Count; } WriteLog("Returning: Cluster {0} State = {1} Count = {2}", clusterId, status.HasValue ? status.Value.ToString() : "ANY", grains.Count); return grains; } private Dictionary<GrainId, List<IActivationInfo>> GetGrainActivations(Dictionary<GrainId, List<IActivationInfo>> exclude = null) { var grains = new Dictionary<GrainId, List<IActivationInfo>>(); int instancecount = 0; foreach (var kvp in Clusters) foreach (var silo in kvp.Value.Silos) { var dir = silo.AppDomainTestHook.GetDirectoryForTypeNamesContaining("ClusterTestGrain"); foreach (var grainKeyValue in dir) { GrainId grainId = grainKeyValue.Key; IGrainInfo grainInfo = grainKeyValue.Value; if (exclude != null && exclude.ContainsKey(grainId)) continue; List<IActivationInfo> acts; if (!grains.TryGetValue(grainId, out acts)) grains[grainId] = acts = new List<IActivationInfo>(); foreach (var instinfo in grainInfo.Instances) { acts.Add(instinfo.Value); instancecount++; } } } WriteLog("Returning: {0} instances for {1} grains", instancecount, grains.Count()); return grains; } // This is a helper function which is used to run the race condition tests. This function waits for all client threads trying to create the // same activation to finish. The last client thread to finish will wakeup the coordinator thread. private void WaitForCoordinator(int numThreads, object coordWakeup, object toWait) { Monitor.Enter(coordWakeup); Monitor.Enter(toWait); threadsDone -= 1; if (threadsDone == 0) { Monitor.Pulse(coordWakeup); } Monitor.Exit(coordWakeup); Monitor.Wait(toWait); Monitor.Exit(toWait); } // This is a helper function which is used to signal the worker client threads to run another iteration of our concurrent experiment. private void WaitForWorkers(int numThreads, object coordWakeup, object toWait) { Monitor.Enter(coordWakeup); while (threadsDone != 0) { Monitor.Wait(coordWakeup); } threadsDone = numThreads; Monitor.Exit(coordWakeup); Monitor.Enter(toWait); Monitor.PulseAll(toWait); Monitor.Exit(toWait); } // ClientThreadArgs is a set of arguments which is used by a client thread which is concurrently running with other client threads. We // use client threads in order to simulate race conditions. private class ClientThreadArgs { public ClientWrapper client; public IEnumerable<Tuple<int, int>> args; public int resultIndex; public int numThreads; public object coordWakeup; public object toWait; public List<Tuple<int, int>>[] results; public int offset; } // Each client thread which is concurrently trying to create a sequence of grains with other clients runs this function. private void ThreadFunc(object obj) { var threadArg = (ClientThreadArgs)obj; var resultList = new List<Tuple<int, int>>(); // Go through the sequence of arguments one by one. foreach (var arg in threadArg.args) { try { // Call the appropriate grain. var grainId = arg.Item2; int ret = threadArg.client.CallGrain(threadArg.offset + grainId); Debug.WriteLine("*** Result = {0}", ret); // Keep the result in resultList. resultList.Add(Tuple.Create(grainId, ret)); } catch (Exception e) { WriteLog("Caught exception: {0}", e); } // Finally, wait for the coordinator to kick-off another round of the test. WaitForCoordinator(threadArg.numThreads, threadArg.coordWakeup, threadArg.toWait); } // Track the results for validation. lock (threadArg.results) { threadArg.results[threadArg.resultIndex] = resultList; } } } #endregion }
// // Author: // Jb Evain ([email protected]) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using SquabPie.Mono.Collections.Generic; namespace SquabPie.Mono.Cecil { public interface IAssemblyResolver { AssemblyDefinition Resolve (AssemblyNameReference name); AssemblyDefinition Resolve (AssemblyNameReference name, ReaderParameters parameters); AssemblyDefinition Resolve (string fullName); AssemblyDefinition Resolve (string fullName, ReaderParameters parameters); } public interface IMetadataResolver { TypeDefinition Resolve (TypeReference type); FieldDefinition Resolve (FieldReference field); MethodDefinition Resolve (MethodReference method); } #if !PCL [Serializable] #endif public class ResolutionException : Exception { readonly MemberReference member; public MemberReference Member { get { return member; } } public IMetadataScope Scope { get { var type = member as TypeReference; if (type != null) return type.Scope; var declaring_type = member.DeclaringType; if (declaring_type != null) return declaring_type.Scope; throw new NotSupportedException (); } } public ResolutionException (MemberReference member) : base ("Failed to resolve " + member.FullName) { if (member == null) throw new ArgumentNullException ("member"); this.member = member; } #if !PCL protected ResolutionException ( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base (info, context) { } #endif } public class MetadataResolver : IMetadataResolver { readonly IAssemblyResolver assembly_resolver; public IAssemblyResolver AssemblyResolver { get { return assembly_resolver; } } public MetadataResolver (IAssemblyResolver assemblyResolver) { if (assemblyResolver == null) throw new ArgumentNullException ("assemblyResolver"); assembly_resolver = assemblyResolver; } public virtual TypeDefinition Resolve (TypeReference type) { if (type == null) throw new ArgumentNullException ("type"); type = type.GetElementType (); var scope = type.Scope; if (scope == null) return null; switch (scope.MetadataScopeType) { case MetadataScopeType.AssemblyNameReference: var assembly = assembly_resolver.Resolve ((AssemblyNameReference) scope); if (assembly == null) return null; return GetType (assembly.MainModule, type); case MetadataScopeType.ModuleDefinition: return GetType ((ModuleDefinition) scope, type); case MetadataScopeType.ModuleReference: var modules = type.Module.Assembly.Modules; var module_ref = (ModuleReference) scope; for (int i = 0; i < modules.Count; i++) { var netmodule = modules [i]; if (netmodule.Name == module_ref.Name) return GetType (netmodule, type); } break; } throw new NotSupportedException (); } static TypeDefinition GetType (ModuleDefinition module, TypeReference reference) { var type = GetTypeDefinition (module, reference); if (type != null) return type; if (!module.HasExportedTypes) return null; var exported_types = module.ExportedTypes; for (int i = 0; i < exported_types.Count; i++) { var exported_type = exported_types [i]; if (exported_type.Name != reference.Name) continue; if (exported_type.Namespace != reference.Namespace) continue; return exported_type.Resolve (); } return null; } static TypeDefinition GetTypeDefinition (ModuleDefinition module, TypeReference type) { if (!type.IsNested) return module.GetType (type.Namespace, type.Name); var declaring_type = type.DeclaringType.Resolve (); if (declaring_type == null) return null; return declaring_type.GetNestedType (type.TypeFullName ()); } public virtual FieldDefinition Resolve (FieldReference field) { if (field == null) throw new ArgumentNullException ("field"); var type = Resolve (field.DeclaringType); if (type == null) return null; if (!type.HasFields) return null; return GetField (type, field); } FieldDefinition GetField (TypeDefinition type, FieldReference reference) { while (type != null) { var field = GetField (type.Fields, reference); if (field != null) return field; if (type.BaseType == null) return null; type = Resolve (type.BaseType); } return null; } static FieldDefinition GetField (Collection<FieldDefinition> fields, FieldReference reference) { for (int i = 0; i < fields.Count; i++) { var field = fields [i]; if (field.Name != reference.Name) continue; if (!AreSame (field.FieldType, reference.FieldType)) continue; return field; } return null; } public virtual MethodDefinition Resolve (MethodReference method) { if (method == null) throw new ArgumentNullException ("method"); var type = Resolve (method.DeclaringType); if (type == null) return null; method = method.GetElementMethod (); if (!type.HasMethods) return null; return GetMethod (type, method); } MethodDefinition GetMethod (TypeDefinition type, MethodReference reference) { while (type != null) { var method = GetMethod (type.Methods, reference); if (method != null) return method; if (type.BaseType == null) return null; type = Resolve (type.BaseType); } return null; } public static MethodDefinition GetMethod (Collection<MethodDefinition> methods, MethodReference reference) { for (int i = 0; i < methods.Count; i++) { var method = methods [i]; if (method.Name != reference.Name) continue; if (method.HasGenericParameters != reference.HasGenericParameters) continue; if (method.HasGenericParameters && method.GenericParameters.Count != reference.GenericParameters.Count) continue; if (!AreSame (method.ReturnType, reference.ReturnType)) continue; if (method.IsVarArg () != reference.IsVarArg ()) continue; if (method.IsVarArg () && IsVarArgCallTo (method, reference)) return method; if (method.HasParameters != reference.HasParameters) continue; if (!method.HasParameters && !reference.HasParameters) return method; if (!AreSame (method.Parameters, reference.Parameters)) continue; return method; } return null; } static bool AreSame (Collection<ParameterDefinition> a, Collection<ParameterDefinition> b) { var count = a.Count; if (count != b.Count) return false; if (count == 0) return true; for (int i = 0; i < count; i++) if (!AreSame (a [i].ParameterType, b [i].ParameterType)) return false; return true; } private static bool IsVarArgCallTo (MethodDefinition method, MethodReference reference) { if (method.Parameters.Count >= reference.Parameters.Count) return false; if (reference.GetSentinelPosition () != method.Parameters.Count) return false; for (int i = 0; i < method.Parameters.Count; i++) if (!AreSame (method.Parameters [i].ParameterType, reference.Parameters [i].ParameterType)) return false; return true; } static bool AreSame (TypeSpecification a, TypeSpecification b) { if (!AreSame (a.ElementType, b.ElementType)) return false; if (a.IsGenericInstance) return AreSame ((GenericInstanceType) a, (GenericInstanceType) b); if (a.IsRequiredModifier || a.IsOptionalModifier) return AreSame ((IModifierType) a, (IModifierType) b); if (a.IsArray) return AreSame ((ArrayType) a, (ArrayType) b); return true; } static bool AreSame (ArrayType a, ArrayType b) { if (a.Rank != b.Rank) return false; // TODO: dimensions return true; } static bool AreSame (IModifierType a, IModifierType b) { return AreSame (a.ModifierType, b.ModifierType); } static bool AreSame (GenericInstanceType a, GenericInstanceType b) { if (a.GenericArguments.Count != b.GenericArguments.Count) return false; for (int i = 0; i < a.GenericArguments.Count; i++) if (!AreSame (a.GenericArguments [i], b.GenericArguments [i])) return false; return true; } static bool AreSame (GenericParameter a, GenericParameter b) { return a.Position == b.Position; } static bool AreSame (TypeReference a, TypeReference b) { if (ReferenceEquals (a, b)) return true; if (a == null || b == null) return false; if (a.etype != b.etype) return false; if (a.IsGenericParameter) return AreSame ((GenericParameter) a, (GenericParameter) b); if (a.IsTypeSpecification ()) return AreSame ((TypeSpecification) a, (TypeSpecification) b); if (a.Name != b.Name || a.Namespace != b.Namespace) return false; //TODO: check scope return AreSame (a.DeclaringType, b.DeclaringType); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure.Messaging.EventHubs.Diagnostics; using Azure.Messaging.EventHubs.Primitives; using Moq; using NUnit.Framework; namespace Azure.Messaging.EventHubs.Tests { /// <summary> /// The suite of tests for the <see cref="PartitionLoadBalancer" /> /// class. /// </summary> /// [TestFixture] public class PartitionLoadBalancerTests { private const string FullyQualifiedNamespace = "fqns"; private const string EventHubName = "name"; private const string ConsumerGroup = "consumerGroup"; /// <summary> /// Verifies that partitions owned by a <see cref="PartitionLoadBalancer" /> are immediately available to be claimed by another load balancer /// after StopAsync is called. /// </summary> /// [Test] public async Task RelinquishOwnershipAsyncRelinquishesPartitionOwnershipOtherClientsConsiderThemClaimableImmediately() { const int NumberOfPartitions = 3; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadbalancer1 = new PartitionLoadBalancer(storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10)); var loadbalancer2 = new PartitionLoadBalancer(storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10)); // Ownership should start empty. var completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); Assert.That(completeOwnership.Count(), Is.EqualTo(0)); // Start the load balancer so that it claims a random partition until none are left. for (int i = 0; i < NumberOfPartitions; i++) { await loadbalancer1.RunLoadBalancingAsync(partitionIds, CancellationToken.None); } completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); // All partitions are owned by loadbalancer1. Assert.That(completeOwnership.Count(p => p.OwnerIdentifier.Equals(loadbalancer1.OwnerIdentifier)), Is.EqualTo(NumberOfPartitions)); // Stopping the load balancer should relinquish all partition ownership. await loadbalancer1.RelinquishOwnershipAsync(CancellationToken.None); completeOwnership = await storageManager.ListOwnershipAsync(loadbalancer1.FullyQualifiedNamespace, loadbalancer1.EventHubName, loadbalancer1.ConsumerGroup); // No partitions are owned by loadbalancer1. Assert.That(completeOwnership.Count(p => p.OwnerIdentifier.Equals(loadbalancer1.OwnerIdentifier)), Is.EqualTo(0)); // Start loadbalancer2 so that the load balancer claims a random partition until none are left. // All partitions should be immediately claimable even though they were just claimed by the loadbalancer1. for (int i = 0; i < NumberOfPartitions; i++) { await loadbalancer2.RunLoadBalancingAsync(partitionIds, CancellationToken.None); } completeOwnership = await storageManager.ListOwnershipAsync(loadbalancer1.FullyQualifiedNamespace, loadbalancer1.EventHubName, loadbalancer1.ConsumerGroup); // All partitions are owned by loadbalancer2. Assert.That(completeOwnership.Count(p => p.OwnerIdentifier.Equals(loadbalancer2.OwnerIdentifier)), Is.EqualTo(NumberOfPartitions)); } /// <summary> /// Verifies that claimable partitions are claimed by a <see cref="PartitionLoadBalancer" /> after RunAsync is called. /// </summary> /// [Test] public async Task RunLoadBalancingAsyncClaimsAllClaimablePartitions() { const int NumberOfPartitions = 3; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadbalancer = new PartitionLoadBalancer(storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10)); // Ownership should start empty. var completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); Assert.That(completeOwnership.Count(), Is.EqualTo(0)); // Start the load balancer so that it claims a random partition until none are left. for (int i = 0; i < NumberOfPartitions; i++) { await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); } completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); // All partitions are owned by load balancer. Assert.That(completeOwnership.Count(), Is.EqualTo(NumberOfPartitions)); } /// <summary> /// Verifies that claimable partitions are claimed by a <see cref="PartitionLoadBalancer" /> after RunAsync is called. /// </summary> /// [Test] public async Task IsBalancedIsCorrectWithOneProcessor() { const int NumberOfPartitions = 3; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadBalancer = new PartitionLoadBalancer(storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10)); // Ownership should start empty. var completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); Assert.That(completeOwnership.Count(), Is.EqualTo(0), "No partitions should be owned."); // Start the load balancer so that it claims a random partition until none are left. for (var index = 0; index < NumberOfPartitions; ++index) { await loadBalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); Assert.That(loadBalancer.IsBalanced, Is.False, "The load balancer should not believe the state is balanced while partitions remain unclaimed."); } // The load balancer should not consider itself balanced until a cycle is run with no partitions claimed. Run one additional // cycle to satisfy that condition. Assert.That(loadBalancer.IsBalanced, Is.False, "The load balancer should not believe the state is balanced until no partition is claimed during a cycle."); await loadBalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); // All partitions are owned by load balancer. completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); Assert.That(completeOwnership.Count(), Is.EqualTo(NumberOfPartitions), "All partitions should be owned."); Assert.That(loadBalancer.IsBalanced, Is.True, "The load balancer should believe the state is balanced when it owns all partitions."); } /// <summary> /// Verifies that claimable partitions are claimed by a <see cref="PartitionLoadBalancer" /> after RunAsync is called. /// </summary> /// [Test] public async Task IsBalancedIsCorrectWithMultipleProcessorsAndAnEventDistribution() { const int MinimumPartitionCount = 4; const int NumberOfPartitions = 12; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadBalancer = new PartitionLoadBalancer(storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10)); var completeOwnership = Enumerable.Empty<EventProcessorPartitionOwnership>(); // Create partitions owned by a different load balancer. var secondLoadBalancerId = Guid.NewGuid().ToString(); var secondLoadBalancerPartitions = Enumerable.Range(1, MinimumPartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(secondLoadBalancerPartitions.Select(i => i.ToString()), secondLoadBalancerId)); // Create partitions owned by a different load balancer. var thirdLoadBalancerId = Guid.NewGuid().ToString(); var thirdLoadBalancerPartitions = Enumerable.Range(secondLoadBalancerPartitions.Max() + 1, MinimumPartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(thirdLoadBalancerPartitions.Select(i => i.ToString()), thirdLoadBalancerId)); // Seed the storageManager with all partitions. await storageManager.ClaimOwnershipAsync(completeOwnership); // Ensure that there is exactly the minimum number of partitions available to be owned. var unownedPartitions = partitionIds.Except(completeOwnership.Select(p => p.PartitionId)); Assert.That(unownedPartitions.Count(), Is.EqualTo(MinimumPartitionCount), "There should be exactly the balanced share of partitions left unowned."); // Run load balancing cycles until the load balancer believes that the state is balanced or the minimum count is quadrupled. var cycleCount = 0; while ((!loadBalancer.IsBalanced) && (cycleCount < (MinimumPartitionCount * 4))) { await loadBalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); ++cycleCount; } completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); unownedPartitions = partitionIds.Except(completeOwnership.Select(p => p.PartitionId)); Assert.That(unownedPartitions.Count(), Is.EqualTo(0), "There no partitions left unowned."); Assert.That(completeOwnership.Count(), Is.EqualTo(NumberOfPartitions), "All partitions should be owned."); Assert.That(loadBalancer.IsBalanced, Is.True, "The load balancer should believe the state is balanced when it owns the correct number of partitions."); Assert.That(cycleCount, Is.EqualTo(MinimumPartitionCount + 1), "The load balancer should have reached a balanced state once all partitions were owned and the next cycle claimed none."); } /// <summary> /// Verifies that claimable partitions are claimed by a <see cref="PartitionLoadBalancer" /> after RunAsync is called. /// </summary> /// [Test] public async Task IsBalancedIsCorrectWithMultipleProcessorsAndAnUnevenDistribution() { const int MinimumPartitionCount = 4; const int NumberOfPartitions = 13; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadBalancer = new PartitionLoadBalancer(storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10)); var completeOwnership = Enumerable.Empty<EventProcessorPartitionOwnership>(); // Create partitions owned by a different load balancer. var secondLoadBalancerId = Guid.NewGuid().ToString(); var secondLoadBalancerPartitions = Enumerable.Range(1, MinimumPartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(secondLoadBalancerPartitions.Select(i => i.ToString()), secondLoadBalancerId)); // Create partitions owned by a different load balancer. var thirdLoadBalancerId = Guid.NewGuid().ToString(); var thirdLoadBalancerPartitions = Enumerable.Range(secondLoadBalancerPartitions.Max() + 1, MinimumPartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(thirdLoadBalancerPartitions.Select(i => i.ToString()), thirdLoadBalancerId)); // Seed the storageManager with all partitions. await storageManager.ClaimOwnershipAsync(completeOwnership); // Ensure that there is exactly one more than the minimum number of partitions available to be owned. var unownedPartitions = partitionIds.Except(completeOwnership.Select(p => p.PartitionId)); Assert.That(unownedPartitions.Count(), Is.EqualTo(MinimumPartitionCount + 1), $"There should be { MinimumPartitionCount + 1 } partitions left unowned."); // Run load balancing cycles until the load balancer believes that the state is balanced or the minimum count is quadrupled. var cycleCount = 0; while ((!loadBalancer.IsBalanced) && (cycleCount < (MinimumPartitionCount * 4))) { await loadBalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); ++cycleCount; } completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); unownedPartitions = partitionIds.Except(completeOwnership.Select(p => p.PartitionId)); Assert.That(unownedPartitions.Count(), Is.EqualTo(0), "There no partitions left unowned."); Assert.That(completeOwnership.Count(), Is.EqualTo(NumberOfPartitions), "All partitions should be owned."); Assert.That(loadBalancer.IsBalanced, Is.True, "The load balancer should believe the state is balanced when it owns the correct number of partitions."); Assert.That(cycleCount, Is.EqualTo(MinimumPartitionCount + 2), "The load balancer should have reached a balanced state once all partitions were owned and the next cycle claimed none."); } /// <summary> /// Verifies that partitions ownership load balancing will direct a <see cref="PartitionLoadBalancer" /> to claim ownership of a claimable partition /// when it owns exactly the calculated MinimumOwnedPartitionsCount. /// </summary> /// [Test] public async Task RunLoadBalancingAsyncClaimsPartitionsWhenOwnedEqualsMinimumOwnedPartitionsCount() { const int MinimumPartitionCount = 4; const int NumberOfPartitions = 13; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadbalancer = new PartitionLoadBalancer( storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10)); // Create partitions owned by this load balancer. var loadbalancer1PartitionIds = Enumerable.Range(1, MinimumPartitionCount); var completeOwnership = CreatePartitionOwnership(loadbalancer1PartitionIds.Select(i => i.ToString()), loadbalancer.OwnerIdentifier); // Create partitions owned by a different load balancer. var loadbalancer2Id = Guid.NewGuid().ToString(); var loadbalancer2PartitionIds = Enumerable.Range(loadbalancer1PartitionIds.Max() + 1, MinimumPartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(loadbalancer2PartitionIds.Select(i => i.ToString()), loadbalancer2Id)); // Create partitions owned by a different load balancer. var loadbalancer3Id = Guid.NewGuid().ToString(); var loadbalancer3PartitionIds = Enumerable.Range(loadbalancer2PartitionIds.Max() + 1, MinimumPartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(loadbalancer3PartitionIds.Select(i => i.ToString()), loadbalancer3Id)); // Seed the storageManager with all partitions. await storageManager.ClaimOwnershipAsync(completeOwnership); var claimablePartitionIds = partitionIds.Except(completeOwnership.Select(p => p.PartitionId)); // Get owned partitions. var totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); var ownedByloadbalancer1 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer.OwnerIdentifier); // Verify owned partitionIds match the owned partitions. Assert.That(ownedByloadbalancer1.Count(), Is.EqualTo(MinimumPartitionCount)); Assert.That(ownedByloadbalancer1.Any(owned => claimablePartitionIds.Contains(owned.PartitionId)), Is.False); // Start the load balancer to claim ownership from of a Partition even though ownedPartitionCount == MinimumOwnedPartitionsCount. await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); // Get owned partitions. totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); ownedByloadbalancer1 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer.OwnerIdentifier); // Verify that we took ownership of the additional partition. Assert.That(ownedByloadbalancer1.Count(), Is.GreaterThan(MinimumPartitionCount)); Assert.That(ownedByloadbalancer1.Any(owned => claimablePartitionIds.Contains(owned.PartitionId)), Is.True); } /// <summary> /// Verifies that partitions ownership load balancing will direct a <see cref="PartitionLoadBalancer" /> steal ownership of a partition /// from another <see cref="PartitionLoadBalancer" /> the other load balancer owns greater than the calculated MaximumOwnedPartitionsCount. /// </summary> /// [Test] public async Task RunLoadBalancingAsyncStealsPartitionsWhenThisLoadbalancerOwnsMinPartitionsAndOtherLoadbalancerOwnsGreatherThanMaxPartitions() { const int MinimumpartitionCount = 4; const int MaximumpartitionCount = 5; const int NumberOfPartitions = 14; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadbalancer = new PartitionLoadBalancer( storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10)); // Create partitions owned by this load balancer. var loadbalancer1PartitionIds = Enumerable.Range(1, MinimumpartitionCount); var completeOwnership = CreatePartitionOwnership(loadbalancer1PartitionIds.Select(i => i.ToString()), loadbalancer.OwnerIdentifier); // Create partitions owned by a different load balancer. var loadbalancer2Id = Guid.NewGuid().ToString(); var loadbalancer2PartitionIds = Enumerable.Range(loadbalancer1PartitionIds.Max() + 1, MinimumpartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(loadbalancer2PartitionIds.Select(i => i.ToString()), loadbalancer2Id)); // Create partitions owned by a different load balancer above the MaximumPartitionCount. var loadbalancer3Id = Guid.NewGuid().ToString(); var stealablePartitionIds = Enumerable.Range(loadbalancer2PartitionIds.Max() + 1, MaximumpartitionCount + 1); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(stealablePartitionIds.Select(i => i.ToString()), loadbalancer3Id)); // Seed the storageManager with the owned partitions. await storageManager.ClaimOwnershipAsync(completeOwnership); // Get owned partitions. var totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); var ownedByloadbalancer1 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer.OwnerIdentifier); var ownedByloadbalancer3 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer3Id); // Verify owned partitionIds match the owned partitions. Assert.That(ownedByloadbalancer1.Any(owned => stealablePartitionIds.Contains(int.Parse(owned.PartitionId))), Is.False); // Verify load balancer 3 has stealable partitions. Assert.That(ownedByloadbalancer3.Count(), Is.GreaterThan(MaximumpartitionCount)); // Start the load balancer to steal ownership from of a when ownedPartitionCount == MinimumOwnedPartitionsCount but a load balancer owns > MaximumPartitionCount. await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); // Get owned partitions. totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); ownedByloadbalancer1 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer.OwnerIdentifier); ownedByloadbalancer3 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer3Id); // Verify that we took ownership of the additional partition. Assert.That(ownedByloadbalancer1.Any(owned => stealablePartitionIds.Contains(int.Parse(owned.PartitionId))), Is.True); // Verify load balancer 3 now does not own > MaximumPartitionCount. Assert.That(ownedByloadbalancer3.Count(), Is.EqualTo(MaximumpartitionCount)); } /// <summary> /// Verifies that partitions ownership load balancing will direct a <see cref="PartitionLoadBalancer" /> steal ownership of a partition /// from another <see cref="PartitionLoadBalancer" /> the other load balancer owns exactly the calculated MaximumOwnedPartitionsCount. /// </summary> /// [Test] public async Task RunLoadBalancingAsyncStealsPartitionsWhenThisLoadbalancerOwnsLessThanMinPartitionsAndOtherLoadbalancerOwnsMaxPartitions() { const int MinimumpartitionCount = 4; const int MaximumpartitionCount = 5; const int NumberOfPartitions = 12; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadbalancer = new PartitionLoadBalancer( storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10)); // Create more partitions owned by this load balancer. var loadbalancer1PartitionIds = Enumerable.Range(1, MinimumpartitionCount - 1); var completeOwnership = CreatePartitionOwnership(loadbalancer1PartitionIds.Select(i => i.ToString()), loadbalancer.OwnerIdentifier); // Create more partitions owned by a different load balancer. var loadbalancer2Id = Guid.NewGuid().ToString(); var loadbalancer2PartitionIds = Enumerable.Range(loadbalancer1PartitionIds.Max() + 1, MinimumpartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(loadbalancer2PartitionIds.Select(i => i.ToString()), loadbalancer2Id)); // Create more partitions owned by a different load balancer above the MaximumPartitionCount. var loadbalancer3Id = Guid.NewGuid().ToString(); var stealablePartitionIds = Enumerable.Range(loadbalancer2PartitionIds.Max() + 1, MaximumpartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(stealablePartitionIds.Select(i => i.ToString()), loadbalancer3Id)); // Seed the storageManager with the owned partitions. await storageManager.ClaimOwnershipAsync(completeOwnership); // Get owned partitions. var totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); var ownedByloadbalancer1 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer.OwnerIdentifier); var ownedByloadbalancer3 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer3Id); // Verify owned partitionIds match the owned partitions. Assert.That(ownedByloadbalancer1.Any(owned => stealablePartitionIds.Contains(int.Parse(owned.PartitionId))), Is.False); // Verify load balancer 3 has stealable partitions. Assert.That(ownedByloadbalancer3.Count(), Is.EqualTo(MaximumpartitionCount)); // Start the load balancer to steal ownership from of a when ownedPartitionCount == MinimumOwnedPartitionsCount but a load balancer owns > MaximumPartitionCount. await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); // Get owned partitions. totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); ownedByloadbalancer1 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer.OwnerIdentifier); ownedByloadbalancer3 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer3Id); // Verify that we took ownership of the additional partition. Assert.That(ownedByloadbalancer1.Any(owned => stealablePartitionIds.Contains(int.Parse(owned.PartitionId))), Is.True); // Verify load balancer 3 now does not own > MaximumPartitionCount. Assert.That(ownedByloadbalancer3.Count(), Is.LessThan(MaximumpartitionCount)); } /// <summary> /// Verifies that partitions ownership load balancing not attempt to steal from itself. /// </summary> /// [Test] public async Task RunLoadBalancingAsyncDoesNotStealFromItself() { const int MinimumpartitionCount = 4; const int NumberOfPartitions = 9; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadbalancer = new PartitionLoadBalancer(storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10)); var mockLog = new Mock<PartitionLoadBalancerEventSource>(); loadbalancer.Logger = mockLog.Object; // Create more partitions owned by this load balancer. var loadbalancerPartitionIds = Enumerable.Range(1, MinimumpartitionCount); var completeOwnership = CreatePartitionOwnership(loadbalancerPartitionIds.Select(i => i.ToString()), loadbalancer.OwnerIdentifier); // Seed the storageManager with the owned partitions. await storageManager.ClaimOwnershipAsync(completeOwnership); // Get owned partitions. var totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); var ownedByloadbalancer = GetOwnedPartitionIds(totalOwnedPartitions, loadbalancer.OwnerIdentifier); // Verify number of owned partitions match the number of total partitions. Assert.That(totalOwnedPartitions.Count(), Is.EqualTo(MinimumpartitionCount), "The minimum number of partitions should be owned."); Assert.That(ownedByloadbalancer, Is.EquivalentTo(loadbalancerPartitionIds), "The minimum number of partitions should be owned by the load balancer."); // The load balancing state is not yet equally distributed. Run several load balancing cycles; balance should be reached and // then remain stable. var balanceCycles = NumberOfPartitions - MinimumpartitionCount; while (balanceCycles > 0) { await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); --balanceCycles; } await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); // Verify partition ownership has not changed. totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); ownedByloadbalancer = GetOwnedPartitionIds(totalOwnedPartitions, loadbalancer.OwnerIdentifier); Assert.That(totalOwnedPartitions.Count(), Is.EqualTo(NumberOfPartitions), "All partitions should be owned."); Assert.That(ownedByloadbalancer, Is.EquivalentTo(totalOwnedPartitions.Select(ownership => int.Parse(ownership.PartitionId))), "The load balancer should own all partitions."); // Verify that no attempts to steal were logged. mockLog.Verify(log => log.ShouldStealPartition(It.IsAny<string>()), Times.Never); } /// <summary> /// Verifies that partitions ownership load balancing will not attempt to steal when an uneven distribution /// is already balanced. /// </summary> /// [Test] [TestCase(new[] { 2, 2, 6 })] [TestCase(new[] { 2, 3, 7 })] [TestCase(new[] { 10, 11, 31 })] public async Task RunLoadBalancingAsyncDoesNotStealWhenTheLoadIsBalanced(int[] args) { var minimumPartitionCount = args[0]; var maximumPartitionCount = args[1]; var numberOfPartitions = args[2]; var partitionIds = Enumerable.Range(1, numberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadbalancer = new PartitionLoadBalancer(storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10)); var mockLog = new Mock<PartitionLoadBalancerEventSource>(); loadbalancer.Logger = mockLog.Object; // Create more partitions owned by this load balancer. var loadbalancer1PartitionIds = Enumerable.Range(1, minimumPartitionCount); var completeOwnership = CreatePartitionOwnership(loadbalancer1PartitionIds.Select(i => i.ToString()), loadbalancer.OwnerIdentifier); // Create more partitions owned by a different load balancer. var loadbalancer2Id = Guid.NewGuid().ToString(); var loadbalancer2PartitionIds = Enumerable.Range(loadbalancer1PartitionIds.Max() + 1, minimumPartitionCount); completeOwnership = completeOwnership.Concat(CreatePartitionOwnership(loadbalancer2PartitionIds.Select(i => i.ToString()), loadbalancer2Id)); // Create more partitions owned by a different load balancer above the MaximumPartitionCount. var loadbalancer3Id = Guid.NewGuid().ToString(); var loadbalancer3PartitionIds = Enumerable.Range(loadbalancer2PartitionIds.Max() + 1, maximumPartitionCount); completeOwnership = completeOwnership.Concat(CreatePartitionOwnership(loadbalancer3PartitionIds.Select(i => i.ToString()), loadbalancer3Id)); // Seed the storageManager with the owned partitions. await storageManager.ClaimOwnershipAsync(completeOwnership); // Get owned partitions. var totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); var ownedByloadbalancer1 = GetOwnedPartitionIds(totalOwnedPartitions, loadbalancer.OwnerIdentifier); var ownedByloadbalancer2 = GetOwnedPartitionIds(totalOwnedPartitions, loadbalancer2Id); var ownedByloadbalancer3 = GetOwnedPartitionIds(totalOwnedPartitions, loadbalancer3Id); // Verify number of owned partitions match the number of total partitions. Assert.That(totalOwnedPartitions.Count(), Is.EqualTo(numberOfPartitions), "All partitions should be owned."); Assert.That(ownedByloadbalancer1, Is.EquivalentTo(loadbalancer1PartitionIds), "The correct set of partitions should be owned by the first load balancer."); Assert.That(ownedByloadbalancer2, Is.EquivalentTo(loadbalancer2PartitionIds), "The correct set of partitions should be owned by the first load balancer."); Assert.That(ownedByloadbalancer3, Is.EquivalentTo(loadbalancer3PartitionIds), "The correct set of partitions should be owned by the first load balancer."); // The load balancing state is equally distributed. Run several load balancing cycles; ownership should remain stable. await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); // Verify partition ownership has not changed. totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); ownedByloadbalancer1 = GetOwnedPartitionIds(totalOwnedPartitions, loadbalancer.OwnerIdentifier); ownedByloadbalancer2 = GetOwnedPartitionIds(totalOwnedPartitions, loadbalancer2Id); ownedByloadbalancer3 = GetOwnedPartitionIds(totalOwnedPartitions, loadbalancer3Id); Assert.That(ownedByloadbalancer1, Is.EquivalentTo(loadbalancer1PartitionIds), "The correct set of partitions should for the first load balancer should not have changed."); Assert.That(ownedByloadbalancer2, Is.EquivalentTo(loadbalancer2PartitionIds), "The correct set of partitions should for the second load balancer should not have changed."); Assert.That(ownedByloadbalancer3, Is.EquivalentTo(loadbalancer3PartitionIds), "The correct set of partitions should for the third load balancer should not have changed."); // Verify that no attempts to steal were logged. mockLog.Verify(log => log.ShouldStealPartition(It.IsAny<string>()), Times.Never); } /// <summary> /// Verifies that claimable partitions are claimed by a <see cref="PartitionLoadBalancer" /> after RunAsync is called. /// </summary> /// [Test] public async Task RunLoadBalancingAsyncReclaimsOwnershipWhenRecovering() { const int NumberOfPartitions = 8; const int OrphanedPartitionCount = 4; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadBalancer = new PartitionLoadBalancer(storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10)); // Ownership should start empty. var completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); Assert.That(completeOwnership.Count(), Is.EqualTo(0), "Storage should be tracking no ownership to start."); Assert.That(loadBalancer.OwnedPartitionIds.Count(), Is.EqualTo(0), "The load balancer should start with no ownership."); // Mimic the state of a processor when recovering from a crash; storage says that the processor has ownership of some // number of partitions, but the processor state does not reflect that ownership. // // Assign the processor ownership over half of the partitions in storage, but do not formally claim them. var orphanedPartitions = partitionIds.Take(OrphanedPartitionCount); completeOwnership = await storageManager.ClaimOwnershipAsync(CreatePartitionOwnership(orphanedPartitions, loadBalancer.OwnerIdentifier)); Assert.That(completeOwnership.Count(), Is.EqualTo(OrphanedPartitionCount), "Storage should be tracking half the partitions as orphaned."); Assert.That(loadBalancer.OwnedPartitionIds.Count(), Is.EqualTo(0), "The load balancer should have no ownership of orphaned partitions."); // Run one load balancing cycle. At the end of the cycle, it should have claimed a random partition // and recovered ownership of the orphans. await loadBalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); Assert.That(completeOwnership.Count(), Is.EqualTo(OrphanedPartitionCount + 1), "Storage should be tracking the orphaned partitions and one additional as owned."); Assert.That(loadBalancer.OwnedPartitionIds.Count(), Is.EqualTo(OrphanedPartitionCount + 1), "The load balancer should have ownership of all orphaned partitions and one additional."); // Run load balancing cycles until the load balancer believes that the state is balanced or the partition count is quadrupled. var cycleCount = 0; while ((!loadBalancer.IsBalanced) && (cycleCount < (NumberOfPartitions * 4))) { await loadBalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); ++cycleCount; } // All partitions should be owned by load balancer. completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); Assert.That(completeOwnership.Count(), Is.EqualTo(NumberOfPartitions)); } /// <summary> /// Verifies that claimable partitions are claimed by a <see cref="PartitionLoadBalancer" /> after RunAsync is called. /// </summary> /// [Test] public async Task RunLoadBalancingAsyncReclaimsOwnershipWhenLeaseRenewalFails() { const int NumberOfPartitions = 8; const int OrphanedPartitionCount = 4; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var mockStorageManager = new Mock<InMemoryStorageManager>() { CallBase = true }; var loadBalancer = new PartitionLoadBalancer(mockStorageManager.Object, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10)); // Ownership should start empty. var completeOwnership = await mockStorageManager.Object.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); Assert.That(completeOwnership.Count(), Is.EqualTo(0), "Storage should be tracking no ownership to start."); Assert.That(loadBalancer.OwnedPartitionIds.Count(), Is.EqualTo(0), "The load balancer should start with no ownership."); // Mimic the state of a processor when recovering from a crash; storage says that the processor has ownership of some // number of partitions, but the processor state does not reflect that ownership. // // Assign the processor ownership over half of the partitions in storage, but do not formally claim them. var orphanedPartitions = partitionIds.Take(OrphanedPartitionCount); completeOwnership = await mockStorageManager.Object.ClaimOwnershipAsync(CreatePartitionOwnership(orphanedPartitions, loadBalancer.OwnerIdentifier)); Assert.That(completeOwnership.Count(), Is.EqualTo(OrphanedPartitionCount), "Storage should be tracking half the partitions as orphaned."); Assert.That(loadBalancer.OwnedPartitionIds.Count(), Is.EqualTo(0), "The load balancer should have no ownership of orphaned partitions."); // Configure the Storage Manager to fail all claim attempts moving forward. mockStorageManager .Setup(sm => sm.ClaimOwnershipAsync(It.IsAny<IEnumerable<EventProcessorPartitionOwnership>>(), It.IsAny<CancellationToken>())) .ReturnsAsync(Enumerable.Empty<EventProcessorPartitionOwnership>()); // Run one load balancing cycle. At the end of the cycle, it should have recovered ownership of the orphans // but made no new claims. await loadBalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); completeOwnership = await mockStorageManager.Object.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); Assert.That(completeOwnership.Count(), Is.EqualTo(OrphanedPartitionCount), "Storage should be tracking the orphaned partitions as owned."); Assert.That(loadBalancer.OwnedPartitionIds.Count(), Is.EqualTo(OrphanedPartitionCount), "The load balancer should have ownership of all orphaned partitions and none additional."); // Run load balancing cycles until the load balancer believes that the state is balanced or the partition count is quadrupled. var cycleCount = 0; while ((!loadBalancer.IsBalanced) && (cycleCount < (NumberOfPartitions * 4))) { await loadBalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); ++cycleCount; } // Only the orphaned partitions should be owned by load balancer, other claims have failed. completeOwnership = await mockStorageManager.Object.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); Assert.That(completeOwnership.Count(), Is.EqualTo(OrphanedPartitionCount), "Storage should be tracking the orphaned partitions as owned."); Assert.That(loadBalancer.OwnedPartitionIds.Count(), Is.EqualTo(OrphanedPartitionCount), "The load balancer should have ownership of all orphaned partitions and none additional."); } /// <summary> /// Verifies that claimable partitions are claimed by a <see cref="PartitionLoadBalancer" /> after RunAsync is called. /// </summary> /// [Test] public async Task RunLoadBalancingAsyncDoesNotStealOwnershipAsRecovery() { const int NumberOfPartitions = 8; const int MinimumPartitionCount = 4; const int OrphanedPartitionCount = 2; var otherLoadBalancerIdentifier = Guid.NewGuid().ToString(); var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadBalancer = new PartitionLoadBalancer(storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10)); // Ownership should start empty. var completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); Assert.That(completeOwnership.Count(), Is.EqualTo(0), "Storage should be tracking no ownership to start."); Assert.That(loadBalancer.OwnedPartitionIds.Count(), Is.EqualTo(0), "The load balancer should start with no ownership."); // Claim the minimum set of partitions for the "other" load balancer. completeOwnership = await storageManager.ClaimOwnershipAsync(CreatePartitionOwnership(partitionIds.Take(MinimumPartitionCount), otherLoadBalancerIdentifier)); Assert.That(completeOwnership.Count(), Is.EqualTo(MinimumPartitionCount), "Storage should be tracking half the partitions as owned by another processor."); Assert.That(loadBalancer.OwnedPartitionIds.Count(), Is.EqualTo(0), "The load balancer should have no ownership of any partitions."); // Mimic the state of a processor when recovering from a crash; storage says that the processor has ownership of some // number of partitions, but the processor state does not reflect that ownership. // // Assign the processor ownership over half of the partitions in storage, but do not formally claim them. await storageManager.ClaimOwnershipAsync(CreatePartitionOwnership(partitionIds.Skip(MinimumPartitionCount).Take(OrphanedPartitionCount), loadBalancer.OwnerIdentifier)); completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); Assert.That(completeOwnership.Count(), Is.EqualTo(OrphanedPartitionCount + MinimumPartitionCount), "Storage should be tracking half the partitions as owned by another processor as well as some orphans."); Assert.That(loadBalancer.OwnedPartitionIds.Count(), Is.EqualTo(0), "The load balancer should have no ownership of orphaned or otherwise owned partitions."); // Run one load balancing cycle. At the end of the cycle, it should have claimed a random partition // and recovered ownership of the orphans. await loadBalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); Assert.That(completeOwnership.Count(), Is.EqualTo(OrphanedPartitionCount + MinimumPartitionCount + 1), "Storage should be tracking the orphaned partitions, other processor partitions, and one additional as owned."); Assert.That(loadBalancer.OwnedPartitionIds.Count(), Is.EqualTo(OrphanedPartitionCount + 1), "The load balancer should have ownership of all orphaned partitions and one additional."); // Run load balancing cycles until the load balancer believes that the state is balanced or the partition count is quadrupled. var cycleCount = 0; while ((!loadBalancer.IsBalanced) && (cycleCount < (NumberOfPartitions * 4))) { await loadBalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); ++cycleCount; } // All partitions should be owned by load balancer. completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); Assert.That(completeOwnership.Count(), Is.EqualTo(NumberOfPartitions)); } /// <summary> /// Verify logs for the <see cref="PartitionLoadBalancer" />. /// </summary> /// [Test] public async Task VerifiesEventProcessorLogs() { const int NumberOfPartitions = 4; const int MinimumpartitionCount = NumberOfPartitions / 2; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadbalancer = new PartitionLoadBalancer( storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10)); // Create more partitions owned by a different load balancer. var loadbalancer2Id = Guid.NewGuid().ToString(); var completeOwnership = CreatePartitionOwnership(partitionIds.Skip(1), loadbalancer2Id); // Seed the storageManager with the owned partitions. await storageManager.ClaimOwnershipAsync(completeOwnership); var mockLog = new Mock<PartitionLoadBalancerEventSource>(); loadbalancer.Logger = mockLog.Object; for (int i = 0; i < NumberOfPartitions; i++) { await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); } await loadbalancer.RelinquishOwnershipAsync(CancellationToken.None); mockLog.Verify(m => m.RenewOwnershipStart(loadbalancer.OwnerIdentifier)); mockLog.Verify(m => m.RenewOwnershipComplete(loadbalancer.OwnerIdentifier)); mockLog.Verify(m => m.ClaimOwnershipStart(It.Is<string>(p => partitionIds.Contains(p)))); mockLog.Verify(m => m.MinimumPartitionsPerEventProcessor(MinimumpartitionCount)); mockLog.Verify(m => m.CurrentOwnershipCount(MinimumpartitionCount, loadbalancer.OwnerIdentifier)); mockLog.Verify(m => m.StealPartition(loadbalancer.OwnerIdentifier)); mockLog.Verify(m => m.ShouldStealPartition(loadbalancer.OwnerIdentifier)); mockLog.Verify(m => m.UnclaimedPartitions(It.Is<HashSet<string>>(set => set.Count == 0 || set.All(item => partitionIds.Contains(item))))); } /// <summary> /// Verifies that ownership is renewed only for partitions past LoadBalancingInterval. /// </summary> /// [Test] public async Task RunLoadBalancingAsyncDoesNotRenewFreshPartitions() { const int NumberOfPartitions = 4; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); string[] CollectVersions() => storageManager.Ownership.OrderBy(pair => pair.Key.PartitionId).Select(pair => pair.Value.Version).ToArray(); var now = DateTimeOffset.UtcNow; var loadbalancerId = Guid.NewGuid().ToString(); var loadbalancerMock = new Mock<PartitionLoadBalancer>( storageManager, loadbalancerId, ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(3), TimeSpan.FromSeconds(60)); loadbalancerMock.CallBase = true; loadbalancerMock.Setup(b => b.GetDateTimeOffsetNow()).Returns(() => now); var loadbalancer = loadbalancerMock.Object; storageManager.LastModifiedTime = now; // This run would re-take ownership and update versions for (int i = 0; i < NumberOfPartitions; i++) { await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); } var claimedVersions = CollectVersions(); // This run would renew ownership now = now.AddSeconds(65); storageManager.LastModifiedTime = now; for (int i = 0; i < NumberOfPartitions; i++) { await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); } var renewedVersions = CollectVersions(); // This run would not review anything as everything is up-to-date for (int i = 0; i < NumberOfPartitions; i++) { await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); } var notRenewedVersions = CollectVersions(); for (int i = 0; i < NumberOfPartitions; i++) { Assert.That(claimedVersions[i], Is.Not.EqualTo(renewedVersions[i]), "Partitions should've been claimed"); Assert.That(renewedVersions[i], Is.EqualTo(notRenewedVersions[i]), "Partitions should've been skipped during renewal"); } Assert.That(storageManager.TotalRenewals, Is.EqualTo(8), "There should be 4 initial claims and 4 renew claims"); } /// <summary> /// Creates a collection of <see cref="PartitionOwnership" /> based on the specified arguments. /// </summary> /// /// <param name="partitionIds">A collection of partition identifiers that the collection will be associated with.</param> /// <param name="identifier">The owner identifier of the EventProcessorClient owning the collection.</param> /// /// <returns>A collection of <see cref="PartitionOwnership" />.</returns> /// private IEnumerable<EventProcessorPartitionOwnership> CreatePartitionOwnership(IEnumerable<string> partitionIds, string identifier) { return partitionIds .Select(partitionId => new EventProcessorPartitionOwnership { FullyQualifiedNamespace = FullyQualifiedNamespace, EventHubName = EventHubName, ConsumerGroup = ConsumerGroup, OwnerIdentifier = identifier, PartitionId = partitionId, LastModifiedTime = DateTimeOffset.UtcNow, Version = Guid.NewGuid().ToString() }).ToList(); } /// <summary> /// Retrieves the partition identifiers from a set of ownership records. /// </summary> /// /// <param name="ownership">The set of ownership to query.</param> /// /// <returns>The set of partition identifies represented in the <paramref name="ownership" /> set.</returns> /// private IEnumerable<int> GetOwnedPartitionIds(IEnumerable<EventProcessorPartitionOwnership> ownership, string ownerIdentifier) { foreach (var item in ownership.Where(itm => itm.OwnerIdentifier == ownerIdentifier)) { yield return int.Parse(item.PartitionId); } } } }
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9 #define UNITY_4 #endif #if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3 #define UNITY_LE_4_3 #endif using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEditor; using Pathfinding; namespace Pathfinding { /** Simple GUI utility functions */ public class GUIUtilityx { private static Color prevCol; public static void SetColor (Color col) { prevCol = GUI.color; GUI.color = col; } public static void ResetColor () { GUI.color = prevCol; } } /** Handles fading effects and also some custom GUI functions such as LayerMaskField. * \warning The code is not pretty. */ public class EditorGUILayoutx { Rect fadeAreaRect; Rect lastAreaRect; private Dictionary<string, FadeArea> fadeAreas; /** Global info about which editor is currently active. * \todo Ugly, rewrite this class at some point... */ public static Editor editor; public static GUIStyle defaultAreaStyle; public static GUIStyle defaultLabelStyle; public static GUIStyle stretchStyle; public static GUIStyle stretchStyleThin; private static float speed = 6; private static bool fade = true; public static bool fancyEffects = true; private Stack<FadeArea> fadeAreaStack; public void RemoveID (string id) { if (fadeAreas == null) { return; } fadeAreas.Remove (id); } public bool DrawID (string id) { if (fadeAreas == null) { return false; } return fadeAreas[id].Show (); } public class FadeArea { public Rect currentRect; public Rect lastRect; public float value; public float lastUpdate; /** Is this area open. * This is not the same as if any contents are visible, use #Show for that. */ public bool open; public Color preFadeColor; /** Update the visibility in Layout to avoid complications with different events not drawing the same thing */ private bool visibleInLayout; public void Switch () { lastRect = currentRect; } public FadeArea (bool open) { value = open ? 1 : 0; } /** Should anything inside this FadeArea be drawn. * Should be called every frame ( in all events ) for best results. */ public bool Show () { bool v = open || value > 0F; if ( Event.current.type == EventType.Layout ) { visibleInLayout = v; } return visibleInLayout; } public static implicit operator bool (FadeArea o) { return o.open; } } /** Make sure the stack is cleared at the start of a frame */ public void ClearFadeAreaStack () { if ( fadeAreaStack != null ) fadeAreaStack.Clear (); } public FadeArea BeginFadeArea (bool open,string label, string id) { return BeginFadeArea (open,label,id, defaultAreaStyle); } public FadeArea BeginFadeArea (bool open,string label, string id, GUIStyle areaStyle) { return BeginFadeArea (open, label, id, areaStyle, defaultLabelStyle); } public FadeArea BeginFadeArea (bool open,string label, string id, GUIStyle areaStyle, GUIStyle labelStyle) { Color tmp1 = GUI.color; FadeArea fadeArea = BeginFadeArea (open,id, 20,areaStyle); Color tmp2 = GUI.color; GUI.color = tmp1; if (label != "") { if (GUILayout.Button (label,labelStyle)) { fadeArea.open = !fadeArea.open; editor.Repaint (); } } GUI.color = tmp2; return fadeArea; } public FadeArea BeginFadeArea (bool open, string id) { return BeginFadeArea (open,id,0); } public FadeArea BeginFadeArea (bool open, string id, float minHeight) { return BeginFadeArea (open, id, minHeight, GUIStyle.none); } public FadeArea BeginFadeArea (bool open, string id, float minHeight, GUIStyle areaStyle) { if (editor == null) { Debug.LogError ("You need to set the 'EditorGUIx.editor' variable before calling this function"); return null; } if (stretchStyle == null) { stretchStyle = new GUIStyle (); stretchStyle.stretchWidth = true; } if (fadeAreaStack == null) { fadeAreaStack = new Stack<FadeArea>(); } if (fadeAreas == null) { fadeAreas = new Dictionary<string, FadeArea> (); } if (!fadeAreas.ContainsKey (id)) { fadeAreas.Add (id,new FadeArea (open)); } FadeArea fadeArea = fadeAreas[id]; fadeAreaStack.Push (fadeArea); fadeArea.open = open; //Make sure the area fills the full width areaStyle.stretchWidth = true; Rect lastRect = fadeArea.lastRect; if (!fancyEffects) { fadeArea.value = open ? 1F : 0F; lastRect.height -= minHeight; lastRect.height = open ? lastRect.height : 0; lastRect.height += minHeight; } else { lastRect.height = lastRect.height < minHeight ? minHeight : lastRect.height; lastRect.height -= minHeight; float faded = Hermite (0F,1F,fadeArea.value); lastRect.height *= faded; lastRect.height += minHeight; lastRect.height = Mathf.Round (lastRect.height); } Rect gotLastRect = GUILayoutUtility.GetRect (new GUIContent (),areaStyle,GUILayout.Height (lastRect.height)); //The clipping area, also drawing background GUILayout.BeginArea (lastRect,areaStyle); Rect newRect = EditorGUILayout.BeginVertical (); if (Event.current.type == EventType.Repaint || Event.current.type == EventType.ScrollWheel) { newRect.x = gotLastRect.x; newRect.y = gotLastRect.y; newRect.width = gotLastRect.width;//stretchWidthRect.width; newRect.height += areaStyle.padding.top+ areaStyle.padding.bottom; fadeArea.currentRect = newRect; if (fadeArea.lastRect != newRect) { //@Fix - duplicate //fadeArea.lastUpdate = Time.realtimeSinceStartup; editor.Repaint (); } fadeArea.Switch (); } if (Event.current.type == EventType.Repaint) { float value = fadeArea.value; float targetValue = open ? 1F : 0F; float newRectHeight = fadeArea.lastRect.height; float deltaHeight = 400F / newRectHeight; float deltaTime = Mathf.Clamp (Time.realtimeSinceStartup-fadeAreas[id].lastUpdate,0.00001F,0.05F); deltaTime *= Mathf.Lerp (deltaHeight*deltaHeight*0.01F, 0.8F, 0.9F); fadeAreas[id].lastUpdate = Time.realtimeSinceStartup; //Useless, but fun feature if (Event.current.shift) { deltaTime *= 0.05F; } if (Mathf.Abs(targetValue-value) > 0.001F) { float time = Mathf.Clamp01 (deltaTime*speed); value += time*Mathf.Sign (targetValue-value); editor.Repaint (); } else { value = Mathf.Round (value); } fadeArea.value = Mathf.Clamp01 (value); } if (fade) { Color c = GUI.color; fadeArea.preFadeColor = c; c.a *= fadeArea.value; GUI.color = c; } fadeArea.open = open; return fadeArea; } public void EndFadeArea () { if (fadeAreaStack.Count <= 0) { Debug.LogError ("You are popping more Fade Areas than you are pushing, make sure they are balanced"); return; } FadeArea fadeArea = fadeAreaStack.Pop (); EditorGUILayout.EndVertical (); GUILayout.EndArea (); if (fade) { GUI.color = fadeArea.preFadeColor; } } /** Returns width of current editor indent. * Unity seems to use 13+6*EditorGUI.indentLevel in U3 * and 15*indent - (indent > 1 ? 2 : 0) or something like that in U4 */ public static int IndentWidth () { #if UNITY_4 //Works well for indent levels 0,1,2 at least return 15*EditorGUI.indentLevel - (EditorGUI.indentLevel > 1 ? 2 : 0); #else return 13+6*EditorGUI.indentLevel; #endif } /** Begin horizontal indent for the next control. * Fake "real" indent when using EditorGUIUtility.LookLikeControls.\n * Forumula used is 13+6*EditorGUI.indentLevel */ public static void BeginIndent () { GUILayout.BeginHorizontal (); GUILayout.Space (IndentWidth()); } /** End indent. * Actually just a EndHorizontal call. * \see BeginIndent */ public static void EndIndent () { GUILayout.EndHorizontal (); } public static int SingleTagField (string label, int value) { string[] tagNames = AstarPath.FindTagNames (); value = value < 0 ? 0 : value; value = value >= tagNames.Length ? tagNames.Length-1 : value; value = EditorGUILayout.IntPopup (label,value,tagNames,new int[] {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31}); return value; } public static void SetTagField (GUIContent label, ref Pathfinding.TagMask value) { GUILayout.BeginHorizontal (); EditorGUIUtility.LookLikeControls(); EditorGUILayout.PrefixLabel (label,EditorStyles.layerMaskField); string text = ""; if (value.tagsChange == 0) text = "Nothing"; else if (value.tagsChange == ~0) text = "Everything"; else { text = System.Convert.ToString (value.tagsChange,2); } string[] tagNames = AstarPath.FindTagNames (); if (GUILayout.Button (text,EditorStyles.layerMaskField,GUILayout.ExpandWidth (true))) { GenericMenu menu = new GenericMenu (); menu.AddItem (new GUIContent ("Everything"),value.tagsChange == ~0, value.SetValues, new Pathfinding.TagMask (~0,value.tagsSet)); menu.AddItem (new GUIContent ("Nothing"),value.tagsChange == 0, value.SetValues, new Pathfinding.TagMask (0,value.tagsSet)); for (int i=0;i<tagNames.Length;i++) { bool on = (value.tagsChange >> i & 0x1) != 0; Pathfinding.TagMask result = new Pathfinding.TagMask (on ? value.tagsChange & ~(1 << i) : value.tagsChange | 1<<i,value.tagsSet); menu.AddItem (new GUIContent (tagNames[i]),on,value.SetValues, result); } menu.AddItem (new GUIContent ("Edit Tags..."),false,AstarPathEditor.EditTags); menu.ShowAsContext (); Event.current.Use (); } #if UNITY_LE_4_3 EditorGUIUtility.LookLikeInspector(); #endif GUILayout.EndHorizontal (); } public static void TagsMaskField (GUIContent changeLabel, GUIContent setLabel,ref Pathfinding.TagMask value) { GUILayout.BeginHorizontal (); EditorGUIUtility.LookLikeControls(); EditorGUILayout.PrefixLabel (changeLabel,EditorStyles.layerMaskField); string text = ""; if (value.tagsChange == 0) text = "Nothing"; else if (value.tagsChange == ~0) text = "Everything"; else { text = System.Convert.ToString (value.tagsChange,2); } if (GUILayout.Button (text,EditorStyles.layerMaskField,GUILayout.ExpandWidth (true))) { GenericMenu menu = new GenericMenu (); menu.AddItem (new GUIContent ("Everything"),value.tagsChange == ~0, value.SetValues, new Pathfinding.TagMask (~0,value.tagsSet)); menu.AddItem (new GUIContent ("Nothing"),value.tagsChange == 0, value.SetValues, new Pathfinding.TagMask (0,value.tagsSet)); for (int i=0;i<32;i++) { bool on = (value.tagsChange >> i & 0x1) != 0; Pathfinding.TagMask result = new Pathfinding.TagMask (on ? value.tagsChange & ~(1 << i) : value.tagsChange | 1<<i,value.tagsSet); menu.AddItem (new GUIContent (""+i),on,value.SetValues, result); } menu.ShowAsContext (); Event.current.Use (); } #if UNITY_LE_4_3 EditorGUIUtility.LookLikeInspector(); #endif GUILayout.EndHorizontal (); GUILayout.BeginHorizontal (); EditorGUIUtility.LookLikeControls(); EditorGUILayout.PrefixLabel (setLabel,EditorStyles.layerMaskField); text = ""; if (value.tagsSet == 0) text = "Nothing"; else if (value.tagsSet == ~0) text = "Everything"; else { text = System.Convert.ToString (value.tagsSet,2); } if (GUILayout.Button (text,EditorStyles.layerMaskField,GUILayout.ExpandWidth (true))) { GenericMenu menu = new GenericMenu (); if (value.tagsChange != 0) menu.AddItem (new GUIContent ("Everything"),value.tagsSet == ~0, value.SetValues, new Pathfinding.TagMask (value.tagsChange,~0)); else menu.AddDisabledItem (new GUIContent ("Everything")); menu.AddItem (new GUIContent ("Nothing"),value.tagsSet == 0, value.SetValues, new Pathfinding.TagMask (value.tagsChange,0)); for (int i=0;i<32;i++) { bool enabled = (value.tagsChange >> i & 0x1) != 0; bool on = (value.tagsSet >> i & 0x1) != 0; Pathfinding.TagMask result = new Pathfinding.TagMask (value.tagsChange, on ? value.tagsSet & ~(1 << i) : value.tagsSet | 1<<i); if (enabled) menu.AddItem (new GUIContent (""+i),on,value.SetValues, result); else menu.AddDisabledItem (new GUIContent (""+i)); } menu.ShowAsContext (); Event.current.Use (); } #if UNITY_LE_4_3 EditorGUIUtility.LookLikeInspector(); #endif GUILayout.EndHorizontal (); } public static int UpDownArrows (GUIContent label, int value, GUIStyle labelStyle, GUIStyle upArrow, GUIStyle downArrow) { GUILayout.BeginHorizontal (); GUILayout.Space (EditorGUI.indentLevel*10); GUILayout.Label (label,labelStyle,GUILayout.Width (170)); if (downArrow == null || upArrow == null) { upArrow = GUI.skin.FindStyle ("Button"); downArrow = upArrow; } if (GUILayout.Button ("",upArrow,GUILayout.Width (16),GUILayout.Height (12))) { value++; } if (GUILayout.Button ("",downArrow,GUILayout.Width (16),GUILayout.Height (12))) { value--; } GUILayout.Space (100); GUILayout.EndHorizontal (); return value; } public static bool UnityTagMaskList (GUIContent label, bool foldout, List<string> tagMask) { if (tagMask == null) throw new System.ArgumentNullException ("tagMask"); if (EditorGUILayout.Foldout (foldout, label)) { EditorGUI.indentLevel++; GUILayout.BeginVertical(); for (int i=0;i<tagMask.Count;i++) { tagMask[i] = EditorGUILayout.TagField (tagMask[i]); } GUILayout.BeginHorizontal(); if (GUILayout.Button ("Add Tag")) tagMask.Add ("Untagged"); EditorGUI.BeginDisabledGroup (tagMask.Count == 0); if (GUILayout.Button ("Remove Last")) tagMask.RemoveAt (tagMask.Count-1); EditorGUI.EndDisabledGroup(); GUILayout.EndHorizontal(); GUILayout.EndVertical(); EditorGUI.indentLevel--; return true; } return false; } public static LayerMask LayerMaskField (string label, LayerMask selected) { return LayerMaskField (label,selected,true); } public static List<string> layers; public static List<int> layerNumbers; public static string[] layerNames; public static long lastUpdateTick; /** Displays a LayerMask field. * \param label Label to display * \param showSpecial Use the Nothing and Everything selections * \param selected Current LayerMask * \note Unity 3.5 and up will use the EditorGUILayout.MaskField instead of a custom written one. */ public static LayerMask LayerMaskField (string label, LayerMask selected, bool showSpecial) { #if !UNITY_3_4 //Unity 3.5 and up if (layers == null || (System.DateTime.UtcNow.Ticks - lastUpdateTick > 10000000L && Event.current.type == EventType.Layout)) { lastUpdateTick = System.DateTime.UtcNow.Ticks; if (layers == null) { layers = new List<string>(); layerNumbers = new List<int>(); layerNames = new string[4]; } else { layers.Clear (); layerNumbers.Clear (); } int emptyLayers = 0; for (int i=0;i<32;i++) { string layerName = LayerMask.LayerToName (i); if (layerName != "") { for (;emptyLayers>0;emptyLayers--) layers.Add ("Layer "+(i-emptyLayers)); layerNumbers.Add (i); layers.Add (layerName); } else { emptyLayers++; } } if (layerNames.Length != layers.Count) { layerNames = new string[layers.Count]; } for (int i=0;i<layerNames.Length;i++) layerNames[i] = layers[i]; } selected.value = EditorGUILayout.MaskField (label,selected.value,layerNames); return selected; #else if (layers == null) { layers = new List<string>(); layerNumbers = new List<int>(); } else { layers.Clear (); layerNumbers.Clear (); } string selectedLayers = ""; for (int i=0;i<32;i++) { string layerName = LayerMask.LayerToName (i); if (layerName != "") { if (selected == (selected | (1 << i))) { if (selectedLayers == "") { selectedLayers = layerName; } else { selectedLayers = "Mixed"; } } } } if (Event.current.type != EventType.MouseDown && Event.current.type != EventType.ExecuteCommand) { if (selected.value == 0) { layers.Add ("Nothing"); } else if (selected.value == -1) { layers.Add ("Everything"); } else { layers.Add (selectedLayers); } layerNumbers.Add (-1); } if (showSpecial) { layers.Add ((selected.value == 0 ? "[X] " : " ") + "Nothing"); layerNumbers.Add (-2); layers.Add ((selected.value == -1 ? "[X] " : " ") + "Everything"); layerNumbers.Add (-3); } for (int i=0;i<32;i++) { string layerName = LayerMask.LayerToName (i); if (layerName != "") { if (selected == (selected | (1 << i))) { layers.Add ("[X] "+layerName); } else { layers.Add (" "+layerName); } layerNumbers.Add (i); } } bool preChange = GUI.changed; GUI.changed = false; int newSelected = 0; if (Event.current.type == EventType.MouseDown) { newSelected = -1; } newSelected = EditorGUILayout.Popup (label,newSelected,layers.ToArray(),EditorStyles.layerMaskField); if (GUI.changed && newSelected >= 0) { int preSelected = selected; if (showSpecial && newSelected == 0) { selected = 0; } else if (showSpecial && newSelected == 1) { selected = -1; } else { if (selected == (selected | (1 << layerNumbers[newSelected]))) { selected &= ~(1 << layerNumbers[newSelected]); //Debug.Log ("Set Layer "+LayerMask.LayerToName (LayerNumbers[newSelected]) + " To False "+selected.value); } else { //Debug.Log ("Set Layer "+LayerMask.LayerToName (LayerNumbers[newSelected]) + " To True "+selected.value); selected = selected | (1 << layerNumbers[newSelected]); } } if (selected == preSelected) { GUI.changed = false; } else { //Debug.Log ("Difference made"); } } GUI.changed = preChange || GUI.changed; return selected; #endif } #region Interpolation functions public static float Hermite(float start, float end, float value) { return Mathf.Lerp(start, end, value * value * (3.0f - 2.0f * value)); } public static float Sinerp(float start, float end, float value) { return Mathf.Lerp(start, end, Mathf.Sin(value * Mathf.PI * 0.5f)); } public static float Coserp(float start, float end, float value) { return Mathf.Lerp(start, end, 1.0f - Mathf.Cos(value * Mathf.PI * 0.5f)); } public static float Berp(float start, float end, float value) { value = Mathf.Clamp01(value); value = (Mathf.Sin(value * Mathf.PI * (0.2f + 2.5f * value * value * value)) * Mathf.Pow(1f - value, 2.2f) + value) * (1f + (1.2f * (1f - value))); return start + (end - start) * value; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.Pkcs; using System.Security.Cryptography.X509Certificates; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; using Microsoft.Win32.SafeHandles; using static Interop.Crypt32; using System.Security.Cryptography.Asn1; namespace Internal.Cryptography.Pal.Windows { internal sealed partial class PkcsPalWindows : PkcsPal { public sealed unsafe override byte[] Encrypt(CmsRecipientCollection recipients, ContentInfo contentInfo, AlgorithmIdentifier contentEncryptionAlgorithm, X509Certificate2Collection originatorCerts, CryptographicAttributeObjectCollection unprotectedAttributes) { using (SafeCryptMsgHandle hCryptMsg = EncodeHelpers.CreateCryptMsgHandleToEncode(recipients, contentInfo.ContentType, contentEncryptionAlgorithm, originatorCerts, unprotectedAttributes)) { byte[] encodedContent; if (contentInfo.ContentType.Value.Equals(Oids.Pkcs7Data, StringComparison.OrdinalIgnoreCase)) { encodedContent = PkcsHelpers.EncodeOctetString(contentInfo.Content); } else { encodedContent = contentInfo.Content; if (encodedContent.Length > 0) { // Windows will throw if it encounters indefinite length encoding. // Let's reencode if that is the case ReencodeIfUsingIndefiniteLengthEncodingOnOuterStructure(ref encodedContent); } } if (encodedContent.Length > 0) { // Pin to avoid copy during heap compaction fixed (byte* pinnedContent = encodedContent) { try { if (!Interop.Crypt32.CryptMsgUpdate(hCryptMsg, encodedContent, encodedContent.Length, fFinal: true)) throw Marshal.GetLastWin32Error().ToCryptographicException(); } finally { if (!object.ReferenceEquals(encodedContent, contentInfo.Content)) { Array.Clear(encodedContent, 0, encodedContent.Length); } } } } byte[] encodedMessage = hCryptMsg.GetMsgParamAsByteArray(CryptMsgParamType.CMSG_CONTENT_PARAM); return encodedMessage; } } private static void ReencodeIfUsingIndefiniteLengthEncodingOnOuterStructure(ref byte[] encodedContent) { AsnReader reader = new AsnReader(encodedContent, AsnEncodingRules.BER); reader.ReadTagAndLength(out int? contentsLength, out int _); if (contentsLength != null) { // definite length, do nothing return; } using (AsnWriter writer = new AsnWriter(AsnEncodingRules.BER)) { // Tag doesn't matter here as we won't write it into the document writer.WriteOctetString(reader.PeekContentBytes().Span); encodedContent = writer.Encode(); } } // // The methods in this class have some pretty terrifying contracts with each other regarding the lifetimes of the pointers they hand around so we'll encapsulate them in a nested class so that // only the top level method is accessible to everyone else. // private static class EncodeHelpers { public static SafeCryptMsgHandle CreateCryptMsgHandleToEncode(CmsRecipientCollection recipients, Oid innerContentType, AlgorithmIdentifier contentEncryptionAlgorithm, X509Certificate2Collection originatorCerts, CryptographicAttributeObjectCollection unprotectedAttributes) { using (HeapBlockRetainer hb = new HeapBlockRetainer()) { // Deep copy the CmsRecipients (and especially their underlying X509Certificate2 objects). This will prevent malicious callers from altering them or disposing them while we're performing // unsafe memory crawling inside them. recipients = recipients.DeepCopy(); // We must keep all the certificates inside recipients alive until the call to CryptMsgOpenToEncode() finishes. The CMSG_ENVELOPED_ENCODE_INFO* structure we passed to it // contains direct pointers to memory owned by the CERT_INFO memory block whose lifetime is that of the certificate. hb.KeepAlive(recipients); unsafe { CMSG_ENVELOPED_ENCODE_INFO* pEnvelopedEncodeInfo = CreateCmsEnvelopedEncodeInfo(recipients, contentEncryptionAlgorithm, originatorCerts, unprotectedAttributes, hb); SafeCryptMsgHandle hCryptMsg = Interop.Crypt32.CryptMsgOpenToEncode(MsgEncodingType.All, 0, CryptMsgType.CMSG_ENVELOPED, pEnvelopedEncodeInfo, innerContentType.Value, IntPtr.Zero); if (hCryptMsg == null || hCryptMsg.IsInvalid) throw Marshal.GetLastWin32Error().ToCryptographicException(); return hCryptMsg; } } } // // This returns an allocated native memory block. Its lifetime (and that of any allocated subblocks it may point to) is that of "hb". // private static unsafe CMSG_ENVELOPED_ENCODE_INFO* CreateCmsEnvelopedEncodeInfo(CmsRecipientCollection recipients, AlgorithmIdentifier contentEncryptionAlgorithm, X509Certificate2Collection originatorCerts, CryptographicAttributeObjectCollection unprotectedAttributes, HeapBlockRetainer hb) { CMSG_ENVELOPED_ENCODE_INFO* pEnvelopedEncodeInfo = (CMSG_ENVELOPED_ENCODE_INFO*)(hb.Alloc(sizeof(CMSG_ENVELOPED_ENCODE_INFO))); pEnvelopedEncodeInfo->cbSize = sizeof(CMSG_ENVELOPED_ENCODE_INFO); pEnvelopedEncodeInfo->hCryptProv = IntPtr.Zero; string algorithmOidValue = contentEncryptionAlgorithm.Oid.Value; pEnvelopedEncodeInfo->ContentEncryptionAlgorithm.pszObjId = hb.AllocAsciiString(algorithmOidValue); // Desktop compat: Though it seems like we could copy over the contents of contentEncryptionAlgorithm.Parameters, that property is for retrieving information from decoded Cms's only, and it // massages the raw data so it wouldn't be usable here anyway. To hammer home that fact, the EncryptedCms constructor rather rudely forces contentEncryptionAlgorithm.Parameters to be the empty array. pEnvelopedEncodeInfo->ContentEncryptionAlgorithm.Parameters.cbData = 0; pEnvelopedEncodeInfo->ContentEncryptionAlgorithm.Parameters.pbData = IntPtr.Zero; pEnvelopedEncodeInfo->pvEncryptionAuxInfo = GenerateEncryptionAuxInfoIfNeeded(contentEncryptionAlgorithm, hb); int numRecipients = recipients.Count; pEnvelopedEncodeInfo->cRecipients = numRecipients; pEnvelopedEncodeInfo->rgpRecipients = IntPtr.Zero; CMSG_RECIPIENT_ENCODE_INFO* rgCmsRecipients = (CMSG_RECIPIENT_ENCODE_INFO*)(hb.Alloc(numRecipients, sizeof(CMSG_RECIPIENT_ENCODE_INFO))); for (int index = 0; index < numRecipients; index++) { rgCmsRecipients[index] = EncodeRecipientInfo(recipients[index], contentEncryptionAlgorithm, hb); } pEnvelopedEncodeInfo->rgCmsRecipients = rgCmsRecipients; int numCertificates = originatorCerts.Count; pEnvelopedEncodeInfo->cCertEncoded = numCertificates; pEnvelopedEncodeInfo->rgCertEncoded = null; if (numCertificates != 0) { DATA_BLOB* pCertEncoded = (DATA_BLOB*)(hb.Alloc(numCertificates, sizeof(DATA_BLOB))); for (int i = 0; i < numCertificates; i++) { byte[] certEncoded = originatorCerts[i].Export(X509ContentType.Cert); pCertEncoded[i].cbData = (uint)(certEncoded.Length); pCertEncoded[i].pbData = hb.AllocBytes(certEncoded); } pEnvelopedEncodeInfo->rgCertEncoded = pCertEncoded; } pEnvelopedEncodeInfo->cCrlEncoded = 0; pEnvelopedEncodeInfo->rgCrlEncoded = null; pEnvelopedEncodeInfo->cAttrCertEncoded = 0; pEnvelopedEncodeInfo->rgAttrCertEncoded = null; int numUnprotectedAttributes = unprotectedAttributes.Count; pEnvelopedEncodeInfo->cUnprotectedAttr = numUnprotectedAttributes; pEnvelopedEncodeInfo->rgUnprotectedAttr = null; if (numUnprotectedAttributes != 0) { CRYPT_ATTRIBUTE* pCryptAttribute = (CRYPT_ATTRIBUTE*)(hb.Alloc(numUnprotectedAttributes, sizeof(CRYPT_ATTRIBUTE))); for (int i = 0; i < numUnprotectedAttributes; i++) { CryptographicAttributeObject attribute = unprotectedAttributes[i]; pCryptAttribute[i].pszObjId = hb.AllocAsciiString(attribute.Oid.Value); AsnEncodedDataCollection values = attribute.Values; int numValues = values.Count; pCryptAttribute[i].cValue = numValues; DATA_BLOB* pValues = (DATA_BLOB*)(hb.Alloc(numValues, sizeof(DATA_BLOB))); for (int j = 0; j < numValues; j++) { byte[] rawData = values[j].RawData; pValues[j].cbData = (uint)(rawData.Length); pValues[j].pbData = hb.AllocBytes(rawData); } pCryptAttribute[i].rgValue = pValues; } pEnvelopedEncodeInfo->rgUnprotectedAttr = pCryptAttribute; } return pEnvelopedEncodeInfo; } // // This returns an allocated native memory block. Its lifetime (and that of any allocated subblocks it may point to) is that of "hb". // private static CMSG_RECIPIENT_ENCODE_INFO EncodeRecipientInfo(CmsRecipient recipient, AlgorithmIdentifier contentEncryptionAlgorithm, HeapBlockRetainer hb) { CMSG_RECIPIENT_ENCODE_INFO recipientEncodeInfo; unsafe { switch (recipient.Certificate.GetKeyAlgorithm()) { case Oids.Rsa: case Oids.RsaOaep: recipientEncodeInfo.dwRecipientChoice = CMsgCmsRecipientChoice.CMSG_KEY_TRANS_RECIPIENT; recipientEncodeInfo.pCmsRecipientEncodeInfo = (IntPtr)EncodeKeyTransRecipientInfo(recipient, hb); break; case Oids.Esdh: case Oids.DiffieHellman: case Oids.DiffieHellmanPkcs3: recipientEncodeInfo.dwRecipientChoice = CMsgCmsRecipientChoice.CMSG_KEY_AGREE_RECIPIENT; recipientEncodeInfo.pCmsRecipientEncodeInfo = (IntPtr)EncodeKeyAgreeRecipientInfo(recipient, contentEncryptionAlgorithm, hb); break; default: throw ErrorCode.CRYPT_E_UNKNOWN_ALGO.ToCryptographicException(); } } return recipientEncodeInfo; } // // This returns an allocated native memory block. Its lifetime (and that of any allocated subblocks it may point to) is that of "hb". // private static unsafe CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO* EncodeKeyTransRecipientInfo(CmsRecipient recipient, HeapBlockRetainer hb) { // "recipient" is a deep-cloned CmsRecipient object whose lifetime this class controls. Because of this, we can pull out the CERT_CONTEXT* and CERT_INFO* pointers // and embed pointers to them in the memory block we return. Yes, this code is scary. // // (The use of SafeCertContextHandle here is about using a consistent pattern to get the CERT_CONTEXT (rather than the ugly (CERT_CONTEXT*)(recipient.Certificate.Handle) pattern.) // It's not about keeping the context alive.) using (SafeCertContextHandle hCertContext = recipient.Certificate.CreateCertContextHandle()) { CERT_CONTEXT* pCertContext = hCertContext.DangerousGetCertContext(); CERT_INFO* pCertInfo = pCertContext->pCertInfo; CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO* pEncodeInfo = (CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO*)(hb.Alloc(sizeof(CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO))); pEncodeInfo->cbSize = sizeof(CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO); RSAEncryptionPadding padding = recipient.RSAEncryptionPadding; if (padding is null) { if (recipient.Certificate.GetKeyAlgorithm() == Oids.RsaOaep) { byte[] parameters = recipient.Certificate.GetKeyAlgorithmParameters(); if (parameters == null || parameters.Length == 0) { padding = RSAEncryptionPadding.OaepSHA1; } else if (!PkcsHelpers.TryGetRsaOaepEncryptionPadding(parameters, out padding, out _)) { throw ErrorCode.CRYPT_E_UNKNOWN_ALGO.ToCryptographicException(); } } else { padding = RSAEncryptionPadding.Pkcs1; } } if (padding == RSAEncryptionPadding.Pkcs1) { pEncodeInfo->KeyEncryptionAlgorithm.pszObjId = hb.AllocAsciiString(Oids.Rsa); pEncodeInfo->KeyEncryptionAlgorithm.Parameters.cbData = (uint)s_rsaPkcsParameters.Length; pEncodeInfo->KeyEncryptionAlgorithm.Parameters.pbData = hb.AllocBytes(s_rsaPkcsParameters); } else if (padding == RSAEncryptionPadding.OaepSHA1) { pEncodeInfo->KeyEncryptionAlgorithm.pszObjId = hb.AllocAsciiString(Oids.RsaOaep); pEncodeInfo->KeyEncryptionAlgorithm.Parameters.cbData = (uint)s_rsaOaepSha1Parameters.Length; pEncodeInfo->KeyEncryptionAlgorithm.Parameters.pbData = hb.AllocBytes(s_rsaOaepSha1Parameters); } else if (padding == RSAEncryptionPadding.OaepSHA256) { pEncodeInfo->KeyEncryptionAlgorithm.pszObjId = hb.AllocAsciiString(Oids.RsaOaep); pEncodeInfo->KeyEncryptionAlgorithm.Parameters.cbData = (uint)s_rsaOaepSha256Parameters.Length; pEncodeInfo->KeyEncryptionAlgorithm.Parameters.pbData = hb.AllocBytes(s_rsaOaepSha256Parameters); } else if (padding == RSAEncryptionPadding.OaepSHA384) { pEncodeInfo->KeyEncryptionAlgorithm.pszObjId = hb.AllocAsciiString(Oids.RsaOaep); pEncodeInfo->KeyEncryptionAlgorithm.Parameters.cbData = (uint)s_rsaOaepSha384Parameters.Length; pEncodeInfo->KeyEncryptionAlgorithm.Parameters.pbData = hb.AllocBytes(s_rsaOaepSha384Parameters); } else if (padding == RSAEncryptionPadding.OaepSHA512) { pEncodeInfo->KeyEncryptionAlgorithm.pszObjId = hb.AllocAsciiString(Oids.RsaOaep); pEncodeInfo->KeyEncryptionAlgorithm.Parameters.cbData = (uint)s_rsaOaepSha512Parameters.Length; pEncodeInfo->KeyEncryptionAlgorithm.Parameters.pbData = hb.AllocBytes(s_rsaOaepSha512Parameters); } else { throw ErrorCode.CRYPT_E_UNKNOWN_ALGO.ToCryptographicException(); } pEncodeInfo->pvKeyEncryptionAuxInfo = IntPtr.Zero; pEncodeInfo->hCryptProv = IntPtr.Zero; pEncodeInfo->RecipientPublicKey = pCertInfo->SubjectPublicKeyInfo.PublicKey; pEncodeInfo->RecipientId = EncodeRecipientId(recipient, hCertContext, pCertContext, pCertInfo, hb); return pEncodeInfo; } } // // This returns an allocated native memory block. Its lifetime (and that of any allocated subblocks it may point to) is that of "hb". // private static unsafe CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO* EncodeKeyAgreeRecipientInfo(CmsRecipient recipient, AlgorithmIdentifier contentEncryptionAlgorithm, HeapBlockRetainer hb) { // "recipient" is a deep-cloned CmsRecipient object whose lifetime this class controls. Because of this, we can pull out the CERT_CONTEXT* and CERT_INFO* pointers without // bringing in all the SafeCertContextHandle machinery, and embed pointers to them in the memory block we return. Yes, this code is scary. using (SafeCertContextHandle hCertContext = recipient.Certificate.CreateCertContextHandle()) { CERT_CONTEXT* pCertContext = hCertContext.DangerousGetCertContext(); CERT_INFO* pCertInfo = pCertContext->pCertInfo; CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO* pEncodeInfo = (CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO*)(hb.Alloc(sizeof(CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO))); pEncodeInfo->cbSize = sizeof(CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO); pEncodeInfo->KeyEncryptionAlgorithm.pszObjId = hb.AllocAsciiString(Oids.Esdh); pEncodeInfo->KeyEncryptionAlgorithm.Parameters.cbData = 0; pEncodeInfo->KeyEncryptionAlgorithm.Parameters.pbData = IntPtr.Zero; pEncodeInfo->pvKeyEncryptionAuxInfo = null; string oidValue; AlgId algId = contentEncryptionAlgorithm.Oid.Value.ToAlgId(); if (algId == AlgId.CALG_RC2) oidValue = Oids.CmsRc2Wrap; else oidValue = Oids.Cms3DesWrap; pEncodeInfo->KeyWrapAlgorithm.pszObjId = hb.AllocAsciiString(oidValue); pEncodeInfo->KeyWrapAlgorithm.Parameters.cbData = 0; pEncodeInfo->KeyWrapAlgorithm.Parameters.pbData = IntPtr.Zero; pEncodeInfo->pvKeyWrapAuxInfo = GenerateEncryptionAuxInfoIfNeeded(contentEncryptionAlgorithm, hb); pEncodeInfo->hCryptProv = IntPtr.Zero; pEncodeInfo->dwKeySpec = 0; pEncodeInfo->dwKeyChoice = CmsKeyAgreeKeyChoice.CMSG_KEY_AGREE_EPHEMERAL_KEY_CHOICE; pEncodeInfo->pEphemeralAlgorithm = (CRYPT_ALGORITHM_IDENTIFIER*)(hb.Alloc(sizeof(CRYPT_ALGORITHM_IDENTIFIER))); *(pEncodeInfo->pEphemeralAlgorithm) = pCertInfo->SubjectPublicKeyInfo.Algorithm; pEncodeInfo->UserKeyingMaterial.cbData = 0; pEncodeInfo->UserKeyingMaterial.pbData = IntPtr.Zero; CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO* pEncryptedKey = (CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO*)(hb.Alloc(sizeof(CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO))); pEncryptedKey->cbSize = sizeof(CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO); pEncryptedKey->RecipientPublicKey = pCertInfo->SubjectPublicKeyInfo.PublicKey; pEncryptedKey->RecipientId = EncodeRecipientId(recipient, hCertContext, pCertContext, pCertInfo, hb); pEncryptedKey->Date = default(FILETIME); pEncryptedKey->pOtherAttr = null; CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO** ppEncryptedKey = (CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO**)(hb.Alloc(sizeof(CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO*))); ppEncryptedKey[0] = pEncryptedKey; pEncodeInfo->cRecipientEncryptedKeys = 1; pEncodeInfo->rgpRecipientEncryptedKeys = ppEncryptedKey; return pEncodeInfo; } } // // This returns an allocated native memory block. Its lifetime (and that of any allocated subblocks it may point to) is that of "hb". // private static unsafe CERT_ID EncodeRecipientId(CmsRecipient recipient, SafeCertContextHandle hCertContext, CERT_CONTEXT* pCertContext, CERT_INFO* pCertInfo, HeapBlockRetainer hb) { CERT_ID recipientId = default(CERT_ID); SubjectIdentifierType type = recipient.RecipientIdentifierType; switch (type) { case SubjectIdentifierType.IssuerAndSerialNumber: { recipientId.dwIdChoice = CertIdChoice.CERT_ID_ISSUER_SERIAL_NUMBER; recipientId.u.IssuerSerialNumber.Issuer = pCertInfo->Issuer; recipientId.u.IssuerSerialNumber.SerialNumber = pCertInfo->SerialNumber; break; } case SubjectIdentifierType.SubjectKeyIdentifier: { byte[] ski = hCertContext.GetSubjectKeyIdentifer(); IntPtr pSki = hb.AllocBytes(ski); recipientId.dwIdChoice = CertIdChoice.CERT_ID_KEY_IDENTIFIER; recipientId.u.KeyId.cbData = (uint)(ski.Length); recipientId.u.KeyId.pbData = pSki; break; } default: // The public contract for CmsRecipient guarantees that SubjectKeyIdentifier and IssuerAndSerialNumber are the only two possibilities. Debug.Fail($"Unexpected SubjectIdentifierType: {type}"); throw new NotSupportedException(SR.Format(SR.Cryptography_Cms_Invalid_Subject_Identifier_Type, type)); } return recipientId; } // // This returns an allocated native memory block. Its lifetime (and that of any allocated subblocks it may point to) is that of "hb". // private static IntPtr GenerateEncryptionAuxInfoIfNeeded(AlgorithmIdentifier contentEncryptionAlgorithm, HeapBlockRetainer hb) { string algorithmOidValue = contentEncryptionAlgorithm.Oid.Value; AlgId algId = algorithmOidValue.ToAlgId(); if (!(algId == AlgId.CALG_RC2 || algId == AlgId.CALG_RC4)) return IntPtr.Zero; unsafe { CMSG_RC2_AUX_INFO* pRc2AuxInfo = (CMSG_RC2_AUX_INFO*)(hb.Alloc(sizeof(CMSG_RC2_AUX_INFO))); pRc2AuxInfo->cbSize = sizeof(CMSG_RC2_AUX_INFO); pRc2AuxInfo->dwBitLen = contentEncryptionAlgorithm.KeyLength; if (pRc2AuxInfo->dwBitLen == 0) { // Desktop compat: If the caller didn't set the KeyLength property, set dwBitLength to the maxmium key length supported by RC2/RC4. The desktop queries CAPI for this but // since that requires us to use a prohibited api (CryptAcquireContext), we'll just hardcode what CAPI returns for RC2 and RC4. pRc2AuxInfo->dwBitLen = KeyLengths.DefaultKeyLengthForRc2AndRc4; } return (IntPtr)pRc2AuxInfo; } } } } }
// // CGColorSpace.cs: Implements geometry classes // // Authors: Mono Team // // Copyright 2009 Novell, Inc // Copyright 2011, 2012 Xamarin Inc // // 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.Runtime.InteropServices; using MonoMac.ObjCRuntime; using MonoMac.Foundation; namespace MonoMac.CoreGraphics { public enum CGColorRenderingIntent { Default, AbsoluteColorimetric, RelativeColorimetric, Perceptual, Saturation }; public enum CGColorSpaceModel { Unknown = -1, Monochrome, RGB, CMYK, Lab, DeviceN, Indexed, Pattern } public class CGColorSpace : INativeObject, IDisposable { internal IntPtr handle; public static CGColorSpace Null = new CGColorSpace (IntPtr.Zero); // Invoked by the marshallers, we need to take a ref public CGColorSpace (IntPtr handle) { this.handle = handle; CGColorSpaceRetain (handle); } [Preserve (Conditional=true)] internal CGColorSpace (IntPtr handle, bool owns) { if (!owns) CGColorSpaceRetain (handle); this.handle = handle; } ~CGColorSpace () { Dispose (false); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } public IntPtr Handle { get { return handle; } } [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGColorSpaceRelease (IntPtr handle); [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGColorSpaceRetain (IntPtr handle); protected virtual void Dispose (bool disposing) { if (handle != IntPtr.Zero){ CGColorSpaceRelease (handle); handle = IntPtr.Zero; } } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGColorSpaceCreateDeviceGray (); public static CGColorSpace CreateDeviceGray () { return new CGColorSpace (CGColorSpaceCreateDeviceGray (), true); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGColorSpaceCreateDeviceRGB (); public static CGColorSpace CreateDeviceRGB () { return new CGColorSpace (CGColorSpaceCreateDeviceRGB (), true); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGColorSpaceCreateDeviceCMYK (); public static CGColorSpace CreateDeviceCMYK () { return new CGColorSpace (CGColorSpaceCreateDeviceCMYK (), true); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGColorSpaceCreateCalibratedGray (float [] whitepoint, float [] blackpoint, float gamma); public static CGColorSpace CreateCalibratedGray (float [] whitepoint, float [] blackpoint, float gamma) { if (whitepoint.Length != 3) throw new ArgumentException ("Must have 3 values", "whitepoint"); if (blackpoint.Length != 3) throw new ArgumentException ("Must have 3 values", "blackpoint"); return new CGColorSpace (CGColorSpaceCreateCalibratedGray (whitepoint, blackpoint, gamma), true); } // 3, 3, 3, 9 [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGColorSpaceCreateCalibratedRGB (float [] whitePoint, float [] blackPoint, float [] gamma, float [] matrix); public static CGColorSpace CreateCalibratedRGB (float [] whitepoint, float [] blackpoint, float [] gamma, float [] matrix) { if (whitepoint.Length != 3) throw new ArgumentException ("Must have 3 values", "whitepoint"); if (blackpoint.Length != 3) throw new ArgumentException ("Must have 3 values", "blackpoint"); if (gamma.Length != 3) throw new ArgumentException ("Must have 3 values", "gamma"); if (matrix.Length != 9) throw new ArgumentException ("Must have 9 values", "matrix"); return new CGColorSpace (CGColorSpaceCreateCalibratedRGB (whitepoint, blackpoint, gamma, matrix), true); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGColorSpaceCreateIndexed (IntPtr baseSpace, int lastIndex, byte[] colorTable); public static CGColorSpace CreateIndexed (CGColorSpace baseSpace, int lastIndex, byte[] colorTable) { return new CGColorSpace (CGColorSpaceCreateIndexed (baseSpace == null ? IntPtr.Zero : baseSpace.handle, lastIndex, colorTable), true); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGColorSpaceCreatePattern (IntPtr baseSpace); public static CGColorSpace CreatePattern (CGColorSpace baseSpace) { return new CGColorSpace (CGColorSpaceCreatePattern (baseSpace == null ? IntPtr.Zero : baseSpace.handle), true); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGColorSpaceCreateWithName (IntPtr name); public static CGColorSpace CreateWithName (string name) { if (name == null) throw new ArgumentNullException ("name"); return new CGColorSpace (CGColorSpaceCreateWithName (new NSString(name).Handle), true); } [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGColorSpaceGetBaseColorSpace (IntPtr space); public CGColorSpace GetBaseColorSpace () { return new CGColorSpace (CGColorSpaceGetBaseColorSpace (handle), true); } [DllImport (Constants.CoreGraphicsLibrary)] extern static CGColorSpaceModel CGColorSpaceGetModel (IntPtr space); public CGColorSpaceModel Model { get { return CGColorSpaceGetModel (handle); } } [DllImport (Constants.CoreGraphicsLibrary)] extern static int CGColorSpaceGetNumberOfComponents (IntPtr space); public int Components { get { return CGColorSpaceGetNumberOfComponents (handle); } } [DllImport (Constants.CoreGraphicsLibrary)] extern static /*size_t*/ IntPtr CGColorSpaceGetColorTableCount (IntPtr /* CGColorSpaceRef */ space); [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGColorSpaceGetColorTable (IntPtr /* CGColorSpaceRef */ space, byte[] table); static byte[] Empty = new byte [0]; public byte[] GetColorTable () { int n = CGColorSpaceGetColorTableCount (handle).ToInt32 (); if (n == 0) return Empty; byte[] table = new byte [n * GetBaseColorSpace ().Components]; CGColorSpaceGetColorTable (handle, table); return table; } } }