context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Collections.Generic;
namespace Octokit
{
/// <summary>
/// A client for GitHub's Repository Branches API.
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches">Repository Branches API documentation</a> for more details.
/// </remarks>
public interface IRepositoryBranchesClient
{
/// <summary>
/// Gets all the branches for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#list-branches">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
Task<IReadOnlyList<Branch>> GetAll(string owner, string name);
/// <summary>
/// Gets all the branches for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#list-branches">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The ID of the repository</param>
Task<IReadOnlyList<Branch>> GetAll(long repositoryId);
/// <summary>
/// Gets all the branches for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#list-branches">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="options">Options for changing the API response</param>
Task<IReadOnlyList<Branch>> GetAll(string owner, string name, ApiOptions options);
/// <summary>
/// Gets all the branches for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#list-branches">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The ID of the repository</param>
/// <param name="options">Options for changing the API response</param>
Task<IReadOnlyList<Branch>> GetAll(long repositoryId, ApiOptions options);
/// <summary>
/// Gets the specified branch.
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#get-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")]
Task<Branch> Get(string owner, string name, string branch);
/// <summary>
/// Gets the specified branch.
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#get-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The ID of the repository</param>
/// <param name="branch">The name of the branch</param>
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")]
Task<Branch> Get(long repositoryId, string branch);
/// <summary>
/// Get the branch protection settings for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#get-branch-protection">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<BranchProtectionSettings> GetBranchProtection(string owner, string name, string branch);
/// <summary>
/// Get the branch protection settings for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#get-branch-protection">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<BranchProtectionSettings> GetBranchProtection(long repositoryId, string branch);
/// <summary>
/// Update the branch protection settings for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#update-branch-protection">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="update">Branch protection settings</param>
Task<BranchProtectionSettings> UpdateBranchProtection(string owner, string name, string branch, BranchProtectionSettingsUpdate update);
/// <summary>
/// Update the branch protection settings for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#update-branch-protection">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="update">Branch protection settings</param>
Task<BranchProtectionSettings> UpdateBranchProtection(long repositoryId, string branch, BranchProtectionSettingsUpdate update);
/// <summary>
/// Remove the branch protection settings for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#remove-branch-protection">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<bool> DeleteBranchProtection(string owner, string name, string branch);
/// <summary>
/// Remove the branch protection settings for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#remove-branch-protection">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<bool> DeleteBranchProtection(long repositoryId, string branch);
/// <summary>
/// Get the required status checks for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#get-required-status-checks-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<BranchProtectionRequiredStatusChecks> GetRequiredStatusChecks(string owner, string name, string branch);
/// <summary>
/// Get the required status checks for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#get-required-status-checks-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<BranchProtectionRequiredStatusChecks> GetRequiredStatusChecks(long repositoryId, string branch);
/// <summary>
/// Replace required status checks for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#update-required-status-checks-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="update">Required status checks</param>
Task<BranchProtectionRequiredStatusChecks> UpdateRequiredStatusChecks(string owner, string name, string branch, BranchProtectionRequiredStatusChecksUpdate update);
/// <summary>
/// Replace required status checks for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#update-required-status-checks-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="update">Required status checks</param>
Task<BranchProtectionRequiredStatusChecks> UpdateRequiredStatusChecks(long repositoryId, string branch, BranchProtectionRequiredStatusChecksUpdate update);
/// <summary>
/// Remove required status checks for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#remove-required-status-checks-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<bool> DeleteRequiredStatusChecks(string owner, string name, string branch);
/// <summary>
/// Remove required status checks for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#remove-required-status-checks-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<bool> DeleteRequiredStatusChecks(long repositoryId, string branch);
/// <summary>
/// Get the required status checks contexts for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#list-required-status-checks-contexts-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
[Obsolete("Please use GetAllRequiredStatusCheckContexts instead")]
Task<IReadOnlyList<string>> GetRequiredStatusChecksContexts(string owner, string name, string branch);
/// <summary>
/// Get the required status checks contexts for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#list-required-status-checks-contexts-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
[Obsolete("Please use GetAllRequiredStatusCheckContexts instead")]
Task<IReadOnlyList<string>> GetRequiredStatusChecksContexts(long repositoryId, string branch);
/// <summary>
/// Get the required status checks contexts for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#list-required-status-checks-contexts-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
[ExcludeFromPaginationApiOptionsConventionTest("Pagination not supported by GitHub API (tested 29/08/2017)")]
Task<IReadOnlyList<string>> GetAllRequiredStatusChecksContexts(string owner, string name, string branch);
/// <summary>
/// Get the required status checks contexts for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#list-required-status-checks-contexts-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
[ExcludeFromPaginationApiOptionsConventionTest("Pagination not supported by GitHub API (tested 29/08/2017)")]
Task<IReadOnlyList<string>> GetAllRequiredStatusChecksContexts(long repositoryId, string branch);
/// <summary>
/// Replace the required status checks contexts for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#replace-required-status-checks-contexts-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="contexts">The contexts to replace</param>
Task<IReadOnlyList<string>> UpdateRequiredStatusChecksContexts(string owner, string name, string branch, IReadOnlyList<string> contexts);
/// <summary>
/// Replace the required status checks contexts for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#replace-required-status-checks-contexts-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="contexts">The contexts to replace</param>
Task<IReadOnlyList<string>> UpdateRequiredStatusChecksContexts(long repositoryId, string branch, IReadOnlyList<string> contexts);
/// <summary>
/// Add the required status checks context for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#add-required-status-checks-contexts-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="contexts">The contexts to add</param>
Task<IReadOnlyList<string>> AddRequiredStatusChecksContexts(string owner, string name, string branch, IReadOnlyList<string> contexts);
/// <summary>
/// Add the required status checks contexts for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#add-required-status-checks-contexts-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="contexts">The contexts to add</param>
Task<IReadOnlyList<string>> AddRequiredStatusChecksContexts(long repositoryId, string branch, IReadOnlyList<string> contexts);
/// <summary>
/// Remove the required status checks contexts for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#remove-required-status-checks-contexts-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="contexts">The contexts to remove</param>
Task<IReadOnlyList<string>> DeleteRequiredStatusChecksContexts(string owner, string name, string branch, IReadOnlyList<string> contexts);
/// <summary>
/// Remove the required status checks contexts for the specified branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#remove-required-status-checks-contexts-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="contexts">The contexts to remove</param>
Task<IReadOnlyList<string>> DeleteRequiredStatusChecksContexts(long repositoryId, string branch, IReadOnlyList<string> contexts);
/// <summary>
/// Get required pull request review enforcement of protected branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#get-pull-request-review-enforcement-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<BranchProtectionRequiredReviews> GetReviewEnforcement(string owner, string name, string branch);
/// <summary>
/// Get required pull request review enforcement of protected branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#get-admin-enforcement-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<BranchProtectionRequiredReviews> GetReviewEnforcement(long repositoryId, string branch);
/// <summary>
/// Update required pull request review enforcement of protected branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#update-pull-request-review-enforcement-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<BranchProtectionRequiredReviews> UpdateReviewEnforcement(string owner, string name, string branch, BranchProtectionRequiredReviewsUpdate update);
/// <summary>
/// Update required pull request review enforcement of protected branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#update-pull-request-review-enforcement-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<BranchProtectionRequiredReviews> UpdateReviewEnforcement(long repositoryId, string branch, BranchProtectionRequiredReviewsUpdate update);
/// <summary>
/// Remove required pull request review enforcement of protected branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#remove-pull-request-review-enforcement-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<bool> RemoveReviewEnforcement(string owner, string name, string branch);
/// <summary>
/// Remove required pull request review enforcement of protected branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#remove-pull-request-review-enforcement-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<bool> RemoveReviewEnforcement(long repositoryId, string branch);
/// <summary>
/// Get admin enforcement of protected branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#get-admin-enforcement-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<EnforceAdmins> GetAdminEnforcement(string owner, string name, string branch);
/// <summary>
/// Get admin enforcement of protected branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#get-admin-enforcement-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<EnforceAdmins> GetAdminEnforcement(long repositoryId, string branch);
/// <summary>
/// Add admin enforcement to protected branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#add-admin-enforcement-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<EnforceAdmins> AddAdminEnforcement(string owner, string name, string branch);
/// <summary>
/// Add admin enforcement to protected branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#add-admin-enforcement-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<EnforceAdmins> AddAdminEnforcement(long repositoryId, string branch);
/// <summary>
/// Remove admin enforcement on protected branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#remove-admin-enforcement-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<bool> RemoveAdminEnforcement(string owner, string name, string branch);
/// <summary>
/// Remove admin enforcement on protected branch
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#remove-admin-enforcement-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<bool> RemoveAdminEnforcement(long repositoryId, string branch);
/// <summary>
/// Get restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#get-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<BranchProtectionPushRestrictions> GetProtectedBranchRestrictions(string owner, string name, string branch);
/// <summary>
/// Get restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#get-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<BranchProtectionPushRestrictions> GetProtectedBranchRestrictions(long repositoryId, string branch);
/// <summary>
/// Remove restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#remove-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<bool> DeleteProtectedBranchRestrictions(string owner, string name, string branch);
/// <summary>
/// Remove restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#remove-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
Task<bool> DeleteProtectedBranchRestrictions(long repositoryId, string branch);
/// <summary>
/// Get team restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#list-team-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
[Obsolete("Please use GetAllProtectedBranchTeamRestrictions instead")]
Task<IReadOnlyList<Team>> GetProtectedBranchTeamRestrictions(string owner, string name, string branch);
/// <summary>
/// Get team restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#list-team-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
[Obsolete("Please use GetAllProtectedBranchTeamRestrictions instead")]
Task<IReadOnlyList<Team>> GetProtectedBranchTeamRestrictions(long repositoryId, string branch);
/// <summary>
/// Get team restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#list-team-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
[ExcludeFromPaginationApiOptionsConventionTest("Pagination not supported by GitHub API (tested 29/08/2017)")]
Task<IReadOnlyList<Team>> GetAllProtectedBranchTeamRestrictions(string owner, string name, string branch);
/// <summary>
/// Get team restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#list-team-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
[ExcludeFromPaginationApiOptionsConventionTest("Pagination not supported by GitHub API (tested 29/08/2017)")]
Task<IReadOnlyList<Team>> GetAllProtectedBranchTeamRestrictions(long repositoryId, string branch);
/// <summary>
/// Replace team restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#replace-team-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="teams">List of teams with push access</param>
Task<IReadOnlyList<Team>> UpdateProtectedBranchTeamRestrictions(string owner, string name, string branch, BranchProtectionTeamCollection teams);
/// <summary>
/// Replace team restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#replace-team-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="teams">List of teams with push access to add</param>
Task<IReadOnlyList<Team>> UpdateProtectedBranchTeamRestrictions(long repositoryId, string branch, BranchProtectionTeamCollection teams);
/// <summary>
/// Add team restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#add-team-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="teams">List of teams with push access to add</param>
Task<IReadOnlyList<Team>> AddProtectedBranchTeamRestrictions(string owner, string name, string branch, BranchProtectionTeamCollection teams);
/// <summary>
/// Add team restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#add-team-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="teams">List of teams with push access</param>
Task<IReadOnlyList<Team>> AddProtectedBranchTeamRestrictions(long repositoryId, string branch, BranchProtectionTeamCollection teams);
/// <summary>
/// Remove team restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#remove-team-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="teams">List of teams to remove</param>
Task<IReadOnlyList<Team>> DeleteProtectedBranchTeamRestrictions(string owner, string name, string branch, BranchProtectionTeamCollection teams);
/// <summary>
/// Remove team restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#remove-team-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="teams">List of teams to remove</param>
Task<IReadOnlyList<Team>> DeleteProtectedBranchTeamRestrictions(long repositoryId, string branch, BranchProtectionTeamCollection teams);
/// <summary>
/// Get user restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#list-user-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
[Obsolete("Please use GetAllProtectedBranchUserRestrictions instead")]
Task<IReadOnlyList<User>> GetProtectedBranchUserRestrictions(string owner, string name, string branch);
/// <summary>
/// Get user restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#list-user-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
[Obsolete("Please use GetAllProtectedBranchUserRestrictions instead")]
Task<IReadOnlyList<User>> GetProtectedBranchUserRestrictions(long repositoryId, string branch);
/// <summary>
/// Get user restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#list-user-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
[ExcludeFromPaginationApiOptionsConventionTest("Pagination not supported by GitHub API (tested 29/08/2017)")]
Task<IReadOnlyList<User>> GetAllProtectedBranchUserRestrictions(string owner, string name, string branch);
/// <summary>
/// Get user restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#list-user-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
[ExcludeFromPaginationApiOptionsConventionTest("Pagination not supported by GitHub API (tested 29/08/2017)")]
Task<IReadOnlyList<User>> GetAllProtectedBranchUserRestrictions(long repositoryId, string branch);
/// <summary>
/// Replace user restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#replace-user-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="users">List of users with push access</param>
Task<IReadOnlyList<User>> UpdateProtectedBranchUserRestrictions(string owner, string name, string branch, BranchProtectionUserCollection users);
/// <summary>
/// Replace user restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#replace-user-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="users">List of users with push access</param>
Task<IReadOnlyList<User>> UpdateProtectedBranchUserRestrictions(long repositoryId, string branch, BranchProtectionUserCollection users);
/// <summary>
/// Add user restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#add-user-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="users">List of users with push access to add</param>
Task<IReadOnlyList<User>> AddProtectedBranchUserRestrictions(string owner, string name, string branch, BranchProtectionUserCollection users);
/// <summary>
/// Add user restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#add-user-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="users">List of users with push access to add</param>
Task<IReadOnlyList<User>> AddProtectedBranchUserRestrictions(long repositoryId, string branch, BranchProtectionUserCollection users);
/// <summary>
/// Remove user restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#remove-user-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="users">List of users with push access to remove</param>
Task<IReadOnlyList<User>> DeleteProtectedBranchUserRestrictions(string owner, string name, string branch, BranchProtectionUserCollection users);
/// <summary>
/// Remove user restrictions for the specified branch (applies only to Organization owned repositories)
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/branches/#remove-user-restrictions-of-protected-branch">API documentation</a> for more details
/// </remarks>
/// <param name="repositoryId">The Id of the repository</param>
/// <param name="branch">The name of the branch</param>
/// <param name="users">List of users with push access to remove</param>
Task<IReadOnlyList<User>> DeleteProtectedBranchUserRestrictions(long repositoryId, string branch, BranchProtectionUserCollection users);
}
}
| |
// 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.DataFactory.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.DataFactory;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// A linked service for an SSH File Transfer Protocol (SFTP) server.
/// </summary>
[Newtonsoft.Json.JsonObject("Sftp")]
[Rest.Serialization.JsonTransformation]
public partial class SftpServerLinkedService : LinkedService
{
/// <summary>
/// Initializes a new instance of the SftpServerLinkedService class.
/// </summary>
public SftpServerLinkedService()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the SftpServerLinkedService class.
/// </summary>
/// <param name="host">The SFTP server host name. Type: string (or
/// Expression with resultType string).</param>
/// <param name="connectVia">The integration runtime reference.</param>
/// <param name="description">Linked service description.</param>
/// <param name="port">The TCP port number that the SFTP server uses to
/// listen for client connections. Default value is 22. Type: integer
/// (or Expression with resultType integer), minimum: 0.</param>
/// <param name="authenticationType">The authentication type to be used
/// to connect to the FTP server. Possible values include: 'Basic',
/// 'SshPublicKey'</param>
/// <param name="userName">The username used to log on to the SFTP
/// server. Type: string (or Expression with resultType
/// string).</param>
/// <param name="password">Password to logon the SFTP server for Basic
/// authentication.</param>
/// <param name="encryptedCredential">The encrypted credential used for
/// authentication. Credentials are encrypted using the integration
/// runtime credential manager. Type: string (or Expression with
/// resultType string).</param>
/// <param name="privateKeyPath">The SSH private key file path for
/// SshPublicKey authentication. Only valid for on-premises copy. For
/// on-premises copy with SshPublicKey authentication, either
/// PrivateKeyPath or PrivateKeyContent should be specified. SSH
/// private key should be OpenSSH format. Type: string (or Expression
/// with resultType string).</param>
/// <param name="privateKeyContent">Base64 encoded SSH private key
/// content for SshPublicKey authentication. For on-premises copy with
/// SshPublicKey authentication, either PrivateKeyPath or
/// PrivateKeyContent should be specified. SSH private key should be
/// OpenSSH format.</param>
/// <param name="passPhrase">The password to decrypt the SSH private
/// key if the SSH private key is encrypted.</param>
/// <param name="skipHostKeyValidation">If true, skip the SSH host key
/// validation. Default value is false. Type: boolean (or Expression
/// with resultType boolean).</param>
/// <param name="hostKeyFingerprint">The host key finger-print of the
/// SFTP server. When SkipHostKeyValidation is false,
/// HostKeyFingerprint should be specified. Type: string (or Expression
/// with resultType string).</param>
public SftpServerLinkedService(object host, IntegrationRuntimeReference connectVia = default(IntegrationRuntimeReference), string description = default(string), object port = default(object), string authenticationType = default(string), object userName = default(object), SecureString password = default(SecureString), object encryptedCredential = default(object), object privateKeyPath = default(object), SecureString privateKeyContent = default(SecureString), SecureString passPhrase = default(SecureString), object skipHostKeyValidation = default(object), object hostKeyFingerprint = default(object))
: base(connectVia, description)
{
Host = host;
Port = port;
AuthenticationType = authenticationType;
UserName = userName;
Password = password;
EncryptedCredential = encryptedCredential;
PrivateKeyPath = privateKeyPath;
PrivateKeyContent = privateKeyContent;
PassPhrase = passPhrase;
SkipHostKeyValidation = skipHostKeyValidation;
HostKeyFingerprint = hostKeyFingerprint;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the SFTP server host name. Type: string (or Expression
/// with resultType string).
/// </summary>
[JsonProperty(PropertyName = "typeProperties.host")]
public object Host { get; set; }
/// <summary>
/// Gets or sets the TCP port number that the SFTP server uses to
/// listen for client connections. Default value is 22. Type: integer
/// (or Expression with resultType integer), minimum: 0.
/// </summary>
[JsonProperty(PropertyName = "typeProperties.port")]
public object Port { get; set; }
/// <summary>
/// Gets or sets the authentication type to be used to connect to the
/// FTP server. Possible values include: 'Basic', 'SshPublicKey'
/// </summary>
[JsonProperty(PropertyName = "typeProperties.authenticationType")]
public string AuthenticationType { get; set; }
/// <summary>
/// Gets or sets the username used to log on to the SFTP server. Type:
/// string (or Expression with resultType string).
/// </summary>
[JsonProperty(PropertyName = "typeProperties.userName")]
public object UserName { get; set; }
/// <summary>
/// Gets or sets password to logon the SFTP server for Basic
/// authentication.
/// </summary>
[JsonProperty(PropertyName = "typeProperties.password")]
public SecureString Password { get; set; }
/// <summary>
/// Gets or sets the encrypted credential used for authentication.
/// Credentials are encrypted using the integration runtime credential
/// manager. Type: string (or Expression with resultType string).
/// </summary>
[JsonProperty(PropertyName = "typeProperties.encryptedCredential")]
public object EncryptedCredential { get; set; }
/// <summary>
/// Gets or sets the SSH private key file path for SshPublicKey
/// authentication. Only valid for on-premises copy. For on-premises
/// copy with SshPublicKey authentication, either PrivateKeyPath or
/// PrivateKeyContent should be specified. SSH private key should be
/// OpenSSH format. Type: string (or Expression with resultType
/// string).
/// </summary>
[JsonProperty(PropertyName = "typeProperties.privateKeyPath")]
public object PrivateKeyPath { get; set; }
/// <summary>
/// Gets or sets base64 encoded SSH private key content for
/// SshPublicKey authentication. For on-premises copy with SshPublicKey
/// authentication, either PrivateKeyPath or PrivateKeyContent should
/// be specified. SSH private key should be OpenSSH format.
/// </summary>
[JsonProperty(PropertyName = "typeProperties.privateKeyContent")]
public SecureString PrivateKeyContent { get; set; }
/// <summary>
/// Gets or sets the password to decrypt the SSH private key if the SSH
/// private key is encrypted.
/// </summary>
[JsonProperty(PropertyName = "typeProperties.passPhrase")]
public SecureString PassPhrase { get; set; }
/// <summary>
/// Gets or sets if true, skip the SSH host key validation. Default
/// value is false. Type: boolean (or Expression with resultType
/// boolean).
/// </summary>
[JsonProperty(PropertyName = "typeProperties.skipHostKeyValidation")]
public object SkipHostKeyValidation { get; set; }
/// <summary>
/// Gets or sets the host key finger-print of the SFTP server. When
/// SkipHostKeyValidation is false, HostKeyFingerprint should be
/// specified. Type: string (or Expression with resultType string).
/// </summary>
[JsonProperty(PropertyName = "typeProperties.hostKeyFingerprint")]
public object HostKeyFingerprint { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public override void Validate()
{
base.Validate();
if (Host == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Host");
}
if (Password != null)
{
Password.Validate();
}
if (PrivateKeyContent != null)
{
PrivateKeyContent.Validate();
}
if (PassPhrase != null)
{
PassPhrase.Validate();
}
}
}
}
| |
/*
Copyright 2014 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.
*/
using System;
using System.Threading;
using DriveProxy.Forms;
using DriveProxy.Service;
using DriveProxy.Utils;
using Google.Apis.Services;
namespace DriveProxy.API
{
partial class DriveService
{
private class Authenticator
{
private Google.Apis.Drive.v2.DriveService _driveService;
private string _refreshTokenFilePath;
private Google.Apis.Auth.OAuth2.UserCredential _userCredential;
private EncryptedFileDataStore _fileDataStore;
private Authenticator()
{
}
public static Authenticator Create()
{
return Factory.Create();
}
private static void ThrowException(Exception exception)
{
string message = String.Empty;
if (!IsNetworkAvailable())
{
message = "Not currently connected to a network";
}
else if (!CanConnectToGoogleDrive())
{
message = "Cannot connect to https://drive.google.com";
}
else
{
message = exception.Message + " (user " + Settings.UserName + ")";
}
Log.Error(message, false);
throw new AuthenticationException(message);
}
private static bool IsNetworkAvailable()
{
try
{
if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
return false;
}
return true;
}
catch (Exception exception)
{
Log.Error(exception, false);
return false;
}
}
private static bool CanConnectToGoogleDrive()
{
try
{
if (!IsNetworkAvailable())
{
return false;
}
System.Net.WebRequest webRequest = System.Net.WebRequest.Create("https://drive.google.com/");
System.Net.WebResponse webResponse = webRequest.GetResponse();
return true;
}
catch (Exception exception)
{
Log.Error(exception, false);
return false;
}
}
public Google.Apis.Drive.v2.DriveService Init(string applicationName,
string clientIdentifier,
string clientSecret,
string[] scope,
bool logout,
string refreshTokenFolder)
{
StatusForm.ShowDialog();
try
{
_refreshTokenFilePath = refreshTokenFolder;
string fileDataStorePath = _refreshTokenFilePath;
if (FileExists(fileDataStorePath))
{
DateTime lastFileWriteTime = GetFileLastWriteTime(fileDataStorePath);
if (lastFileWriteTime < new DateTime(2014, 8, 22))
{
DeleteFile(fileDataStorePath);
}
}
if (logout)
{
try
{
if (DirectoryExists(fileDataStorePath))
{
string[] fileDataStoreFiles = System.IO.Directory.GetFiles(fileDataStorePath,
"Google.Apis.Auth.OAuth2.Responses.*");
foreach (string fileDataStoreFile in fileDataStoreFiles)
{
DeleteFile(fileDataStoreFile);
}
}
LoginForm.Logout();
}
catch (Exception exception)
{
Log.Error(String.Format("Authenticator.Logout - Deleting token file. {0}",exception.Message));
}
}
var clientSecrets = new Google.Apis.Auth.OAuth2.ClientSecrets
{
ClientId = clientIdentifier,
ClientSecret = clientSecret
};
_fileDataStore = new EncryptedFileDataStore(refreshTokenFolder);
System.Threading.Tasks.Task<Google.Apis.Auth.OAuth2.UserCredential> task = null;
try
{
task = Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.AuthorizeAsync(
clientSecrets,
scope,
System.Environment.UserName,
System.Threading.CancellationToken.None,
_fileDataStore);
task.Wait();
}
catch (Exception exception)
{
throw new LogException("GoogleWebAuthorizationBroker.AuthorizeAsync - " + exception.Message, false, false);
}
_userCredential = task.Result;
var initializer = new BaseClientService.Initializer
{
HttpClientInitializer = _userCredential,
ApplicationName = applicationName
};
_driveService = new Google.Apis.Drive.v2.DriveService(initializer);
UpdateAboutData(_driveService);
return _driveService;
}
catch (Exception exception)
{
Log.Error(exception);
return null;
}
finally
{
StatusForm.CloseDialog();
}
}
public bool HasTimedOut()
{
try
{
if (_userCredential == null || _userCredential.Token == null)
{
return true;
}
if (_userCredential.Token.IsExpired(Google.Apis.Util.SystemClock.Default))
{
return true;
}
System.Threading.Tasks.Task<bool> task =
_userCredential.RefreshTokenAsync(System.Threading.CancellationToken.None);
if (task == null)
{
return true;
}
task.Wait();
if (task.Status != System.Threading.Tasks.TaskStatus.RanToCompletion)
{
return true;
}
if (!task.Result)
{
return true;
}
return false;
}
catch (Exception exception)
{
Log.Error(exception);
return true;
}
}
public void ClearRefreshToken()
{
try
{
//Delete Browser cookies
DeleteDirectoryContents(Environment.GetFolderPath(Environment.SpecialFolder.Cookies));
//Delete Token
DeleteDirectoryContents(_fileDataStore.FolderPath);
//Clean User Credentials
_userCredential = null;
//Clean LoggedUser
Settings.LoggedUser = String.Empty;
}
catch (Exception exception)
{
Log.Error(exception, false, false);
}
}
public void RevokeRefreshToken()
{
try
{
//Revokes the user token.
_userCredential.RevokeTokenAsync(CancellationToken.None);
}
catch (Exception exception)
{
Log.Error(exception, false, false);
}
}
private static class Factory
{
public static Authenticator Create()
{
return new Authenticator();
}
}
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: WebClient.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.ComponentModel;
using System.Text;
using System.Threading.Tasks;
using Dot42;
using Java.IO;
using Java.Net;
namespace System.Net
{
/// <summary>
/// Web connection helper
/// </summary>
public class WebClient : Component
{
private const int BUFFER_SIZE = 4096;
private Encoding encoding;
/// <summary>
/// Gets/sets the encoding used for converting bytes to/from strings.
/// </summary>
public Encoding Encoding
{
get { return encoding ?? Encoding.Default; }
set { encoding = value; }
}
/// <summary>
/// Download a resource from the specified URI.
/// </summary>
[Inline]
public byte[] DownloadData(string address)
{
return DownloadData(new URL(address));
}
/// <summary>
/// Download a resource from the specified URI.
/// </summary>
[Inline]
public byte[] DownloadData(Uri address)
{
return DownloadData(address.ToURL());
}
/// <summary>
/// Download a resource from the specified URI.
/// </summary>
public byte[] DownloadData(URL address)
{
URLConnection connection = null;
InputStream inputStream = null;
try
{
connection = OpenConnection(address);
inputStream = connection.InputStream;
var memStream = new ByteArrayOutputStream();
var buffer = new byte[BUFFER_SIZE];
int len;
while ((len = inputStream.Read(buffer, 0, BUFFER_SIZE)) > 0)
{
memStream.Write(buffer, 0, len);
}
return memStream.ToByteArray();
}
finally
{
if (inputStream != null)
inputStream.Close();
var httpConnection = connection as HttpURLConnection;
if (httpConnection != null)
httpConnection.Disconnect();
}
}
/// <summary>
/// Download a resource from the specified URI.
/// </summary>
[Inline]
public Task<byte[]> DownloadDataTaskAsync(string address)
{
return DownloadDataTaskAsync(new URL(address));
}
/// <summary>
/// Download a resource from the specified URI.
/// </summary>
[Inline]
public Task<byte[]> DownloadDataTaskAsync(Uri address)
{
return DownloadDataTaskAsync(address.ToURL());
}
/// <summary>
/// Download a resource from the specified URI.
/// </summary>
public Task<byte[]> DownloadDataTaskAsync(URL address)
{
return Task.Factory.StartNewIO(() => DownloadData(address));
}
/// <summary>
/// Download a string from the specified URI.
/// </summary>
[Inline]
public string DownloadString(string address)
{
return DownloadString(new URL(address));
}
/// <summary>
/// Download a string from the specified URI.
/// </summary>
[Inline]
public string DownloadString(Uri address)
{
return DownloadString(address.ToURL());
}
/// <summary>
/// Download a string from the specified URI.
/// </summary>
public string DownloadString(URL address)
{
URLConnection connection = null;
InputStream inputStream = null;
try
{
connection = OpenConnection(address);
inputStream = connection.InputStream;
var reader = new InputStreamReader(inputStream);
var buffer = new char[BUFFER_SIZE];
var builder = new StringBuilder();
int len;
while ((len = reader.Read(buffer, 0, BUFFER_SIZE)) > 0)
{
builder.Append(buffer, 0, len);
}
return builder.ToString();
}
finally
{
if (inputStream != null)
inputStream.Close();
var httpConnection = connection as HttpURLConnection;
if (httpConnection != null)
httpConnection.Disconnect();
}
}
/// <summary>
/// Download a resource from the specified URI.
/// </summary>
[Inline]
public Task<string> DownloadStringTaskAsync(string address)
{
return DownloadStringTaskAsync(new URL(address));
}
/// <summary>
/// Download a resource from the specified URI.
/// </summary>
[Inline]
public Task<string> DownloadStringTaskAsync(Uri address)
{
return DownloadStringTaskAsync(address.ToURL());
}
/// <summary>
/// Download a resource from the specified URI.
/// </summary>
public Task<string> DownloadStringTaskAsync(URL address)
{
return Task.Factory.StartNewIO(() => DownloadString(address));
}
/// <summary>
/// Downloads the resource with the specified URI to a local file.
/// </summary>
[Inline]
public void DownloadFile(string address, string fileName)
{
DownloadFile(new URL(address), fileName);
}
/// <summary>
/// Downloads the resource with the specified URI to a local file.
/// </summary>
[Inline]
public void DownloadFile(Uri address, string fileName)
{
DownloadFile(address.ToURL(), fileName);
}
/// <summary>
/// Downloads the resource with the specified URI to a local file.
/// </summary>
public void DownloadFile(URL address, string fileName)
{
URLConnection connection = null;
InputStream inputStream = null;
OutputStream outputStream = new FileOutputStream(fileName);
try
{
connection = OpenConnection(address);
inputStream = connection.InputStream;
var buffer = new byte[BUFFER_SIZE];
int len;
while ((len = inputStream.Read(buffer, 0, BUFFER_SIZE)) > 0)
{
outputStream.Write(buffer, 0, len);
}
outputStream.Flush();
}
finally
{
if (inputStream != null)
inputStream.Close();
var httpConnection = connection as HttpURLConnection;
if (httpConnection != null)
httpConnection.Disconnect();
outputStream.Close();
}
}
/// <summary>
/// Downloads the resource with the specified URI to a local file.
/// </summary>
[Inline]
public Task DownloadFileTaskAsync(string address, string fileName)
{
return DownloadFileTaskAsync(new URL(address), fileName);
}
/// <summary>
/// Downloads the resource with the specified URI to a local file.
/// </summary>
[Inline]
public Task DownloadFileTaskAsync(Uri address, string fileName)
{
return DownloadFileTaskAsync(address.ToURL(), fileName);
}
/// <summary>
/// Downloads the resource with the specified URI to a local file.
/// </summary>
public Task DownloadFileTaskAsync(URL address, string fileName)
{
return Task.Factory.StartNewIO(() => DownloadFileTaskAsync(address, fileName));
}
/// <summary>
/// Open a connection and initialize it.
/// </summary>
private static URLConnection OpenConnection(URL url)
{
var connection = url.OpenConnection();
var httpConnection = connection as HttpURLConnection;
if (httpConnection != null)
{
httpConnection.InstanceFollowRedirects = true;
}
return connection;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ServiceModel.Channels;
using System.Runtime.Serialization;
using System.Xml;
using System.Runtime;
namespace System.ServiceModel.Dispatcher
{
/*
This class is not exposed on the contract as we only need it public for reflection purpose on .Net Native.
*/
public class FaultFormatter : IClientFaultFormatter, IDispatchFaultFormatter
{
private FaultContractInfo[] _faultContractInfos;
internal FaultFormatter(Type[] detailTypes)
{
List<FaultContractInfo> faultContractInfoList = new List<FaultContractInfo>();
for (int i = 0; i < detailTypes.Length; i++)
{
faultContractInfoList.Add(new FaultContractInfo(MessageHeaders.WildcardAction, detailTypes[i]));
}
AddInfrastructureFaults(faultContractInfoList);
_faultContractInfos = GetSortedArray(faultContractInfoList);
}
internal FaultFormatter(SynchronizedCollection<FaultContractInfo> faultContractInfoCollection)
{
List<FaultContractInfo> faultContractInfoList;
lock (faultContractInfoCollection.SyncRoot)
{
faultContractInfoList = new List<FaultContractInfo>(faultContractInfoCollection);
}
AddInfrastructureFaults(faultContractInfoList);
_faultContractInfos = GetSortedArray(faultContractInfoList);
}
public MessageFault Serialize(FaultException faultException, out string action)
{
XmlObjectSerializer serializer = null;
Type detailType = null;
string faultExceptionAction = action = faultException.Action;
Type faultExceptionOfT = null;
for (Type faultType = faultException.GetType(); faultType != typeof(FaultException); faultType = faultType.BaseType())
{
if (faultType.IsGenericType() && (faultType.GetGenericTypeDefinition() == typeof(FaultException<>)))
{
faultExceptionOfT = faultType;
break;
}
}
if (faultExceptionOfT != null)
{
detailType = faultExceptionOfT.GetGenericArguments()[0];
serializer = GetSerializer(detailType, faultExceptionAction, out action);
}
return CreateMessageFault(serializer, faultException, detailType);
}
public FaultException Deserialize(MessageFault messageFault, string action)
{
if (!messageFault.HasDetail)
{
return new FaultException(messageFault, action);
}
return CreateFaultException(messageFault, action);
}
protected virtual XmlObjectSerializer GetSerializer(Type detailType, string faultExceptionAction, out string action)
{
action = faultExceptionAction;
FaultContractInfo faultInfo = null;
for (int i = 0; i < _faultContractInfos.Length; i++)
{
if (_faultContractInfos[i].Detail == detailType)
{
faultInfo = _faultContractInfos[i];
break;
}
}
if (faultInfo != null)
{
if (action == null)
{
action = faultInfo.Action;
}
return faultInfo.Serializer;
}
else
{
return DataContractSerializerDefaults.CreateSerializer(detailType, int.MaxValue /* maxItemsInObjectGraph */ );
}
}
protected virtual FaultException CreateFaultException(MessageFault messageFault, string action)
{
IList<FaultContractInfo> faultInfos;
if (action != null)
{
faultInfos = new List<FaultContractInfo>();
for (int i = 0; i < _faultContractInfos.Length; i++)
{
if (_faultContractInfos[i].Action == action || _faultContractInfos[i].Action == MessageHeaders.WildcardAction)
{
faultInfos.Add(_faultContractInfos[i]);
}
}
}
else
{
faultInfos = _faultContractInfos;
}
Type detailType = null;
object detailObj = null;
for (int i = 0; i < faultInfos.Count; i++)
{
FaultContractInfo faultInfo = faultInfos[i];
XmlDictionaryReader detailReader = messageFault.GetReaderAtDetailContents();
XmlObjectSerializer serializer = faultInfo.Serializer;
if (serializer.IsStartObject(detailReader))
{
detailType = faultInfo.Detail;
try
{
detailObj = serializer.ReadObject(detailReader);
FaultException faultException = CreateFaultException(messageFault, action,
detailObj, detailType, detailReader);
if (faultException != null)
{
return faultException;
}
}
catch (SerializationException)
{
}
}
}
return new FaultException(messageFault, action);
}
protected FaultException CreateFaultException(MessageFault messageFault, string action,
object detailObj, Type detailType, XmlDictionaryReader detailReader)
{
if (!detailReader.EOF)
{
detailReader.MoveToContent();
if (detailReader.NodeType != XmlNodeType.EndElement && !detailReader.EOF)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.ExtraContentIsPresentInFaultDetail));
}
}
bool isDetailObjectValid = true;
if (detailObj == null)
{
isDetailObjectValid = !detailType.IsValueType();
}
else
{
isDetailObjectValid = detailType.IsAssignableFrom(detailObj.GetType());
}
if (isDetailObjectValid)
{
Type knownFaultType = typeof(FaultException<>).MakeGenericType(detailType);
return (FaultException)Activator.CreateInstance(knownFaultType,
detailObj,
messageFault.Reason,
messageFault.Code,
action);
}
return null;
}
private static FaultContractInfo[] GetSortedArray(List<FaultContractInfo> faultContractInfoList)
{
FaultContractInfo[] temp = faultContractInfoList.ToArray();
Array.Sort(temp,
delegate (FaultContractInfo x, FaultContractInfo y)
{ return string.CompareOrdinal(x.Action, y.Action); }
);
return temp;
}
private static void AddInfrastructureFaults(List<FaultContractInfo> faultContractInfos)
{
faultContractInfos.Add(new FaultContractInfo(FaultCodeConstants.Actions.NetDispatcher, typeof(ExceptionDetail)));
}
private static MessageFault CreateMessageFault(XmlObjectSerializer serializer, FaultException faultException, Type detailType)
{
if (detailType == null)
{
if (faultException.Fault != null)
{
return faultException.Fault;
}
return MessageFault.CreateFault(faultException.Code, faultException.Reason);
}
Fx.Assert(serializer != null, "");
Type operationFaultType = typeof(OperationFault<>).MakeGenericType(detailType);
return (MessageFault)Activator.CreateInstance(operationFaultType, serializer, faultException);
}
/*
This class is not exposed on the contract as we only need it public for reflection purpose on .Net Native.
*/
public class OperationFault<T> : XmlObjectSerializerFault
{
public OperationFault(XmlObjectSerializer serializer, FaultException<T> faultException) :
base(faultException.Code, faultException.Reason,
faultException.Detail,
serializer,
string.Empty/*actor*/,
string.Empty/*node*/)
{
}
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.AWSSupport.Model
{
/// <summary>
/// <para>JSON-formatted object that contains the metadata for a support case. It is contained the response from a DescribeCases request. This
/// structure contains the following fields:</para> <ol> <li> <b>CaseID</b> . String that indicates the AWS Support caseID requested or returned
/// in the call. The caseID is an alphanumeric string formatted as shown in this example CaseId: <i>case-12345678910-2013-c4c1d2bf33c5cf47</i>
/// </li>
/// <li> <b>CategoryCode</b> . Specifies the category of problem for the AWS Support case. Corresponds to the CategoryCode values returned by a
/// call to DescribeServices </li>
/// <li> <b>DisplayId</b> . String that identifies the case on pages in the AWS Support Center</li>
/// <li> <b>Language</b> . Specifies the ISO 639-1 code for the language in which AWS provides support. AWS Support currently supports English
/// and Japanese, for which the codes are <i>en</i> and <i>ja</i> , respectively.</li>
/// <li> <b>RecentCommunications</b> . One ore more Communication data types. Subfields of these structures are Body, CaseId, SubmittedBy, and
/// TimeCreated.</li>
/// <li> <b>NextToken</b> . Defines a resumption point for pagination.</li>
/// <li> <b>ServiceCode</b> . Identifier for the AWS service that corresponds to the service code defined in the call to DescribeServices </li>
/// <li> <b>SeverityCode. </b> Specifies the severity code assigned to the case. Contains one of the values returned by the call to
/// DescribeSeverityLevels </li>
/// <li> <b>Status</b> . Represents the status of your case in the AWS Support Center</li>
/// <li> <b>Subject</b> . Represents the subject line of the case.</li>
/// <li> <b>SubmittedBy</b> .Email address of the account that submitted the case.</li>
/// <li> <b>TimeCreated</b> .Time the case was created, using ISO 8601 format. </li>
/// </ol>
/// </summary>
public class CaseDetails
{
private string caseId;
private string displayId;
private string subject;
private string status;
private string serviceCode;
private string categoryCode;
private string severityCode;
private string submittedBy;
private string timeCreated;
private RecentCaseCommunications recentCommunications;
private List<string> ccEmailAddresses = new List<string>();
private string language;
/// <summary>
/// String that indicates the AWS Support caseID requested or returned in the call. The caseID is an alphanumeric string formatted as shown in
/// this example CaseId: <i>case-12345678910-2013-c4c1d2bf33c5cf47</i>
///
/// </summary>
public string CaseId
{
get { return this.caseId; }
set { this.caseId = value; }
}
/// <summary>
/// Sets the CaseId property
/// </summary>
/// <param name="caseId">The value to set for the CaseId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CaseDetails WithCaseId(string caseId)
{
this.caseId = caseId;
return this;
}
// Check to see if CaseId property is set
internal bool IsSetCaseId()
{
return this.caseId != null;
}
/// <summary>
/// Represents the Id value displayed on pages for the case in AWS Support Center. This is a numeric string.
///
/// </summary>
public string DisplayId
{
get { return this.displayId; }
set { this.displayId = value; }
}
/// <summary>
/// Sets the DisplayId property
/// </summary>
/// <param name="displayId">The value to set for the DisplayId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CaseDetails WithDisplayId(string displayId)
{
this.displayId = displayId;
return this;
}
// Check to see if DisplayId property is set
internal bool IsSetDisplayId()
{
return this.displayId != null;
}
/// <summary>
/// Represents the subject line for a support case in the AWS Support Center user interface.
///
/// </summary>
public string Subject
{
get { return this.subject; }
set { this.subject = value; }
}
/// <summary>
/// Sets the Subject property
/// </summary>
/// <param name="subject">The value to set for the Subject property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CaseDetails WithSubject(string subject)
{
this.subject = subject;
return this;
}
// Check to see if Subject property is set
internal bool IsSetSubject()
{
return this.subject != null;
}
/// <summary>
/// Represents the status of a case submitted to AWS Support.
///
/// </summary>
public string Status
{
get { return this.status; }
set { this.status = value; }
}
/// <summary>
/// Sets the Status property
/// </summary>
/// <param name="status">The value to set for the Status property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CaseDetails WithStatus(string status)
{
this.status = status;
return this;
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this.status != null;
}
/// <summary>
/// Code for the AWS service returned by the call to <a href="API_DescribeServices.html" title="DescribeServices">DescribeServices</a>.
///
/// </summary>
public string ServiceCode
{
get { return this.serviceCode; }
set { this.serviceCode = value; }
}
/// <summary>
/// Sets the ServiceCode property
/// </summary>
/// <param name="serviceCode">The value to set for the ServiceCode property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CaseDetails WithServiceCode(string serviceCode)
{
this.serviceCode = serviceCode;
return this;
}
// Check to see if ServiceCode property is set
internal bool IsSetServiceCode()
{
return this.serviceCode != null;
}
/// <summary>
/// Specifies the category of problem for the AWS Support case.
///
/// </summary>
public string CategoryCode
{
get { return this.categoryCode; }
set { this.categoryCode = value; }
}
/// <summary>
/// Sets the CategoryCode property
/// </summary>
/// <param name="categoryCode">The value to set for the CategoryCode property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CaseDetails WithCategoryCode(string categoryCode)
{
this.categoryCode = categoryCode;
return this;
}
// Check to see if CategoryCode property is set
internal bool IsSetCategoryCode()
{
return this.categoryCode != null;
}
/// <summary>
/// Code for the severity level returned by the call to <a href="API_DescribeSeverityLevels.html"
/// title="DescribeSeverityLevels">DescribeSeverityLevels</a>.
///
/// </summary>
public string SeverityCode
{
get { return this.severityCode; }
set { this.severityCode = value; }
}
/// <summary>
/// Sets the SeverityCode property
/// </summary>
/// <param name="severityCode">The value to set for the SeverityCode property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CaseDetails WithSeverityCode(string severityCode)
{
this.severityCode = severityCode;
return this;
}
// Check to see if SeverityCode property is set
internal bool IsSetSeverityCode()
{
return this.severityCode != null;
}
/// <summary>
/// Represents the email address of the account that submitted the case to support.
///
/// </summary>
public string SubmittedBy
{
get { return this.submittedBy; }
set { this.submittedBy = value; }
}
/// <summary>
/// Sets the SubmittedBy property
/// </summary>
/// <param name="submittedBy">The value to set for the SubmittedBy property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CaseDetails WithSubmittedBy(string submittedBy)
{
this.submittedBy = submittedBy;
return this;
}
// Check to see if SubmittedBy property is set
internal bool IsSetSubmittedBy()
{
return this.submittedBy != null;
}
/// <summary>
/// Time that the case was case created in AWS Support Center.
///
/// </summary>
public string TimeCreated
{
get { return this.timeCreated; }
set { this.timeCreated = value; }
}
/// <summary>
/// Sets the TimeCreated property
/// </summary>
/// <param name="timeCreated">The value to set for the TimeCreated property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CaseDetails WithTimeCreated(string timeCreated)
{
this.timeCreated = timeCreated;
return this;
}
// Check to see if TimeCreated property is set
internal bool IsSetTimeCreated()
{
return this.timeCreated != null;
}
/// <summary>
/// Returns up to the five most recent communications between you and AWS Support Center. Includes a <i>nextToken</i> to retrieve the next set
/// of communications.
///
/// </summary>
public RecentCaseCommunications RecentCommunications
{
get { return this.recentCommunications; }
set { this.recentCommunications = value; }
}
/// <summary>
/// Sets the RecentCommunications property
/// </summary>
/// <param name="recentCommunications">The value to set for the RecentCommunications property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CaseDetails WithRecentCommunications(RecentCaseCommunications recentCommunications)
{
this.recentCommunications = recentCommunications;
return this;
}
// Check to see if RecentCommunications property is set
internal bool IsSetRecentCommunications()
{
return this.recentCommunications != null;
}
/// <summary>
/// List of email addresses that are copied in any communication about the case.
///
/// </summary>
public List<string> CcEmailAddresses
{
get { return this.ccEmailAddresses; }
set { this.ccEmailAddresses = value; }
}
/// <summary>
/// Adds elements to the CcEmailAddresses collection
/// </summary>
/// <param name="ccEmailAddresses">The values to add to the CcEmailAddresses collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CaseDetails WithCcEmailAddresses(params string[] ccEmailAddresses)
{
foreach (string element in ccEmailAddresses)
{
this.ccEmailAddresses.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the CcEmailAddresses collection
/// </summary>
/// <param name="ccEmailAddresses">The values to add to the CcEmailAddresses collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CaseDetails WithCcEmailAddresses(IEnumerable<string> ccEmailAddresses)
{
foreach (string element in ccEmailAddresses)
{
this.ccEmailAddresses.Add(element);
}
return this;
}
// Check to see if CcEmailAddresses property is set
internal bool IsSetCcEmailAddresses()
{
return this.ccEmailAddresses.Count > 0;
}
/// <summary>
/// Specifies the ISO 639-1 code for the language in which AWS provides support. AWS Support currently supports English and Japanese, for which
/// the codes are <i>en</i> and <i>ja</i>, respectively.
///
/// </summary>
public string Language
{
get { return this.language; }
set { this.language = value; }
}
/// <summary>
/// Sets the Language property
/// </summary>
/// <param name="language">The value to set for the Language property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CaseDetails WithLanguage(string language)
{
this.language = language;
return this;
}
// Check to see if Language property is set
internal bool IsSetLanguage()
{
return this.language != null;
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using NetTopologySuite.Geometries;
namespace DotSpatial.NTSExtension
{
/// <summary>
/// A float based 3 dimensional vector class, implementing all interesting features of vectors.
/// </summary>
public struct FloatVector3
{
#region Fields
/// <summary>
/// X.
/// </summary>
public float X;
/// <summary>
/// Y.
/// </summary>
public float Y;
/// <summary>
/// Z.
/// </summary>
public float Z;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="FloatVector3"/> struct.
/// Copies the X, Y and Z values from the CoordinateF without doing a conversion.
/// </summary>
/// <param name="coord">X, Y Z.</param>
public FloatVector3(CoordinateF coord)
{
X = coord.X;
Y = coord.Y;
Z = coord.Z;
}
/// <summary>
/// Initializes a new instance of the <see cref="FloatVector3"/> struct with the specified values.
/// </summary>
/// <param name="xValue">X.</param>
/// <param name="yValue">Y.</param>
/// <param name="zValue">Z.</param>
public FloatVector3(float xValue, float yValue, float zValue)
{
X = xValue;
Y = yValue;
Z = zValue;
}
/// <summary>
/// Initializes a new instance of the <see cref="FloatVector3"/> structusing the X, Y and Z values from the coordinate.
/// </summary>
/// <param name="coord">The coordinate to obtain X, Y and Z values from.</param>
public FloatVector3(Coordinate coord)
{
X = Convert.ToSingle(coord.X);
Y = Convert.ToSingle(coord.Y);
Z = Convert.ToSingle(coord.Z);
}
#endregion
#region Properties
/// <summary>
/// Gets the length of the vector.
/// </summary>
public float Length => Convert.ToSingle(Math.Sqrt((X * X) + (Y * Y) + (Z * Z)));
/// <summary>
/// Gets the square of length of this vector.
/// </summary>
public float LengthSq => Convert.ToSingle((X * X) + (Y * Y) + (Z * Z));
#endregion
#region Operators
/// <summary>
/// Adds the vectors lhs and V using vector addition, which adds the corresponding components.
/// </summary>
/// <param name="lhs">One vector to be added.</param>
/// <param name="rhs">A second vector to be added.</param>
/// <returns>The sum of the vectors.</returns>
public static FloatVector3 operator +(FloatVector3 lhs, FloatVector3 rhs)
{
return new FloatVector3
{
X = lhs.X + rhs.X,
Y = lhs.Y + rhs.Y,
Z = lhs.Z + rhs.Z
};
}
/// <summary>
/// Divides the components of vector lhs by the respective components
/// ov vector V and returns the resulting vector.
/// </summary>
/// <param name="lhs">FloatVector3 Dividend (Numbers to be divided).</param>
/// <param name="rhs">FloatVector3 Divisor (Numbers to divide by).</param>
/// <returns>A FloatVector3 quotient of lhs and V.</returns>
/// <remarks>To prevent divide by 0, if a 0 is in V, it will return 0 in the result.</remarks>
public static FloatVector3 operator /(FloatVector3 lhs, FloatVector3 rhs)
{
FloatVector3 result = default(FloatVector3);
if (rhs.X > 0) result.X = lhs.X / rhs.X;
if (rhs.Y > 0) result.Y = lhs.Y / rhs.Y;
if (rhs.Z > 0) result.Z = lhs.Z / rhs.Z;
return result;
}
/// <summary>
/// Multiplies each component of vector lhs by the Scalar value.
/// </summary>
/// <param name="lhs">A vector representing the vector to be multiplied.</param>
/// <param name="scalar">Double, the scalar value to mulitiply the vector components by.</param>
/// <returns>A FloatVector3 representing the vector product of vector lhs and the Scalar.</returns>
/// <exception cref="ArgumentException">Thrown if scalar is 0.</exception>
public static FloatVector3 operator /(FloatVector3 lhs, float scalar)
{
if (scalar == 0) throw new ArgumentException("Divisor cannot be 0.");
return new FloatVector3
{
X = lhs.X / scalar,
Y = lhs.Y / scalar,
Z = lhs.Z / scalar
};
}
/// <summary>
/// Tests two float vectors for equality.
/// </summary>
/// <param name="lhs">The left hand side FloatVector3 to test.</param>
/// <param name="rhs">The right hand side FloatVector3 to test.</param>
/// <returns>Returns true if X, Y and Z are all equal.</returns>
public static bool operator ==(FloatVector3 lhs, FloatVector3 rhs)
{
return lhs.X == rhs.X && lhs.Y == rhs.Y && lhs.Z == rhs.Z;
}
/// <summary>
/// Returns the Cross Product of two vectors lhs and rhs.
/// </summary>
/// <param name="lhs">Vector, the first input vector.</param>
/// <param name="rhs">Vector, the second input vector.</param>
/// <returns>A FloatVector3 containing the cross product of lhs and V.</returns>
public static FloatVector3 operator ^(FloatVector3 lhs, FloatVector3 rhs)
{
return new FloatVector3
{
X = (lhs.Y * rhs.Z) - (lhs.Z * rhs.Y),
Y = (lhs.Z * rhs.X) - (lhs.X * rhs.Z),
Z = (lhs.X * rhs.Y) - (lhs.Y * rhs.X)
};
}
/// <summary>
/// Tests two float vectors for inequality.
/// </summary>
/// <param name="lhs">The left hand side FloatVector3 to test.</param>
/// <param name="rhs">The right hand side FloatVector3 to test.</param>
/// <returns>Returns true if any of X, Y and Z are unequal.</returns>
public static bool operator !=(FloatVector3 lhs, FloatVector3 rhs)
{
return lhs.X != rhs.X || lhs.Y != rhs.Y || lhs.Z != rhs.Z;
}
/// <summary>
/// Returns the Inner Product also known as the dot product of two vectors, lhs and V.
/// </summary>
/// <param name="lhs">The input vector.</param>
/// <param name="rhs">The vector to take the inner product against lhs.</param>
/// <returns>a Double containing the dot product of lhs and V.</returns>
public static float operator *(FloatVector3 lhs, FloatVector3 rhs)
{
return (lhs.X * rhs.X) + (lhs.Y * rhs.Y) + (lhs.Z * rhs.Z);
}
/// <summary>
/// Multiplies the vectors lhs and V using vector multiplication,
/// which adds the corresponding components.
/// </summary>
/// <param name="scalar">A scalar to multpy to the vector.</param>
/// <param name="rhs">A vector to be multiplied.</param>
/// <returns>The scalar product for the vectors.</returns>
public static FloatVector3 operator *(float scalar, FloatVector3 rhs)
{
return new FloatVector3
{
X = scalar * rhs.X,
Y = scalar * rhs.Y,
Z = scalar * rhs.Z
};
}
/// <summary>
/// Multiplies each component of vector lhs by the Scalar value.
/// </summary>
/// <param name="lhs">A vector representing the vector to be multiplied.</param>
/// <param name="scalar">Double, the scalar value to mulitiply the vector components by.</param>
/// <returns>A FloatVector3 representing the vector product of vector lhs and the Scalar.</returns>
public static FloatVector3 operator *(FloatVector3 lhs, float scalar)
{
return new FloatVector3
{
X = lhs.X * scalar,
Y = lhs.Y * scalar,
Z = lhs.Z * scalar
};
}
/// <summary>
/// Subtracts FloatVector3 V from FloatVector3 lhs.
/// </summary>
/// <param name="lhs">A FloatVector3 to subtract from.</param>
/// <param name="rhs">A FloatVector3 to subtract.</param>
/// <returns>The FloatVector3 difference lhs - V.</returns>
public static FloatVector3 operator -(FloatVector3 lhs, FloatVector3 rhs)
{
FloatVector3 result;
result.X = lhs.X - rhs.X;
result.Y = lhs.Y - rhs.Y;
result.Z = lhs.Z - rhs.Z;
return result;
}
#endregion
#region Methods
/// <summary>
/// Adds all the scalar members of the the two vectors.
/// </summary>
/// <param name="lhs">Left hand side.</param>
/// <param name="rhs">Right hand side.</param>
/// <returns>The resulting vector.</returns>
public static FloatVector3 Add(FloatVector3 lhs, FloatVector3 rhs)
{
return new FloatVector3(lhs.X + rhs.X, lhs.Y + rhs.Y, lhs.Z + rhs.Z);
}
/// <summary>
/// Returns the Cross Product of two vectors lhs and V.
/// </summary>
/// <param name="lhs">Vector, the first input vector.</param>
/// <param name="rhs">Vector, the second input vector.</param>
/// <returns>A FloatVector3 containing the cross product of lhs and V.</returns>
public static FloatVector3 CrossProduct(FloatVector3 lhs, FloatVector3 rhs)
{
FloatVector3 result = new FloatVector3
{
X = (lhs.Y * rhs.Z) - (lhs.Z * rhs.Y),
Y = (lhs.Z * rhs.X) - (lhs.X * rhs.Z),
Z = (lhs.X * rhs.Y) - (lhs.Y * rhs.X)
};
return result;
}
/// <summary>
/// Multiplies all the scalar members of the the two vectors.
/// </summary>
/// <param name="lhs">Left hand side.</param>
/// <param name="rhs">Right hand side.</param>
/// <returns>The resulting value.</returns>
public static float Dot(FloatVector3 lhs, FloatVector3 rhs)
{
return (lhs.X * rhs.X) + (lhs.Y * rhs.Y) + (lhs.Z * rhs.Z);
}
/// <summary>
/// Multiplies the source vector by a scalar.
/// </summary>
/// <param name="source">The vector.</param>
/// <param name="scalar">The scalar.</param>
/// <returns>The resulting vector.</returns>
public static FloatVector3 Multiply(FloatVector3 source, float scalar)
{
return new FloatVector3(source.X * scalar, source.Y * scalar, source.Z * scalar);
}
/// <summary>
/// Subtracts all the scalar members of the the two vectors.
/// </summary>
/// <param name="lhs">Left hand side.</param>
/// <param name="rhs">Right hand side.</param>
/// <returns>The resulting vector.</returns>
public static FloatVector3 Subtract(FloatVector3 lhs, FloatVector3 rhs)
{
return new FloatVector3(lhs.X - rhs.X, lhs.Y - rhs.Y, lhs.Z - rhs.Z);
}
/// <summary>
/// Adds the specified v.
/// </summary>
/// <param name="vector">A FloatVector3 to add to this vector.</param>
public void Add(FloatVector3 vector)
{
X += vector.X;
Y += vector.Y;
Z += vector.Z;
}
/// <summary>
/// Tests to see if the specified object has the same X, Y and Z values.
/// </summary>
/// <param name="obj">object to test against.</param>
/// <returns>True, if the X, Y, Z values of the two vectors are equal.</returns>
public override bool Equals(object obj)
{
if (!(obj is FloatVector3)) return false;
FloatVector3 fv = (FloatVector3)obj;
return fv.X == X && fv.Y == Y && fv.Z == Z;
}
/// <summary>
/// Not sure what I should be doing here since Int can't really contain this much info very well.
/// </summary>
/// <returns>The generated hash code.</returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Multiplies this vector by a scalar value.
/// </summary>
/// <param name="scalar">The scalar to multiply by.</param>
public void Multiply(float scalar)
{
X *= scalar;
Y *= scalar;
Z *= scalar;
}
/// <summary>
/// Normalizes the vectors.
/// </summary>
public void Normalize()
{
float length = Length;
X = X / length;
Y = Y / length;
Z = Z / length;
}
/// <summary>
/// Subtracts the specified value.
/// </summary>
/// <param name="vector">A FloatVector3.</param>
public void Subtract(FloatVector3 vector)
{
X -= vector.X;
Y -= vector.Y;
Z -= vector.Z;
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenMetaverse.Messages.Linden;
using OpenMetaverse.Packets;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.ClientStack.Linden;
using OpenSim.Region.CoreModules.Avatar.InstantMessage;
using OpenSim.Region.CoreModules.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups;
using OpenSim.Tests.Common;
namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups.Tests
{
/// <summary>
/// Basic groups module tests
/// </summary>
[TestFixture]
public class GroupsModuleTests : OpenSimTestCase
{
[SetUp]
public override void SetUp()
{
base.SetUp();
uint port = 9999;
uint sslPort = 9998;
// This is an unfortunate bit of clean up we have to do because MainServer manages things through static
// variables and the VM is not restarted between tests.
MainServer.RemoveHttpServer(port);
BaseHttpServer server = new BaseHttpServer(port, false, sslPort, "");
MainServer.AddHttpServer(server);
MainServer.Instance = server;
}
[Test]
public void TestSendAgentGroupDataUpdate()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestScene scene = new SceneHelpers().SetupScene();
IConfigSource configSource = new IniConfigSource();
IConfig config = configSource.AddConfig("Groups");
config.Set("Enabled", true);
config.Set("Module", "GroupsModule");
config.Set("DebugEnabled", true);
GroupsModule gm = new GroupsModule();
EventQueueGetModule eqgm = new EventQueueGetModule();
// We need a capabilities module active so that adding the scene presence creates an event queue in the
// EventQueueGetModule
SceneHelpers.SetupSceneModules(
scene, configSource, gm, new MockGroupsServicesConnector(), new CapabilitiesModule(), eqgm);
ScenePresence sp = SceneHelpers.AddScenePresence(scene, TestHelpers.ParseStem("1"));
gm.SendAgentGroupDataUpdate(sp.ControllingClient);
Hashtable eventsResponse = eqgm.GetEvents(UUID.Zero, sp.UUID);
Assert.That((int)eventsResponse["int_response_code"], Is.EqualTo((int)HttpStatusCode.OK));
// Console.WriteLine("Response [{0}]", (string)eventsResponse["str_response_string"]);
OSDMap rawOsd = (OSDMap)OSDParser.DeserializeLLSDXml((string)eventsResponse["str_response_string"]);
OSDArray eventsOsd = (OSDArray)rawOsd["events"];
bool foundUpdate = false;
foreach (OSD osd in eventsOsd)
{
OSDMap eventOsd = (OSDMap)osd;
if (eventOsd["message"] == "AgentGroupDataUpdate")
foundUpdate = true;
}
Assert.That(foundUpdate, Is.True, "Did not find AgentGroupDataUpdate in response");
// TODO: More checking of more actual event data.
}
[Test]
public void TestSendGroupNotice()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestScene scene = new SceneHelpers().SetupScene();
MessageTransferModule mtm = new MessageTransferModule();
GroupsModule gm = new GroupsModule();
GroupsMessagingModule gmm = new GroupsMessagingModule();
MockGroupsServicesConnector mgsc = new MockGroupsServicesConnector();
IConfigSource configSource = new IniConfigSource();
{
IConfig config = configSource.AddConfig("Messaging");
config.Set("MessageTransferModule", mtm.Name);
}
{
IConfig config = configSource.AddConfig("Groups");
config.Set("Enabled", true);
config.Set("Module", gm.Name);
config.Set("DebugEnabled", true);
config.Set("MessagingModule", gmm.Name);
config.Set("MessagingEnabled", true);
}
SceneHelpers.SetupSceneModules(scene, configSource, mgsc, mtm, gm, gmm);
UUID userId = TestHelpers.ParseTail(0x1);
string subjectText = "newman";
string messageText = "Hello";
string combinedSubjectMessage = string.Format("{0}|{1}", subjectText, messageText);
ScenePresence sp = SceneHelpers.AddScenePresence(scene, TestHelpers.ParseTail(0x1));
TestClient tc = (TestClient)sp.ControllingClient;
UUID groupID = gm.CreateGroup(tc, "group1", null, true, UUID.Zero, 0, true, true, true);
gm.JoinGroupRequest(tc, groupID);
// Create a second user who doesn't want to receive notices
ScenePresence sp2 = SceneHelpers.AddScenePresence(scene, TestHelpers.ParseTail(0x2));
TestClient tc2 = (TestClient)sp2.ControllingClient;
gm.JoinGroupRequest(tc2, groupID);
gm.SetGroupAcceptNotices(tc2, groupID, false, true);
List<GridInstantMessage> spReceivedMessages = new List<GridInstantMessage>();
tc.OnReceivedInstantMessage += im => spReceivedMessages.Add(im);
List<GridInstantMessage> sp2ReceivedMessages = new List<GridInstantMessage>();
tc2.OnReceivedInstantMessage += im => sp2ReceivedMessages.Add(im);
GridInstantMessage noticeIm = new GridInstantMessage();
noticeIm.fromAgentID = userId.Guid;
noticeIm.toAgentID = groupID.Guid;
noticeIm.message = combinedSubjectMessage;
noticeIm.dialog = (byte)InstantMessageDialog.GroupNotice;
tc.HandleImprovedInstantMessage(noticeIm);
Assert.That(spReceivedMessages.Count, Is.EqualTo(1));
Assert.That(spReceivedMessages[0].message, Is.EqualTo(combinedSubjectMessage));
List<GroupNoticeData> notices = mgsc.GetGroupNotices(UUID.Zero, groupID);
Assert.AreEqual(1, notices.Count);
// OpenSimulator (possibly also SL) transport the notice ID as the session ID!
Assert.AreEqual(notices[0].NoticeID.Guid, spReceivedMessages[0].imSessionID);
Assert.That(sp2ReceivedMessages.Count, Is.EqualTo(0));
}
/// <summary>
/// Run test with the MessageOnlineUsersOnly flag set.
/// </summary>
[Test]
public void TestSendGroupNoticeOnlineOnly()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
TestScene scene = new SceneHelpers().SetupScene();
MessageTransferModule mtm = new MessageTransferModule();
GroupsModule gm = new GroupsModule();
GroupsMessagingModule gmm = new GroupsMessagingModule();
IConfigSource configSource = new IniConfigSource();
{
IConfig config = configSource.AddConfig("Messaging");
config.Set("MessageTransferModule", mtm.Name);
}
{
IConfig config = configSource.AddConfig("Groups");
config.Set("Enabled", true);
config.Set("Module", gm.Name);
config.Set("DebugEnabled", true);
config.Set("MessagingModule", gmm.Name);
config.Set("MessagingEnabled", true);
config.Set("MessageOnlineUsersOnly", true);
}
SceneHelpers.SetupSceneModules(scene, configSource, new MockGroupsServicesConnector(), mtm, gm, gmm);
UUID userId = TestHelpers.ParseTail(0x1);
string subjectText = "newman";
string messageText = "Hello";
string combinedSubjectMessage = string.Format("{0}|{1}", subjectText, messageText);
ScenePresence sp = SceneHelpers.AddScenePresence(scene, TestHelpers.ParseTail(0x1));
TestClient tc = (TestClient)sp.ControllingClient;
UUID groupID = gm.CreateGroup(tc, "group1", null, true, UUID.Zero, 0, true, true, true);
gm.JoinGroupRequest(tc, groupID);
// Create a second user who doesn't want to receive notices
ScenePresence sp2 = SceneHelpers.AddScenePresence(scene, TestHelpers.ParseTail(0x2));
TestClient tc2 = (TestClient)sp2.ControllingClient;
gm.JoinGroupRequest(tc2, groupID);
gm.SetGroupAcceptNotices(tc2, groupID, false, true);
List<GridInstantMessage> spReceivedMessages = new List<GridInstantMessage>();
tc.OnReceivedInstantMessage += im => spReceivedMessages.Add(im);
List<GridInstantMessage> sp2ReceivedMessages = new List<GridInstantMessage>();
tc2.OnReceivedInstantMessage += im => sp2ReceivedMessages.Add(im);
GridInstantMessage noticeIm = new GridInstantMessage();
noticeIm.fromAgentID = userId.Guid;
noticeIm.toAgentID = groupID.Guid;
noticeIm.message = combinedSubjectMessage;
noticeIm.dialog = (byte)InstantMessageDialog.GroupNotice;
tc.HandleImprovedInstantMessage(noticeIm);
Assert.That(spReceivedMessages.Count, Is.EqualTo(1));
Assert.That(spReceivedMessages[0].message, Is.EqualTo(combinedSubjectMessage));
Assert.That(sp2ReceivedMessages.Count, Is.EqualTo(0));
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers
{
internal class AttributeNamedParameterCompletionProvider : AbstractCompletionProvider
{
private const string EqualsString = "=";
private const string SpaceEqualsString = " =";
private const string ColonString = ":";
public override bool IsCommitCharacter(CompletionItem completionItem, char ch, string textTypedSoFar)
{
return CompletionUtilities.IsCommitCharacter(completionItem, ch, textTypedSoFar);
}
public override bool SendEnterThroughToEditor(CompletionItem completionItem, string textTypedSoFar)
{
return CompletionUtilities.SendEnterThroughToEditor(completionItem, textTypedSoFar);
}
public override bool IsTriggerCharacter(SourceText text, int characterPosition, OptionSet options)
{
return CompletionUtilities.IsTriggerCharacter(text, characterPosition, options);
}
public override TextChange GetTextChange(CompletionItem selectedItem, char? ch = null, string textTypedSoFar = null)
{
var displayText = selectedItem.DisplayText;
if (ch != null)
{
// If user types a space, do not complete the " =" (space and equals) at the end of a named parameter. The
// typed space character will be passed through to the editor, and they can then type the '='.
if (ch == ' ' && displayText.EndsWith(SpaceEqualsString, StringComparison.Ordinal))
{
return new TextChange(selectedItem.FilterSpan, displayText.Remove(displayText.Length - SpaceEqualsString.Length));
}
// If the user types '=', do not complete the '=' at the end of the named parameter because the typed '='
// will be passed through to the editor.
if (ch == '=' && displayText.EndsWith(EqualsString, StringComparison.Ordinal))
{
return new TextChange(selectedItem.FilterSpan, displayText.Remove(displayText.Length - EqualsString.Length));
}
// If the user types ':', do not complete the ':' at the end of the named parameter because the typed ':'
// will be passed through to the editor.
if (ch == ':' && displayText.EndsWith(ColonString, StringComparison.Ordinal))
{
return new TextChange(selectedItem.FilterSpan, displayText.Remove(displayText.Length - ColonString.Length));
}
}
return new TextChange(selectedItem.FilterSpan, displayText);
}
protected override async Task<bool> IsExclusiveAsync(Document document, int caretPosition, CompletionTriggerInfo triggerInfo, CancellationToken cancellationToken)
{
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var token = syntaxTree.FindTokenOnLeftOfPosition(caretPosition, cancellationToken)
.GetPreviousTokenIfTouchingWord(caretPosition);
return IsAfterNameColonArgument(token) || IsAfterNameEqualsArgument(token);
}
private bool IsAfterNameColonArgument(SyntaxToken token)
{
var argumentList = token.Parent as AttributeArgumentListSyntax;
if (token.Kind() == SyntaxKind.CommaToken && argumentList != null)
{
foreach (var item in argumentList.Arguments.GetWithSeparators())
{
if (item.IsToken && item.AsToken() == token)
{
return false;
}
if (item.IsNode)
{
var node = item.AsNode() as AttributeArgumentSyntax;
if (node.NameColon != null)
{
return true;
}
}
}
}
return false;
}
private bool IsAfterNameEqualsArgument(SyntaxToken token)
{
var argumentList = token.Parent as AttributeArgumentListSyntax;
if (token.Kind() == SyntaxKind.CommaToken && argumentList != null)
{
foreach (var item in argumentList.Arguments.GetWithSeparators())
{
if (item.IsToken && item.AsToken() == token)
{
return false;
}
if (item.IsNode)
{
var node = item.AsNode() as AttributeArgumentSyntax;
if (node.NameEquals != null)
{
return true;
}
}
}
}
return false;
}
protected override async Task<IEnumerable<CompletionItem>> GetItemsWorkerAsync(
Document document, int position, CompletionTriggerInfo triggerInfo, CancellationToken cancellationToken)
{
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
if (syntaxTree.IsInNonUserCode(position, cancellationToken))
{
return null;
}
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
token = token.GetPreviousTokenIfTouchingWord(position);
if (token.Kind() != SyntaxKind.OpenParenToken && token.Kind() != SyntaxKind.CommaToken)
{
return null;
}
var attributeArgumentList = token.Parent as AttributeArgumentListSyntax;
var attributeSyntax = token.Parent.Parent as AttributeSyntax;
if (attributeSyntax == null || attributeArgumentList == null)
{
return null;
}
// We actually want to collect two sets of named parameters to present the user. The
// normal named parameters that come from the attribute constructors. These will be
// presented like "foo:". And also the named parameters that come from the writable
// fields/properties in the attribute. These will be presented like "bar =".
var existingNamedParameters = GetExistingNamedParameters(attributeArgumentList, position);
var workspace = document.Project.Solution.Workspace;
var semanticModel = await document.GetSemanticModelForNodeAsync(attributeSyntax, cancellationToken).ConfigureAwait(false);
var nameColonItems = await GetNameColonItemsAsync(workspace, semanticModel, position, token, attributeSyntax, existingNamedParameters, cancellationToken).ConfigureAwait(false);
var nameEqualsItems = await GetNameEqualsItemsAsync(workspace, semanticModel, position, token, attributeSyntax, existingNamedParameters, cancellationToken).ConfigureAwait(false);
// If we're after a name= parameter, then we only want to show name= parameters.
if (IsAfterNameEqualsArgument(token))
{
return nameEqualsItems;
}
return nameColonItems.Concat(nameEqualsItems);
}
private async Task<IEnumerable<CompletionItem>> GetNameEqualsItemsAsync(Workspace workspace, SemanticModel semanticModel,
int position, SyntaxToken token, AttributeSyntax attributeSyntax, ISet<string> existingNamedParameters,
CancellationToken cancellationToken)
{
var attributeNamedParameters = GetAttributeNamedParameters(semanticModel, position, attributeSyntax, cancellationToken);
var unspecifiedNamedParameters = attributeNamedParameters.Where(p => !existingNamedParameters.Contains(p.Name));
var text = await semanticModel.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
return
from p in attributeNamedParameters
where !existingNamedParameters.Contains(p.Name)
select new CSharpCompletionItem(
workspace,
this,
p.Name.ToIdentifierToken().ToString() + SpaceEqualsString,
CompletionUtilities.GetTextChangeSpan(text, position),
CommonCompletionUtilities.CreateDescriptionFactory(workspace, semanticModel, token.SpanStart, p),
p.GetGlyph(),
sortText: p.Name);
}
private async Task<IEnumerable<CompletionItem>> GetNameColonItemsAsync(
Workspace workspace, SemanticModel semanticModel, int position, SyntaxToken token, AttributeSyntax attributeSyntax, ISet<string> existingNamedParameters,
CancellationToken cancellationToken)
{
var parameterLists = GetParameterLists(semanticModel, position, attributeSyntax, cancellationToken);
parameterLists = parameterLists.Where(pl => IsValid(pl, existingNamedParameters));
var text = await semanticModel.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
return
from pl in parameterLists
from p in pl
where !existingNamedParameters.Contains(p.Name)
select new CSharpCompletionItem(
workspace,
this,
p.Name.ToIdentifierToken().ToString() + ColonString,
CompletionUtilities.GetTextChangeSpan(text, position),
CommonCompletionUtilities.CreateDescriptionFactory(workspace, semanticModel, token.SpanStart, p),
p.GetGlyph(),
sortText: p.Name);
}
private bool IsValid(ImmutableArray<IParameterSymbol> parameterList, ISet<string> existingNamedParameters)
{
return existingNamedParameters.Except(parameterList.Select(p => p.Name)).IsEmpty();
}
private ISet<string> GetExistingNamedParameters(AttributeArgumentListSyntax argumentList, int position)
{
var existingArguments1 =
argumentList.Arguments.Where(a => a.Span.End <= position)
.Where(a => a.NameColon != null)
.Select(a => a.NameColon.Name.Identifier.ValueText);
var existingArguments2 =
argumentList.Arguments.Where(a => a.Span.End <= position)
.Where(a => a.NameEquals != null)
.Select(a => a.NameEquals.Name.Identifier.ValueText);
return existingArguments1.Concat(existingArguments2).ToSet();
}
private IEnumerable<ImmutableArray<IParameterSymbol>> GetParameterLists(
SemanticModel semanticModel,
int position,
AttributeSyntax attribute,
CancellationToken cancellationToken)
{
var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken);
var attributeType = semanticModel.GetTypeInfo(attribute, cancellationToken).Type as INamedTypeSymbol;
if (within != null && attributeType != null)
{
return attributeType.InstanceConstructors.Where(c => c.IsAccessibleWithin(within))
.Select(c => c.Parameters);
}
return SpecializedCollections.EmptyEnumerable<ImmutableArray<IParameterSymbol>>();
}
private IEnumerable<ISymbol> GetAttributeNamedParameters(
SemanticModel semanticModel,
int position,
AttributeSyntax attribute,
CancellationToken cancellationToken)
{
var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken);
var attributeType = semanticModel.GetTypeInfo(attribute, cancellationToken).Type as INamedTypeSymbol;
return attributeType.GetAttributeNamedParameters(semanticModel.Compilation, within);
}
}
}
| |
//#define ASTAR_POOL_DEBUG //@SHOWINEDITOR Enables debugging of path pooling. Will log warnings and info messages about paths not beeing pooled correctly.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Pathfinding {
/** Base class for all path types */
public abstract class Path {
#if ASTAR_POOL_DEBUG
private string pathTraceInfo = "";
private List<string> claimInfo = new List<string>();
~Path() {
Debug.Log("Destroying " + GetType().Name + " instance");
if (claimed.Count > 0) {
Debug.LogWarning("Pool Is Leaking. See list of claims:\n" +
"Each message below will list what objects are currently claiming the path." +
" These objects have removed their reference to the path object but has not called .Release on it (which is bad).\n" + pathTraceInfo+"\n");
for (int i = 0; i < claimed.Count; i++) {
Debug.LogWarning("- Claim "+ (i+1) + " is by a " + claimed[i].GetType().Name + "\n"+claimInfo[i]);
}
} else {
Debug.Log("Some scripts are not using pooling.\n" + pathTraceInfo + "\n");
}
}
#endif
/** Data for the thread calculating this path */
public PathHandler pathHandler { get; private set; }
/** Callback to call when the path is complete.
* This is usually sent to the Seeker component which post processes the path and then calls a callback to the script which requested the path
*/
public OnPathDelegate callback;
/** Immediate callback to call when the path is complete.
* \warning This may be called from a separate thread. Usually you do not want to use this one.
*
* \see callback
*/
public OnPathDelegate immediateCallback;
#if !ASTAR_LOCK_FREE_PATH_STATE
PathState state;
System.Object stateLock = new object();
#else
int state;
#endif
/** Current state of the path.
* \see #CompleteState
*/
PathCompleteState pathCompleteState;
/** Current state of the path */
public PathCompleteState CompleteState {
get { return pathCompleteState; }
protected set { pathCompleteState = value; }
}
/** If the path failed, this is true.
* \see #errorLog
*/
public bool error { get { return CompleteState == PathCompleteState.Error; } }
/** Additional info on what went wrong.
* \see #error
*/
private string _errorLog = "";
/** Log messages with info about eventual errors. */
public string errorLog {
get { return _errorLog; }
}
/** Holds the path as a Node array. All nodes the path traverses.
* This might not be the same as all nodes the smoothed path traverses.
*/
public List<GraphNode> path;
/** Holds the (perhaps post processed) path as a Vector3 list */
public List<Vector3> vectorPath;
/** The max number of milliseconds per iteration (frame, in case of non-multithreading) */
protected float maxFrameTime;
/** The node currently being processed */
protected PathNode currentR;
/** The duration of this path in ms. How long it took to calculate the path */
public float duration;
/** The number of frames/iterations this path has executed.
* This is the number of frames when not using multithreading.
* When using multithreading, this value is quite irrelevant
*/
public int searchIterations;
/** Number of nodes this path has searched */
public int searchedNodes;
/** When the call was made to start the pathfinding for this path */
public System.DateTime callTime { get; private set; }
/** True if the path is currently pooled.
* Do not set this value. Only read. It is used internally.
*
* \see PathPool
* \version Was named 'recycled' in 3.7.5 and earlier.
*/
internal bool pooled;
/** True if the path is currently recycled (i.e in the path pool).
* Do not set this value. Only read. It is used internally.
*
* \deprecated Has been renamed to 'pooled' to use more widely underestood terminology
*/
[System.Obsolete("Has been renamed to 'pooled' to use more widely underestood terminology")]
internal bool recycled { get { return pooled; } set { pooled = value; } }
/** True if the Reset function has been called.
* Used to alert users when they are doing something wrong.
*/
protected bool hasBeenReset;
/** Constraint for how to search for nodes */
public NNConstraint nnConstraint = PathNNConstraint.Default;
/** Internal linked list implementation.
* \warning This is used internally by the system. You should never change this.
*/
internal Path next;
/** Determines which heuristic to use */
public Heuristic heuristic;
/** Scale of the heuristic values */
public float heuristicScale = 1F;
/** ID of this path. Used to distinguish between different paths */
public ushort pathID { get; private set; }
/** Target to use for H score calculation. Used alongside #hTarget. */
protected GraphNode hTargetNode;
/** Target to use for H score calculations. \see Pathfinding.Node.H */
protected Int3 hTarget;
/** Which graph tags are traversable.
* This is a bitmask so -1 = all bits set = all tags traversable.
* For example, to set bit 5 to true, you would do
* \code myPath.enabledTags |= 1 << 5; \endcode
* To set it to false, you would do
* \code myPath.enabledTags &= ~(1 << 5); \endcode
*
* The Seeker has a popup field where you can set which tags to use.
* \note If you are using a Seeker. The Seeker will set this value to what is set in the inspector field on StartPath.
* So you need to change the Seeker value via script, not set this value if you want to change it via script.
*
* \see CanTraverse
*/
public int enabledTags = -1;
/** List of zeroes to use as default tag penalties */
static readonly int[] ZeroTagPenalties = new int[32];
/** The tag penalties that are actually used.
* If manualTagPenalties is null, this will be ZeroTagPenalties
* \see tagPenalties
*/
protected int[] internalTagPenalties;
/** Tag penalties set by other scripts
* \see tagPenalties
*/
protected int[] manualTagPenalties;
/** Penalties for each tag.
* Tag 0 which is the default tag, will have added a penalty of tagPenalties[0].
* These should only be positive values since the A* algorithm cannot handle negative penalties.
* \note This array will never be null. If you try to set it to null or with a lenght which is not 32. It will be set to "new int[0]".
*
* \note If you are using a Seeker. The Seeker will set this value to what is set in the inspector field on StartPath.
* So you need to change the Seeker value via script, not set this value if you want to change it via script.
*
* \see Seeker.tagPenalties
*/
public int[] tagPenalties {
get {
return manualTagPenalties;
}
set {
if (value == null || value.Length != 32) {
manualTagPenalties = null;
internalTagPenalties = ZeroTagPenalties;
} else {
manualTagPenalties = value;
internalTagPenalties = value;
}
}
}
/** True for paths that want to search all nodes and not jump over nodes as optimizations.
* This disables Jump Point Search when that is enabled to prevent e.g ConstantPath and FloodPath
* to become completely useless.
*/
public virtual bool FloodingPath {
get {
return false;
}
}
/** Total Length of the path.
* Calculates the total length of the #vectorPath.
* Cache this rather than call this function every time since it will calculate the length every time, not just return a cached value.
* \returns Total length of #vectorPath, if #vectorPath is null positive infinity is returned.
*/
public float GetTotalLength () {
if (vectorPath == null) return float.PositiveInfinity;
float tot = 0;
for (int i = 0; i < vectorPath.Count-1; i++) tot += Vector3.Distance(vectorPath[i], vectorPath[i+1]);
return tot;
}
/** Waits until this path has been calculated and returned.
* Allows for very easy scripting.
* \code
* //In an IEnumerator function
*
* Path p = Seeker.StartPath (transform.position, transform.position + Vector3.forward * 10);
* yield return StartCoroutine (p.WaitForPath ());
*
* //The path is calculated at this stage
* \endcode
* \note Do not confuse this with AstarPath.WaitForPath. This one will wait using yield until it has been calculated
* while AstarPath.WaitForPath will halt all operations until the path has been calculated.
*
* \throws System.InvalidOperationException if the path is not started. Send the path to Seeker.StartPath or AstarPath.StartPath before calling this function.
*
* \see AstarPath.WaitForPath
*/
public IEnumerator WaitForPath () {
if (GetState() == PathState.Created) throw new System.InvalidOperationException("This path has not been started yet");
while (GetState() != PathState.Returned) yield return null;
}
/** Estimated cost from the specified node to the target.
* \see https://en.wikipedia.org/wiki/A*_search_algorithm
*/
public uint CalculateHScore (GraphNode node) {
uint h;
switch (heuristic) {
case Heuristic.Euclidean:
h = (uint)(((GetHTarget() - node.position).costMagnitude)*heuristicScale);
// Inlining this check and the return
// for each case saves an extra jump.
// This code is pretty hot
if (hTargetNode != null) {
h = System.Math.Max(h, AstarPath.active.euclideanEmbedding.GetHeuristic(node.NodeIndex, hTargetNode.NodeIndex));
}
return h;
case Heuristic.Manhattan:
Int3 p2 = node.position;
h = (uint)((System.Math.Abs(hTarget.x-p2.x) + System.Math.Abs(hTarget.y-p2.y) + System.Math.Abs(hTarget.z-p2.z))*heuristicScale);
if (hTargetNode != null) {
h = System.Math.Max(h, AstarPath.active.euclideanEmbedding.GetHeuristic(node.NodeIndex, hTargetNode.NodeIndex));
}
return h;
case Heuristic.DiagonalManhattan:
Int3 p = GetHTarget() - node.position;
p.x = System.Math.Abs(p.x);
p.y = System.Math.Abs(p.y);
p.z = System.Math.Abs(p.z);
int diag = System.Math.Min(p.x, p.z);
int diag2 = System.Math.Max(p.x, p.z);
h = (uint)((((14*diag)/10) + (diag2-diag) + p.y) * heuristicScale);
if (hTargetNode != null) {
h = System.Math.Max(h, AstarPath.active.euclideanEmbedding.GetHeuristic(node.NodeIndex, hTargetNode.NodeIndex));
}
return h;
}
return 0U;
}
/** Returns penalty for the given tag.
* \param tag A value between 0 (inclusive) and 32 (exclusive).
*/
public uint GetTagPenalty (int tag) {
return (uint)internalTagPenalties[tag];
}
public Int3 GetHTarget () {
return hTarget;
}
/** Returns if the node can be traversed.
* This per default equals to if the node is walkable and if the node's tag is included in #enabledTags */
public bool CanTraverse (GraphNode node) {
unchecked { return node.Walkable && (enabledTags >> (int)node.Tag & 0x1) != 0; }
}
public uint GetTraversalCost (GraphNode node) {
#if ASTAR_NO_TRAVERSAL_COST
return 0;
#else
unchecked { return GetTagPenalty((int)node.Tag) + node.Penalty; }
#endif
}
/** May be called by graph nodes to get a special cost for some connections.
* Nodes may call it when PathNode.flag2 is set to true, for example mesh nodes, which have
* a very large area can be marked on the start and end nodes, this method will be called
* to get the actual cost for moving from the start position to its neighbours instead
* of as would otherwise be the case, from the start node's position to its neighbours.
* The position of a node and the actual start point on the node can vary quite a lot.
*
* The default behaviour of this method is to return the previous cost of the connection,
* essentiall making no change at all.
*
* This method should return the same regardless of the order of a and b.
* That is f(a,b) == f(b,a) should hold.
*
* \param a Moving from this node
* \param b Moving to this node
* \param currentCost The cost of moving between the nodes. Return this value if there is no meaningful special cost to return.
*/
public virtual uint GetConnectionSpecialCost (GraphNode a, GraphNode b, uint currentCost) {
return currentCost;
}
/** Returns if this path is done calculating.
* \returns If CompleteState is not PathCompleteState.NotCalculated.
*
* \note The path might not have been returned yet.
*
* \since Added in 3.0.8
*
* \see Seeker.IsDone
*/
public bool IsDone () {
return CompleteState != PathCompleteState.NotCalculated;
}
/** Threadsafe increment of the state */
#if !ASTAR_LOCK_FREE_PATH_STATE
public void AdvanceState (PathState s) {
lock (stateLock) {
state = (PathState)System.Math.Max((int)state, (int)s);
}
}
#else
public void AdvanceState () {
System.Threading.Interlocked.Increment(ref state);
}
#endif
/** Returns the state of the path in the pathfinding pipeline */
public PathState GetState () {
return (PathState)state;
}
/** Appends \a msg to #errorLog and logs \a msg to the console.
* Debug.Log call is only made if AstarPath.logPathResults is not equal to None and not equal to InGame.
* Consider calling Error() along with this call.
*/
// Ugly Code Inc. wrote the below code :D
// What it does is that it disables the LogError function if ASTAR_NO_LOGGING is enabled
// since the DISABLED define will never be enabled
// Ugly way of writing Conditional("!ASTAR_NO_LOGGING")
#if ASTAR_NO_LOGGING
[System.Diagnostics.Conditional("DISABLED")]
#endif
public void LogError (string msg) {
// Optimize for release builds
if (!(!AstarPath.isEditor && AstarPath.active.logPathResults == PathLog.None)) {
_errorLog += msg;
}
if (AstarPath.active.logPathResults != PathLog.None && AstarPath.active.logPathResults != PathLog.InGame) {
//Debug.LogWarning(msg);
}
}
/** Logs an error and calls Error().
* This is called only if something is very wrong or the user is doing something he/she really should not be doing.
*/
public void ForceLogError (string msg) {
Error();
_errorLog += msg;
Debug.LogError(msg);
}
/** Appends a message to the #errorLog.
* Nothing is logged to the console.
*
* \note If AstarPath.logPathResults is PathLog.None and this is a standalone player, nothing will be logged as an optimization.
*/
public void Log (string msg) {
// Optimize for release builds
if (!(!AstarPath.isEditor && AstarPath.active.logPathResults == PathLog.None)) {
_errorLog += msg;
}
}
/** Aborts the path because of an error.
* Sets #error to true.
* This function is called when an error has ocurred (e.g a valid path could not be found).
* \see LogError
*/
public void Error () {
CompleteState = PathCompleteState.Error;
}
/** Does some error checking.
* Makes sure the user isn't using old code paths and that no major errors have been done.
*
* \throws An exception if any errors are found
*/
private void ErrorCheck () {
if (!hasBeenReset) throw new System.Exception("The path has never been reset. Use pooling API or call Reset() after creating the path with the default constructor.");
if (pooled) throw new System.Exception("The path is currently in a path pool. Are you sending the path for calculation twice?");
if (pathHandler == null) throw new System.Exception("Field pathHandler is not set. Please report this bug.");
if (GetState() > PathState.Processing) throw new System.Exception("This path has already been processed. Do not request a path with the same path object twice.");
}
/** Called when the path enters the pool.
* This method should release e.g pooled lists and other pooled resources
* The base version of this method releases vectorPath and path lists.
* Reset() will be called after this function, not before.
* \warning Do not call this function manually.
*/
public virtual void OnEnterPool () {
if (vectorPath != null) Pathfinding.Util.ListPool<Vector3>.Release(vectorPath);
if (path != null) Pathfinding.Util.ListPool<GraphNode>.Release(path);
vectorPath = null;
path = null;
}
/** Reset all values to their default values.
*
* \note All inheriting path types (e.g ConstantPath, RandomPath, etc.) which declare their own variables need to
* override this function, resetting ALL their variables to enable recycling of paths.
* If this is not done, trying to use that path type for pooling might result in weird behaviour.
* The best way is to reset to default values the variables declared in the extended path type and then
* call this base function in inheriting types with base.Reset ().
*
* \warning This function should not be called manually.
*/
public virtual void Reset () {
#if ASTAR_POOL_DEBUG
pathTraceInfo = "This path was got from the pool or created from here (stacktrace):\n";
pathTraceInfo += System.Environment.StackTrace;
#endif
if (System.Object.ReferenceEquals(AstarPath.active, null))
throw new System.NullReferenceException("No AstarPath object found in the scene. " +
"Make sure there is one or do not create paths in Awake");
hasBeenReset = true;
state = (int)PathState.Created;
releasedNotSilent = false;
pathHandler = null;
callback = null;
_errorLog = "";
pathCompleteState = PathCompleteState.NotCalculated;
path = Pathfinding.Util.ListPool<GraphNode>.Claim();
vectorPath = Pathfinding.Util.ListPool<Vector3>.Claim();
currentR = null;
duration = 0;
searchIterations = 0;
searchedNodes = 0;
//calltime
nnConstraint = PathNNConstraint.Default;
next = null;
heuristic = AstarPath.active.heuristic;
heuristicScale = AstarPath.active.heuristicScale;
enabledTags = -1;
tagPenalties = null;
callTime = System.DateTime.UtcNow;
pathID = AstarPath.active.GetNextPathID();
hTarget = Int3.zero;
hTargetNode = null;
}
protected bool HasExceededTime (int searchedNodes, long targetTime) {
return System.DateTime.UtcNow.Ticks >= targetTime;
}
/** List of claims on this path with reference objects */
private List<System.Object> claimed = new List<System.Object>();
/** True if the path has been released with a non-silent call yet.
*
* \see Release
* \see Claim
*/
private bool releasedNotSilent;
/** Claim this path (pooling).
* A claim on a path will ensure that it is not pooled.
* If you are using a path, you will want to claim it when you first get it and then release it when you will not
* use it anymore. When there are no claims on the path, it will be reset and put in a pool.
*
* This is essentially just reference counting.
*
* The object passed to this method is merely used as a way to more easily detect when pooling is not done correctly.
* It can be any object, when used from a movement script you can just pass "this". This class will throw an exception
* if you try to call Claim on the same path twice with the same object (which is usually not what you want) or
* if you try to call Release with an object that has not been used in a Claim call for that path.
* The object passed to the Claim method needs to be the same as the one you pass to this method.
*
* \see Release
* \see Pool
* \see \ref pooling
*/
public void Claim (System.Object o) {
if (System.Object.ReferenceEquals(o, null)) throw new System.ArgumentNullException("o");
for (int i = 0; i < claimed.Count; i++) {
// Need to use ReferenceEquals because it might be called from another thread
if (System.Object.ReferenceEquals(claimed[i], o))
throw new System.ArgumentException("You have already claimed the path with that object ("+o+"). Are you claiming the path with the same object twice?");
}
claimed.Add(o);
#if ASTAR_POOL_DEBUG
claimInfo.Add(o.ToString() + "\n\nClaimed from:\n" + System.Environment.StackTrace);
#endif
}
/** Releases the path silently (pooling).
* \deprecated Use Release(o, true) instead
*/
[System.Obsolete("Use Release(o, true) instead")]
public void ReleaseSilent (System.Object o) {
Release(o, true);
}
/** Releases a path claim (pooling).
* Removes the claim of the path by the specified object.
* When the claim count reaches zero, the path will be pooled, all variables will be cleared and the path will be put in a pool to be used again.
* This is great for memory since less allocations are made.
*
* If the silent parameter is true, this method will remove the claim by the specified object
* but the path will not be pooled if the claim count reches zero unless a Release call (not silent) has been made earlier.
* This is used by the internal pathfinding components such as Seeker and AstarPath so that they will not cause paths to be pooled.
* This enables users to skip the claim/release calls if they want without the path being pooled by the Seeker or AstarPath and
* thus causing strange bugs.
*
* \see Claim
* \see PathPool
*/
public void Release (System.Object o, bool silent = false) {
if (o == null) throw new System.ArgumentNullException("o");
for (int i = 0; i < claimed.Count; i++) {
// Need to use ReferenceEquals because it might be called from another thread
if (System.Object.ReferenceEquals(claimed[i], o)) {
claimed.RemoveAt(i);
#if ASTAR_POOL_DEBUG
claimInfo.RemoveAt(i);
#endif
if (!silent) {
releasedNotSilent = true;
}
if (claimed.Count == 0 && releasedNotSilent) {
PathPool.Pool(this);
}
return;
}
}
if (claimed.Count == 0) {
throw new System.ArgumentException("You are releasing a path which is not claimed at all (most likely it has been pooled already). " +
"Are you releasing the path with the same object ("+o+") twice?" +
"\nCheck out the documentation on path pooling for help.");
}
throw new System.ArgumentException("You are releasing a path which has not been claimed with this object ("+o+"). " +
"Are you releasing the path with the same object twice?\n" +
"Check out the documentation on path pooling for help.");
}
/** Traces the calculated path from the end node to the start.
* This will build an array (#path) of the nodes this path will pass through and also set the #vectorPath array to the #path arrays positions.
* Assumes the #vectorPath and #path are empty and not null (which will be the case for a correctly initialized path).
*/
protected virtual void Trace (PathNode from) {
// Current node we are processing
PathNode c = from;
int count = 0;
while (c != null) {
c = c.parent;
count++;
if (count > 2048) {
Debug.LogWarning("Infinite loop? >2048 node path. Remove this message if you really have that long paths (Path.cs, Trace method)");
break;
}
}
// Ensure capacities for lists
AstarProfiler.StartProfile("Check List Capacities");
if (path.Capacity < count) path.Capacity = count;
if (vectorPath.Capacity < count) vectorPath.Capacity = count;
AstarProfiler.EndProfile();
c = from;
for (int i = 0; i < count; i++) {
path.Add(c.node);
c = c.parent;
}
// Reverse
int half = count/2;
for (int i = 0; i < half; i++) {
var tmp = path[i];
path[i] = path[count-i-1];
path[count - i - 1] = tmp;
}
for (int i = 0; i < count; i++) {
vectorPath.Add((Vector3)path[i].position);
}
}
/** Writes text shared for all overrides of DebugString to the string builder.
* \see DebugString
*/
protected void DebugStringPrefix (PathLog logMode, System.Text.StringBuilder text) {
text.Append(error ? "Path Failed : " : "Path Completed : ");
text.Append("Computation Time ");
text.Append(duration.ToString(logMode == PathLog.Heavy ? "0.000 ms " : "0.00 ms "));
text.Append("Searched Nodes ").Append(searchedNodes);
if (!error) {
text.Append(" Path Length ");
text.Append(path == null ? "Null" : path.Count.ToString());
if (logMode == PathLog.Heavy) {
text.Append("\nSearch Iterations ").Append(searchIterations);
}
}
}
/** Writes text shared for all overrides of DebugString to the string builder.
* \see DebugString
*/
protected void DebugStringSuffix (PathLog logMode, System.Text.StringBuilder text) {
if (error) {
text.Append("\nError: ").Append(errorLog);
}
if (logMode == PathLog.Heavy && !AstarPath.IsUsingMultithreading) {
text.Append("\nCallback references ");
if (callback != null) text.Append(callback.Target.GetType().FullName).AppendLine();
else text.AppendLine("NULL");
}
text.Append("\nPath Number ").Append(pathID).Append(" (unique id)");
}
/** Returns a string with information about it.
* More information is emitted when logMode == Heavy.
* An empty string is returned if logMode == None
* or logMode == OnlyErrors and this path did not fail.
*/
public virtual string DebugString (PathLog logMode) {
if (logMode == PathLog.None || (!error && logMode == PathLog.OnlyErrors)) {
return "";
}
// Get a cached string builder for this thread
System.Text.StringBuilder text = pathHandler.DebugStringBuilder;
text.Length = 0;
DebugStringPrefix(logMode, text);
DebugStringSuffix(logMode, text);
return text.ToString();
}
/** Calls callback to return the calculated path. \see #callback */
public virtual void ReturnPath () {
if (callback != null) {
callback(this);
}
}
/** Prepares low level path variables for calculation.
* Called before a path search will take place.
* Always called before the Prepare, Initialize and CalculateStep functions
*/
internal void PrepareBase (PathHandler pathHandler) {
//Path IDs have overflowed 65K, cleanup is needed
//Since pathIDs are handed out sequentially, we can do this
if (pathHandler.PathID > pathID) {
pathHandler.ClearPathIDs();
}
//Make sure the path has a reference to the pathHandler
this.pathHandler = pathHandler;
//Assign relevant path data to the pathHandler
pathHandler.InitializeForPath(this);
// Make sure that internalTagPenalties is an array which has the length 32
if (internalTagPenalties == null || internalTagPenalties.Length != 32)
internalTagPenalties = ZeroTagPenalties;
try {
ErrorCheck();
} catch (System.Exception e) {
ForceLogError("Exception in path "+pathID+"\n"+e);
}
}
/** Called before the path is started.
* Called right before Initialize
*/
public abstract void Prepare ();
/** Always called after the path has been calculated.
* Guaranteed to be called before other paths have been calculated on
* the same thread.
* Use for cleaning up things like node tagging and similar.
*/
public virtual void Cleanup () {}
/** Initializes the path.
* Sets up the open list and adds the first node to it
*/
public abstract void Initialize ();
/** Calculates the until it is complete or the time has progressed past \a targetTick */
public abstract void CalculateStep (long targetTick);
}
}
| |
/*
* Copyright 2013-2018 Guardtime, Inc.
*
* This file is part of the Guardtime client SDK.
*
* 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, CONDITIONS, OR OTHER LICENSES OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
* "Guardtime" and "KSI" are trademarks or registered trademarks of
* Guardtime, Inc., and no license to trademarks is granted; Guardtime
* reserves and retains all trademark rights.
*/
using System;
using System.Text;
namespace Guardtime.KSI.Utils
{
/// <summary>
/// A generic implementation base for the <a target="_blank" href="http://www.ietf.org/rfc/rfc4648.txt">RFC 4648</a>
/// base-X encoders/decoders.
/// </summary>
public class BaseX
{
/// <summary>
/// The number of data bits encoded per character.
/// </summary>
private readonly int _bits;
/// <summary>
/// The number of characters in a full block in the encoded form.
/// </summary>
private readonly int _block;
/// <summary>
/// A lookup table from values to characters.
/// </summary>
private readonly char[] _chars;
/// <summary>
/// The character used for padding the last block when encoding.
/// </summary>
private readonly char _pad;
/// <summary>
/// A lookup table from character code points to values. A value of -1 in the
/// table indicates the corresponding character is not used in the encoded
/// form. The indices {@code 0..values.length-1} correspond to code points
/// {@code min..max}.
/// </summary>
private readonly int[] _values;
/// <summary>
/// The highest code point used in the encoded form.
/// </summary>
private int _max;
/// <summary>
/// The lowest code point used in the encoded form.
/// </summary>
private int _min;
/// <summary>
/// Create base converting instance.
/// </summary>
/// <param name="alphabet">base alphabet</param>
/// <param name="caseSensitive">is base conversion case sensitive</param>
/// <param name="padding">padding</param>
public BaseX(string alphabet, bool caseSensitive, char padding)
{
// the bit and byte counts
_bits = 1;
while ((1 << _bits) < alphabet.Length)
{
_bits++;
}
if ((1 << _bits) != alphabet.Length)
{
throw new ArgumentException("The size of the encoding alphabet is not a power of 2", nameof(alphabet));
}
_block = 8 / Util.GetGreatestCommonDivisor(8, _bits);
// the encoding lookup table
_chars = alphabet.ToCharArray();
// the decoding lookup table
_min = -1;
_max = -1;
if (caseSensitive)
{
AddMinMax(alphabet);
_values = new int[_max - _min + 1];
Util.ArrayFill(_values, -1);
AddChars(alphabet);
}
else
{
AddMinMax(alphabet.ToUpper());
AddMinMax(alphabet.ToLower());
_values = new int[_max - _min + 1];
Util.ArrayFill(_values, -1);
AddChars(alphabet.ToUpper());
AddChars(alphabet.ToLower());
}
// the padding
if (padding >= _min && padding <= _max && _values[padding - _min] != -1)
{
throw new ArgumentException("The padding character appears in the encoding alphabet", nameof(padding));
}
_pad = padding;
}
private void AddMinMax(string chars)
{
if (chars == null)
{
throw new ArgumentNullException(nameof(chars));
}
for (int i = 0; i < chars.Length; i++)
{
int c = chars[i];
if (_min == -1 || _min > c)
{
_min = c;
}
if (_max == -1 || _max < c)
{
_max = c;
}
}
}
private void AddChars(string chars)
{
if (chars == null)
{
throw new ArgumentNullException(nameof(chars));
}
for (int i = 0; i < chars.Length; i++)
{
int c = chars[i] - _min;
if (_values[c] != -1 && _values[c] != i)
{
throw new ArgumentException("Duplicate characters in the encoding alphapbet", nameof(chars));
}
_values[c] = i;
}
}
/// <summary>
/// Encode bytes in given base.
/// </summary>
/// <param name="bytes">data bytes</param>
/// <param name="sep">separator</param>
/// <param name="freq">frequency</param>
/// <returns>bytes string representation in given base</returns>
public string Encode(byte[] bytes, string sep, int freq)
{
return Encode(bytes, 0, bytes.Length, sep, freq);
}
/// <summary>
/// Encode bytes in given base.
/// </summary>
/// <param name="bytes">data bytes</param>
/// <param name="off">offset</param>
/// <param name="len">length</param>
/// <param name="sep">separator</param>
/// <param name="freq">frequency</param>
/// <returns>bytes string representation in given base</returns>
public string Encode(byte[] bytes, int off, int len, string sep, int freq)
{
// sanitize the parameters
if (bytes == null)
{
throw new ArgumentNullException(nameof(bytes));
}
if (off < 0 || len < 0 || off + len < 0 || off + len > bytes.Length)
{
throw new ArgumentOutOfRangeException();
}
if (sep == null)
{
freq = 0;
}
else
{
for (int i = 0; i < sep.Length; i++)
{
int c = sep[i];
if (c >= _min && c <= _max && _values[c - _min] != -1)
{
throw new ArgumentException("The separator contains characters from the encoding alphabet");
}
}
}
// create the output buffer
int outLen = (8 * len + _bits - 1) / _bits;
outLen = (outLen + _block - 1) / _block * _block;
if (freq > 0)
{
if (sep != null)
{
outLen += (outLen - 1) / freq * sep.Length;
}
}
StringBuilder builder = new StringBuilder(outLen);
// encode
int outCount = 0; // number of output characters produced
int inCount = 0; // number of input bytes consumed
int buf = 0; // buffer of input bits not yet sent to output
int bufBits = 0; // number of bits in the bit buffer
int bufMask = (1 << _bits) - 1;
while (_bits * outCount < 8 * len)
{
if (freq > 0 && outCount > 0 && outCount % freq == 0)
{
builder.Append(sep);
}
// fetch the next byte(s), padding with zero bits as needed
while (bufBits < _bits)
{
int next = inCount < len ? bytes[off + inCount] : 0;
inCount++;
buf = (buf << 8) | (next & 0xff); // we want unsigned bytes
bufBits += 8;
}
// output the top bits from the bit buffer
builder.Append(_chars[(buf >> (bufBits - _bits)) & bufMask]);
bufBits -= _bits;
outCount++;
}
// pad
while (outCount % _block != 0)
{
if (freq > 0 && outCount > 0 && outCount % freq == 0)
{
builder.Append(sep);
}
builder.Append(_pad);
outCount++;
}
return builder.ToString();
}
/// <summary>
/// Decode string base representation.
/// </summary>
/// <param name="s">base string</param>
/// <returns>base decoded byte array</returns>
public byte[] Decode(string s)
{
// sanitize the parameters
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
// create the result buffer
byte[] outputBytes = new byte[s.Length * _bits / 8];
// decode
int outCount = 0; // number of output bytes produced
int inCount = 0; // number of input characters consumed
int buf = 0; // buffer of input bits not yet sent to output
int bufBits = 0; // number of bits in the bit buffer
while (inCount < s.Length)
{
int next = s[inCount];
inCount++;
if (next < _min || next > _max)
{
continue;
}
next = _values[next - _min];
if (next == -1)
{
continue;
}
buf = (buf << _bits) | next;
bufBits += _bits;
while (bufBits >= 8)
{
outputBytes[outCount] = (byte)((buf >> (bufBits - 8)) & 0xff);
bufBits -= 8;
outCount++;
}
}
// trim the result if there were any skipped characters
return outCount >= outputBytes.Length ? outputBytes : Util.Clone(outputBytes, 0, outCount);
}
}
}
| |
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Xml;
/// <summary>
/// WSSecurityBasedCredentials is the base class for all credential classes using WS-Security.
/// </summary>
public abstract class WSSecurityBasedCredentials : ExchangeCredentials
{
// The WS-Addressing headers format string to use for adding the WS-Addressing headers.
// Fill-Ins: {0} = Web method name; {1} = EWS URL
internal const string WsAddressingHeadersFormat =
"<wsa:Action soap:mustUnderstand='1'>http://schemas.microsoft.com/exchange/services/2006/messages/{0}</wsa:Action>" +
"<wsa:ReplyTo><wsa:Address>http://www.w3.org/2005/08/addressing/anonymous</wsa:Address></wsa:ReplyTo>" +
"<wsa:To soap:mustUnderstand='1'>{1}</wsa:To>";
// The WS-Security header format string to use for adding the WS-Security header.
// Fill-Ins:
// {0} = EncryptedData block (the token)
internal const string WsSecurityHeaderFormat =
"<wsse:Security soap:mustUnderstand='1'>" +
" {0}" + // EncryptedData (token)
"</wsse:Security>";
internal const string WsuTimeStampFormat =
"<wsu:Timestamp>" +
"<wsu:Created>{0:yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'}</wsu:Created>" +
"<wsu:Expires>{1:yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'}</wsu:Expires>" +
"</wsu:Timestamp>";
/// <summary>
/// Path suffix for WS-Security endpoint.
/// </summary>
internal const string WsSecurityPathSuffix = "/wssecurity";
private readonly bool addTimestamp;
private static XmlNamespaceManager namespaceManager;
private string securityToken;
private Uri ewsUrl;
/// <summary>
/// Initializes a new instance of the <see cref="WSSecurityBasedCredentials"/> class.
/// </summary>
internal WSSecurityBasedCredentials()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WSSecurityBasedCredentials"/> class.
/// </summary>
/// <param name="securityToken">The security token.</param>
internal WSSecurityBasedCredentials(string securityToken)
{
this.securityToken = securityToken;
}
/// <summary>
/// Initializes a new instance of the <see cref="WSSecurityBasedCredentials"/> class.
/// </summary>
/// <param name="securityToken">The security token.</param>
/// <param name="addTimestamp">Timestamp should be added.</param>
internal WSSecurityBasedCredentials(string securityToken, bool addTimestamp)
{
this.securityToken = securityToken;
this.addTimestamp = addTimestamp;
}
/// <summary>
/// This method is called to pre-authenticate credentials before a service request is made.
/// </summary>
internal override void PreAuthenticate()
{
// Nothing special to do here.
}
/// <summary>
/// Emit the extra namespace aliases used for WS-Security and WS-Addressing.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void EmitExtraSoapHeaderNamespaceAliases(XmlWriter writer)
{
writer.WriteAttributeString(
"xmlns",
EwsUtilities.WSSecuritySecExtNamespacePrefix,
null,
EwsUtilities.WSSecuritySecExtNamespace);
writer.WriteAttributeString(
"xmlns",
EwsUtilities.WSAddressingNamespacePrefix,
null,
EwsUtilities.WSAddressingNamespace);
}
/// <summary>
/// Serialize the WS-Security and WS-Addressing SOAP headers.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="webMethodName">The Web method being called.</param>
internal override void SerializeExtraSoapHeaders(XmlWriter writer, string webMethodName)
{
this.SerializeWSAddressingHeaders(writer, webMethodName);
this.SerializeWSSecurityHeaders(writer);
}
/// <summary>
/// Creates the WS-Addressing headers necessary to send with an outgoing request.
/// </summary>
/// <param name="xmlWriter">The XML writer to serialize the headers to.</param>
/// <param name="webMethodName">Web method being called</param>
private void SerializeWSAddressingHeaders(XmlWriter xmlWriter, string webMethodName)
{
EwsUtilities.Assert(
webMethodName != null,
"WSSecurityBasedCredentials.SerializeWSAddressingHeaders",
"Web method name cannot be null!");
EwsUtilities.Assert(
this.ewsUrl != null,
"WSSecurityBasedCredentials.SerializeWSAddressingHeaders",
"EWS Url cannot be null!");
// Format the WS-Addressing headers.
string wsAddressingHeaders = String.Format(
WSSecurityBasedCredentials.WsAddressingHeadersFormat,
webMethodName,
this.ewsUrl);
// And write them out...
xmlWriter.WriteRaw(wsAddressingHeaders);
}
/// <summary>
/// Creates the WS-Security header necessary to send with an outgoing request.
/// </summary>
/// <param name="xmlWriter">The XML writer to serialize the header to.</param>
internal override void SerializeWSSecurityHeaders(XmlWriter xmlWriter)
{
EwsUtilities.Assert(
this.securityToken != null,
"WSSecurityBasedCredentials.SerializeWSSecurityHeaders",
"Security token cannot be null!");
// <wsu:Timestamp wsu:Id="_timestamp">
// <wsu:Created>2007-09-20T01:13:10.468Z</wsu:Created>
// <wsu:Expires>2007-09-20T01:18:10.468Z</wsu:Expires>
// </wsu:Timestamp>
//
string timestamp = null;
if (this.addTimestamp)
{
DateTime utcNow = DateTime.UtcNow;
timestamp = string.Format(
WSSecurityBasedCredentials.WsuTimeStampFormat,
utcNow,
utcNow.AddMinutes(5));
}
// Format the WS-Security header based on all the information we have.
string wsSecurityHeader = String.Format(
WSSecurityBasedCredentials.WsSecurityHeaderFormat,
timestamp + this.securityToken);
// And write the header out...
xmlWriter.WriteRaw(wsSecurityHeader);
}
/// <summary>
/// Adjusts the URL based on the credentials.
/// </summary>
/// <param name="url">The URL.</param>
/// <returns>Adjust URL.</returns>
internal override Uri AdjustUrl(Uri url)
{
return new Uri(GetUriWithoutSuffix(url) + WSSecurityBasedCredentials.WsSecurityPathSuffix);
}
/// <summary>
/// Gets or sets the security token.
/// </summary>
internal string SecurityToken
{
get { return this.securityToken; }
set { this.securityToken = value; }
}
/// <summary>
/// Gets or sets the EWS URL.
/// </summary>
internal Uri EwsUrl
{
get { return this.ewsUrl; }
set { this.ewsUrl = value; }
}
/// <summary>
/// Gets the XmlNamespaceManager which is used to select node during signing the message.
/// </summary>
internal static XmlNamespaceManager NamespaceManager
{
get
{
if (namespaceManager == null)
{
namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace(EwsUtilities.WSSecurityUtilityNamespacePrefix, EwsUtilities.WSSecurityUtilityNamespace);
namespaceManager.AddNamespace(EwsUtilities.WSAddressingNamespacePrefix, EwsUtilities.WSAddressingNamespace);
namespaceManager.AddNamespace(EwsUtilities.EwsSoapNamespacePrefix, EwsUtilities.EwsSoapNamespace);
namespaceManager.AddNamespace(EwsUtilities.EwsTypesNamespacePrefix, EwsUtilities.EwsTypesNamespace);
namespaceManager.AddNamespace(EwsUtilities.WSSecuritySecExtNamespacePrefix, EwsUtilities.WSSecuritySecExtNamespace);
}
return namespaceManager;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------
// <copyright file="UsingTaskCollection_Tests.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>Baseline Regression Tests for v9 OM Public Interface Compatibility: UsingTaskCollection Class</summary>
//-----------------------------------------------------------------------
using System;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using NUnit.Framework;
using Microsoft.Build.BuildEngine;
using Microsoft.Build.Framework;
using Microsoft.Build.UnitTests;
namespace Microsoft.Build.UnitTests.OM.OrcasCompatibility
{
/// <summary>
/// Fixture Class for the v9 OM Public Interface Compatibility Tests. UsingTaskCollection Class.
/// Also see Toolset tests in the Project test class.
/// </summary>
[TestFixture]
public class UsingTaskCollection_Tests
{
/// <summary>
/// Imports Cache issue causes xml not to be loaded
/// This is a test case to reproduce some quirkiness found when running tests out of order.
/// </summary>
[Test]
public void ImportsUsingTask()
{
string importPath = String.Empty;
try
{
importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.Content3SimpleTargetsDefaultSpecified);
Project p = new Project();
p.Save(importPath); // required to reproduce
importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.ContentUsingTaskFile);
Project p2 = new Project(); // new Engine() here fixes testcase
p2.AddNewImport(importPath, "true");
object o = p2.EvaluatedProperties; // evaluate the import
Assertion.AssertNull(CompatibilityTestHelpers.FindUsingTaskByName("TaskName", p2.UsingTasks)); // fails to find task
}
finally
{
CompatibilityTestHelpers.RemoveFile(importPath);
}
}
/// <summary>
/// Count Test. Increment Count on Import Add in OM
/// </summary>
[Test]
public void Count_IncrementOnAddFile()
{
Project p = new Project(new Engine());
Assertion.AssertEquals(0, p.UsingTasks.Count);
p.AddNewUsingTaskFromAssemblyFile("TaskName", "AssemblyFile.dll");
Assertion.AssertEquals(0, p.UsingTasks.Count);
object o = p.EvaluatedProperties;
Assertion.AssertEquals(1, p.UsingTasks.Count);
}
/// <summary>
/// Count Test. Increment Count on Import Add in OM
/// </summary>
[Test]
public void Count_IncrementOnAddName()
{
Project p = new Project(new Engine());
Assertion.AssertEquals(0, p.UsingTasks.Count);
p.AddNewUsingTaskFromAssemblyName("TaskName", "AssemblyName");
Assertion.AssertEquals(0, p.UsingTasks.Count);
object o = p.EvaluatedProperties;
Assertion.AssertEquals(1, p.UsingTasks.Count);
}
/// <summary>
/// Count Test. Increment Count on Import Add in XML
/// </summary>
[Test]
public void Count_IncrementOnAddFileXml()
{
string projectPath = String.Empty;
try
{
projectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.ContentUsingTaskFile);
Project p = new Project(new Engine());
Assertion.AssertEquals(0, p.UsingTasks.Count);
p.Load(projectPath);
Assertion.AssertEquals(1, p.UsingTasks.Count);
}
finally
{
CompatibilityTestHelpers.RemoveFile(projectPath);
}
}
/// <summary>
/// Count Test. Decrement\Reset Count to 0 on reload project xml
/// </summary>
[Test]
public void Count_DecrementOnRemove()
{
Project p = new Project(new Engine());
p.AddNewUsingTaskFromAssemblyFile("TaskName", "AssemblyFile.dll");
object o = p.EvaluatedProperties;
Assertion.AssertEquals(1, p.UsingTasks.Count);
p.LoadXml(TestData.ContentSimpleTools35);
Assertion.AssertEquals(0, p.UsingTasks.Count);
o = p.EvaluatedProperties;
Assertion.AssertEquals(0, p.UsingTasks.Count);
}
/// <summary>
/// IsSynchronized Test
/// </summary>
[Test]
public void IsSynchronized()
{
Project p = new Project(new Engine());
p.AddNewUsingTaskFromAssemblyFile("TaskName", "AssemblyFile.dll");
Assertion.AssertEquals(false, p.UsingTasks.IsSynchronized);
}
/// <summary>
/// SyncRoot Test, ensure that SyncRoot returns and we can take a lock on it.
/// </summary>
[Test]
public void SyncRoot()
{
Project p = new Project(new Engine());
p.AddNewUsingTaskFromAssemblyFile("TaskName1", "AssemblyFile1.dll");
p.AddNewUsingTaskFromAssemblyFile("TaskName2", "AssemblyFile2.dll");
UsingTask[] usingTasks = new UsingTask[p.UsingTasks.Count];
p.UsingTasks.CopyTo(usingTasks, 0);
lock (p.UsingTasks.SyncRoot)
{
int i = 0;
foreach (UsingTask usingTask in p.UsingTasks)
{
Assertion.AssertEquals(usingTasks[i].AssemblyFile, usingTask.AssemblyFile);
i++;
}
}
}
/// <summary>
/// SyncRoot Test, copy into a strongly typed array and assert content against the source collection.
/// </summary>
[Test]
public void CopyTo_ZeroIndex()
{
Project p = new Project(new Engine());
p.AddNewUsingTaskFromAssemblyFile("TaskName1", "AssemblyFile1.dll");
p.AddNewUsingTaskFromAssemblyFile("TaskName2", "AssemblyFile2.dll");
UsingTask[] usingTasks = new UsingTask[p.UsingTasks.Count];
p.UsingTasks.CopyTo(usingTasks, 0);
int i = 0;
foreach (UsingTask usingTask in p.UsingTasks)
{
Assertion.AssertEquals(usingTasks[i].AssemblyFile, usingTask.AssemblyFile);
i++;
}
}
/// <summary>
/// SyncRoot Test, copy into a strongly typed array and assert content against the source collection.
/// </summary>
[Test]
public void CopyTo_OffsetIndex()
{
int offSet = 3;
Project p = new Project(new Engine());
p.AddNewUsingTaskFromAssemblyFile("TaskName1", "AssemblyFile1.dll");
p.AddNewUsingTaskFromAssemblyFile("TaskName2", "AssemblyFile2.dll");
UsingTask[] taskArray = new UsingTask[p.UsingTasks.Count + offSet];
p.UsingTasks.CopyTo(taskArray, offSet);
int i = offSet - 1;
Assertion.AssertNull(taskArray[offSet - 1]);
foreach (UsingTask usingTask in p.UsingTasks)
{
Assertion.AssertEquals(taskArray[i].AssemblyFile, usingTask.AssemblyFile);
i++;
}
}
/// <summary>
/// SyncRoot Test, copy into a strongly typed array with an offset where the array is too small
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void CopyTo_OffsetIndexArrayTooSmall()
{
int offSet = 3;
Project p = new Project(new Engine());
p.AddNewUsingTaskFromAssemblyFile("TaskName1", "AssemblyFile1.dll");
p.AddNewUsingTaskFromAssemblyFile("TaskName2", "AssemblyFile2.dll");
UsingTask[] usingTasks = new UsingTask[p.UsingTasks.Count];
p.UsingTasks.CopyTo(usingTasks, offSet);
}
/// <summary>
/// Copy to a weakly typed array, no offset. Itterate over collection
/// </summary>
[Test]
public void CopyTo_WeakAndGetEnumerator()
{
Project p = new Project(new Engine());
p.AddNewUsingTaskFromAssemblyFile("TaskName1", "AssemblyFile1.dll");
p.AddNewUsingTaskFromAssemblyFile("TaskName2", "AssemblyFile2.dll");
Array taskArray = Array.CreateInstance(typeof(UsingTask), p.UsingTasks.Count);
p.UsingTasks.CopyTo(taskArray, 0);
Assertion.AssertEquals(p.UsingTasks.Count, taskArray.Length);
int i = 0;
foreach (UsingTask usingTask in p.UsingTasks)
{
Assertion.AssertEquals(((UsingTask)taskArray.GetValue(i)), usingTask.AssemblyFile);
i++;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Text;
using Dbg = System.Management.Automation;
namespace System.Management.Automation
{
/// <summary>
/// Takes as input a collection of strings and builds an expression tree from the input.
/// At the evaluation stage, it walks down the tree and evaluates the result.
/// </summary>
public sealed class FlagsExpression<T> where T : struct, IConvertible
{
#region Constructors
/// <summary>
/// Construct the expression from a single string.
/// </summary>
/// <param name="expression">
/// The specified flag attribute expression string.
/// </param>
public FlagsExpression(string expression)
{
if (!typeof(T).IsEnum)
{
throw InterpreterError.NewInterpreterException(expression, typeof(RuntimeException),
null, "InvalidGenericType", EnumExpressionEvaluatorStrings.InvalidGenericType);
}
_underType = Enum.GetUnderlyingType(typeof(T));
if (string.IsNullOrWhiteSpace(expression))
{
throw InterpreterError.NewInterpreterException(expression, typeof(RuntimeException),
null, "EmptyInputString", EnumExpressionEvaluatorStrings.EmptyInputString);
}
List<Token> tokenList = TokenizeInput(expression);
// Append an OR at the end of the list for construction
tokenList.Add(new Token(TokenKind.Or));
CheckSyntaxError(tokenList);
Root = ConstructExpressionTree(tokenList);
}
/// <summary>
/// Construct the tree from an object collection when arguments are comma separated.
/// If valid, all elements are OR separated.
/// </summary>
/// <param name="expression">
/// The array of specified flag attribute subexpression strings.
/// </param>
public FlagsExpression(object[] expression)
{
if (!typeof(T).IsEnum)
{
throw InterpreterError.NewInterpreterException(expression, typeof(RuntimeException),
null, "InvalidGenericType", EnumExpressionEvaluatorStrings.InvalidGenericType);
}
_underType = Enum.GetUnderlyingType(typeof(T));
if (expression == null)
{
throw InterpreterError.NewInterpreterException(null, typeof(ArgumentNullException),
null, "EmptyInputString", EnumExpressionEvaluatorStrings.EmptyInputString);
}
foreach (string inputClause in expression)
{
if (string.IsNullOrWhiteSpace(inputClause))
{
throw InterpreterError.NewInterpreterException(expression, typeof(RuntimeException),
null, "EmptyInputString", EnumExpressionEvaluatorStrings.EmptyInputString);
}
}
List<Token> tokenList = new List<Token>();
foreach (string orClause in expression)
{
tokenList.AddRange(TokenizeInput(orClause));
tokenList.Add(new Token(TokenKind.Or));
}
// Unnecessary OR at the end not removed for tree construction
Debug.Assert(tokenList.Count > 0, "Input must not all be white characters.");
CheckSyntaxError(tokenList);
Root = ConstructExpressionTree(tokenList);
}
#endregion
#region parser tokens
internal enum TokenKind
{
Identifier,
And,
Or,
Not
}
internal class Token
{
public string Text { get; set; }
public TokenKind Kind { get; set; }
internal Token(TokenKind kind)
{
Kind = kind;
switch (kind)
{
case TokenKind.Or:
Text = "OR";
break;
case TokenKind.And:
Text = "AND";
break;
case TokenKind.Not:
Text = "NOT";
break;
default:
Debug.Fail("Invalid token kind passed in.");
break;
}
}
internal Token(string identifier)
{
Kind = TokenKind.Identifier;
Text = identifier;
}
}
#endregion
#region tree nodes
/// <summary>
/// Abstract base type for other types of nodes in the tree.
/// </summary>
internal abstract class Node
{
// Only used in internal nodes holding operators.
public Node Operand1 { get; set; }
internal abstract bool Eval(object val);
internal abstract bool ExistEnum(object enumVal);
}
/// <summary>
/// OR node for attributes separated by a comma.
/// </summary>
internal class OrNode : Node
{
public Node Operand2 { get; set; }
public OrNode(Node n)
{
Operand2 = n;
}
internal override bool Eval(object val)
{
// bitwise OR
bool satisfy = Operand1.Eval(val) || Operand2.Eval(val);
return satisfy;
}
internal override bool ExistEnum(object enumVal)
{
bool exist = Operand1.ExistEnum(enumVal) || Operand2.ExistEnum(enumVal);
return exist;
}
}
/// <summary>
/// AND node for attributes separated by a plus(+) operator.
/// </summary>
internal class AndNode : Node
{
public Node Operand2 { get; set; }
public AndNode(Node n)
{
Operand2 = n;
}
internal override bool Eval(object val)
{
// bitwise AND
bool satisfy = Operand1.Eval(val) && Operand2.Eval(val);
return satisfy;
}
internal override bool ExistEnum(object enumVal)
{
bool exist = Operand1.ExistEnum(enumVal) || Operand2.ExistEnum(enumVal);
return exist;
}
}
/// <summary>
/// NOT node for attribute preceded by an exclamation(!) operator.
/// </summary>
internal class NotNode : Node
{
internal override bool Eval(object val)
{
// bitwise NOT
bool satisfy = !(Operand1.Eval(val));
return satisfy;
}
internal override bool ExistEnum(object enumVal)
{
bool exist = Operand1.ExistEnum(enumVal);
return exist;
}
}
/// <summary>
/// Leaf nodes of the expression tree.
/// </summary>
internal class OperandNode : Node
{
internal object _operandValue;
public object OperandValue
{
get
{
return _operandValue;
}
set
{
_operandValue = value;
}
}
/// <summary>
/// Takes a string value and converts to corresponding enum value.
/// The string value should be checked at parsing stage prior to
/// tree construction to ensure it is valid.
/// </summary>
internal OperandNode(string enumString)
{
Type enumType = typeof(T);
Type underType = Enum.GetUnderlyingType(enumType);
FieldInfo enumItem = enumType.GetField(enumString);
_operandValue = LanguagePrimitives.ConvertTo(enumItem.GetValue(enumType), underType, CultureInfo.InvariantCulture);
}
internal override bool Eval(object val)
{
Type underType = Enum.GetUnderlyingType(typeof(T));
// bitwise AND checking
bool satisfy = false;
if (isUnsigned(underType))
{
ulong valueToCheck = (ulong)LanguagePrimitives.ConvertTo(val, typeof(ulong), CultureInfo.InvariantCulture);
ulong operandValue = (ulong)LanguagePrimitives.ConvertTo(_operandValue, typeof(ulong), CultureInfo.InvariantCulture);
satisfy = (operandValue == (valueToCheck & operandValue));
}
// allow for negative enum value input (though it's not recommended practice for flags attribute)
else
{
long valueToCheck = (long)LanguagePrimitives.ConvertTo(val, typeof(long), CultureInfo.InvariantCulture);
long operandValue = (long)LanguagePrimitives.ConvertTo(_operandValue, typeof(long), CultureInfo.InvariantCulture);
satisfy = (operandValue == (valueToCheck & operandValue));
}
return satisfy;
}
internal override bool ExistEnum(object enumVal)
{
Type underType = Enum.GetUnderlyingType(typeof(T));
// bitwise AND checking
bool exist = false;
if (isUnsigned(underType))
{
ulong valueToCheck = (ulong)LanguagePrimitives.ConvertTo(enumVal, typeof(ulong), CultureInfo.InvariantCulture);
ulong operandValue = (ulong)LanguagePrimitives.ConvertTo(_operandValue, typeof(ulong), CultureInfo.InvariantCulture);
exist = valueToCheck == (valueToCheck & operandValue);
}
// allow for negative enum value input (though it's not recommended practice for flags attribute)
else
{
long valueToCheck = (long)LanguagePrimitives.ConvertTo(enumVal, typeof(long), CultureInfo.InvariantCulture);
long operandValue = (long)LanguagePrimitives.ConvertTo(_operandValue, typeof(long), CultureInfo.InvariantCulture);
exist = valueToCheck == (valueToCheck & operandValue);
}
return exist;
}
private static bool isUnsigned(Type type)
{
return (type == typeof(ulong) || type == typeof(uint) || type == typeof(ushort) || type == typeof(byte));
}
}
#endregion
#region private members
private readonly Type _underType = null;
#endregion
#region properties
internal Node Root { get; set; } = null;
#endregion
#region public methods
/// <summary>
/// Evaluate a given flag enum value against the expression.
/// </summary>
/// <param name="value">
/// The flag enum value to be evaluated.
/// </param>
/// <returns>
/// Whether the enum value satisfy the expression.
/// </returns>
public bool Evaluate(T value)
{
object val = LanguagePrimitives.ConvertTo(value, _underType, CultureInfo.InvariantCulture);
return Root.Eval(val);
}
#endregion
#region internal methods
/// <summary>
/// Given an enum element, check if the element is present in the expression tree,
/// which is also present in the input expression.
/// </summary>
/// <param name="flagName">
/// The enum element to be examined.
/// </param>
/// <returns>
/// Whether the enum element is present in the expression.
/// </returns>
/// <remarks>
/// The enum value passed in should be a single enum element value,
/// not a flag enum value with multiple bits set.
/// </remarks>
internal bool ExistsInExpression(T flagName)
{
bool exist = false;
object val = LanguagePrimitives.ConvertTo(flagName, _underType, CultureInfo.InvariantCulture);
exist = Root.ExistEnum(val);
return exist;
}
#endregion
#region parser methods
/// <summary>
/// Takes a string of input tokenize into a list of ordered tokens.
/// </summary>
/// <param name="input">
/// The input argument string,
/// could be partial input (one element from the argument collection).
/// </param>
/// <returns>
/// A generic list of tokenized input.
/// </returns>
private static List<Token> TokenizeInput(string input)
{
List<Token> tokenList = new List<Token>();
int _offset = 0;
while (_offset < input.Length)
{
FindNextToken(input, ref _offset);
if (_offset < input.Length)
{
tokenList.Add(GetNextToken(input, ref _offset));
}
}
return tokenList;
}
/// <summary>
/// Find the start of the next token, skipping white spaces.
/// </summary>
/// <param name="input">
/// Input string
/// </param>
/// <param name="_offset">
/// Current offset position for the string parser.
/// </param>
private static void FindNextToken(string input, ref int _offset)
{
while (_offset < input.Length)
{
char cc = input[_offset++];
if (!char.IsWhiteSpace(cc))
{
_offset--;
break;
}
}
}
/// <summary>
/// Given the start (offset) of the next token, traverse through
/// the string to find the next token, stripping correctly
/// enclosed quotes.
/// </summary>
/// <param name="input">
/// Input string
/// </param>
/// <param name="_offset">
/// Current offset position for the string parser.
/// </param>
/// <returns>
/// The next token on the input string
/// </returns>
private static Token GetNextToken(string input, ref int _offset)
{
StringBuilder sb = new StringBuilder();
// bool singleQuoted = false;
// bool doubleQuoted = false;
bool readingIdentifier = false;
while (_offset < input.Length)
{
char cc = input[_offset++];
if ((cc == ',') || (cc == '+') || (cc == '!'))
{
if (!readingIdentifier)
{
sb.Append(cc);
}
else
{
_offset--;
}
break;
}
else
{
sb.Append(cc);
readingIdentifier = true;
}
}
string result = sb.ToString().Trim();
// If resulting identifier is enclosed in paired quotes,
// remove the only the first pair of quotes from the string
if (result.Length >= 2 &&
((result[0] == '\'' && result[result.Length - 1] == '\'') ||
(result[0] == '\"' && result[result.Length - 1] == '\"')))
{
result = result.Substring(1, result.Length - 2);
}
result = result.Trim();
// possible empty token because white spaces are enclosed in quotation marks.
if (string.IsNullOrWhiteSpace(result))
{
throw InterpreterError.NewInterpreterException(input, typeof(RuntimeException),
null, "EmptyTokenString", EnumExpressionEvaluatorStrings.EmptyTokenString,
EnumMinimumDisambiguation.EnumAllValues(typeof(T)));
}
else if (result[0] == '(')
{
int matchIndex = input.IndexOf(')', _offset);
if (result[result.Length - 1] == ')' || matchIndex >= 0)
{
throw InterpreterError.NewInterpreterException(input, typeof(RuntimeException),
null, "NoIdentifierGroupingAllowed", EnumExpressionEvaluatorStrings.NoIdentifierGroupingAllowed);
}
}
if (result.Equals(","))
{
return (new Token(TokenKind.Or));
}
else if (result.Equals("+"))
{
return (new Token(TokenKind.And));
}
else if (result.Equals("!"))
{
return (new Token(TokenKind.Not));
}
else
{
return (new Token(result));
}
}
/// <summary>
/// Checks syntax errors on input expression,
/// as well as performing disambiguation for identifiers.
/// </summary>
/// <param name="tokenList">
/// A list of tokenized input.
/// </param>
private static void CheckSyntaxError(List<Token> tokenList)
{
// Initialize, assuming preceded by OR
TokenKind previous = TokenKind.Or;
for (int i = 0; i < tokenList.Count; i++)
{
Token token = tokenList[i];
// Not allowed: ... AND/OR AND/OR ...
// Allowed: ... AND/OR NOT/ID ...
if (previous == TokenKind.Or || previous == TokenKind.And)
{
if ((token.Kind == TokenKind.Or) || (token.Kind == TokenKind.And))
{
throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException),
null, "SyntaxErrorUnexpectedBinaryOperator", EnumExpressionEvaluatorStrings.SyntaxErrorUnexpectedBinaryOperator);
}
}
// Not allowed: ... NOT AND/OR/NOT ...
// Allowed: ... NOT ID ...
else if (previous == TokenKind.Not)
{
if (token.Kind != TokenKind.Identifier)
{
throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException),
null, "SyntaxErrorIdentifierExpected", EnumExpressionEvaluatorStrings.SyntaxErrorIdentifierExpected);
}
}
// Not allowed: ... ID NOT/ID ...
// Allowed: ... ID AND/OR ...
else if (previous == TokenKind.Identifier)
{
if ((token.Kind == TokenKind.Identifier) || (token.Kind == TokenKind.Not))
{
throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException),
null, "SyntaxErrorBinaryOperatorExpected", EnumExpressionEvaluatorStrings.SyntaxErrorBinaryOperatorExpected);
}
}
if (token.Kind == TokenKind.Identifier)
{
string text = token.Text;
token.Text = EnumMinimumDisambiguation.EnumDisambiguate(text, typeof(T));
}
previous = token.Kind;
}
}
/// <summary>
/// Takes a list of tokenized input and create the corresponding expression tree.
/// </summary>
/// <param name="tokenList">
/// Tokenized list of the input string.
/// </param>
private static Node ConstructExpressionTree(List<Token> tokenList)
{
bool notFlag = false;
Queue<Node> andQueue = new Queue<Node>();
Queue<Node> orQueue = new Queue<Node>();
for (int i = 0; i < tokenList.Count; i++)
{
Token token = tokenList[i];
TokenKind kind = token.Kind;
if (kind == TokenKind.Identifier)
{
Node idNode = new OperandNode(token.Text);
if (notFlag) // identifier preceded by NOT
{
Node notNode = new NotNode();
notNode.Operand1 = idNode;
notFlag = false;
andQueue.Enqueue(notNode);
}
else
{
andQueue.Enqueue(idNode);
}
}
else if (kind == TokenKind.Not)
{
notFlag = true;
}
else if (kind == TokenKind.And)
{
// do nothing
}
else if (kind == TokenKind.Or)
{
// Dequeue all nodes from AND queue,
// create the AND tree, then add to the OR queue.
Node andCurrent = andQueue.Dequeue();
while (andQueue.Count > 0)
{
Node andNode = new AndNode(andCurrent);
andNode.Operand1 = andQueue.Dequeue();
andCurrent = andNode;
}
orQueue.Enqueue(andCurrent);
}
}
// Dequeue all nodes from OR queue,
// create the OR tree (final expression tree)
Node orCurrent = orQueue.Dequeue();
while (orQueue.Count > 0)
{
Node orNode = new OrNode(orCurrent);
orNode.Operand1 = orQueue.Dequeue();
orCurrent = orNode;
}
return orCurrent;
}
#endregion
}
}
| |
using Lucene.Net.Documents;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Linq;
using Console = Lucene.Net.Support.SystemConsole;
namespace Lucene.Net.Search
{
using Lucene.Net.Index;
using Lucene.Net.Randomized.Generators;
using NUnit.Framework;
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using IBits = Lucene.Net.Util.IBits;
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 FixedBitSet = Lucene.Net.Util.FixedBitSet;
using IndexReader = Lucene.Net.Index.IndexReader;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using NumericDocValuesField = NumericDocValuesField;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using SortedDocValuesField = SortedDocValuesField;
using StoredField = StoredField;
using TestUtil = Lucene.Net.Util.TestUtil;
/// <summary>
/// random sorting tests </summary>
[TestFixture]
public class TestSortRandom : LuceneTestCase
{
[Test]
public virtual void TestRandomStringSort()
{
Random random = new Random(Random().Next());
int NUM_DOCS = AtLeast(100);
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random, dir, Similarity, TimeZone);
bool allowDups = random.NextBoolean();
HashSet<string> seen = new HashSet<string>();
int maxLength = TestUtil.NextInt(random, 5, 100);
if (VERBOSE)
{
Console.WriteLine("TEST: NUM_DOCS=" + NUM_DOCS + " maxLength=" + maxLength + " allowDups=" + allowDups);
}
int numDocs = 0;
IList<BytesRef> docValues = new List<BytesRef>();
// TODO: deletions
while (numDocs < NUM_DOCS)
{
Document doc = new Document();
// 10% of the time, the document is missing the value:
BytesRef br;
if (Random().Next(10) != 7)
{
string s;
if (random.NextBoolean())
{
s = TestUtil.RandomSimpleString(random, maxLength);
}
else
{
s = TestUtil.RandomUnicodeString(random, maxLength);
}
if (!allowDups)
{
if (seen.Contains(s))
{
continue;
}
seen.Add(s);
}
if (VERBOSE)
{
Console.WriteLine(" " + numDocs + ": s=" + s);
}
br = new BytesRef(s);
if (DefaultCodecSupportsDocValues())
{
doc.Add(new SortedDocValuesField("stringdv", br));
doc.Add(new NumericDocValuesField("id", numDocs));
}
else
{
doc.Add(NewStringField("id", Convert.ToString(numDocs), Field.Store.NO));
}
doc.Add(NewStringField("string", s, Field.Store.NO));
docValues.Add(br);
}
else
{
br = null;
if (VERBOSE)
{
Console.WriteLine(" " + numDocs + ": <missing>");
}
docValues.Add(null);
if (DefaultCodecSupportsDocValues())
{
doc.Add(new NumericDocValuesField("id", numDocs));
}
else
{
doc.Add(NewStringField("id", Convert.ToString(numDocs), Field.Store.NO));
}
}
doc.Add(new StoredField("id", numDocs));
writer.AddDocument(doc);
numDocs++;
if (random.Next(40) == 17)
{
// force flush
writer.Reader.Dispose();
}
}
IndexReader r = writer.Reader;
writer.Dispose();
if (VERBOSE)
{
Console.WriteLine(" reader=" + r);
}
IndexSearcher idxS = NewSearcher(r, false, Similarity);
int ITERS = AtLeast(100);
for (int iter = 0; iter < ITERS; iter++)
{
bool reverse = random.NextBoolean();
TopFieldDocs hits;
SortField sf;
bool sortMissingLast;
bool missingIsNull;
if (DefaultCodecSupportsDocValues() && random.NextBoolean())
{
sf = new SortField("stringdv", SortFieldType.STRING, reverse);
// Can only use sort missing if the DVFormat
// supports docsWithField:
sortMissingLast = DefaultCodecSupportsDocsWithField() && Random().NextBoolean();
missingIsNull = DefaultCodecSupportsDocsWithField();
}
else
{
sf = new SortField("string", SortFieldType.STRING, reverse);
sortMissingLast = Random().NextBoolean();
missingIsNull = true;
}
if (sortMissingLast)
{
sf.MissingValue = SortField.STRING_LAST;
}
Sort sort;
if (random.NextBoolean())
{
sort = new Sort(sf);
}
else
{
sort = new Sort(sf, SortField.FIELD_DOC);
}
int hitCount = TestUtil.NextInt(random, 1, r.MaxDoc + 20);
RandomFilter f = new RandomFilter(random, (float)random.NextDouble(), docValues);
int queryType = random.Next(3);
if (queryType == 0)
{
// force out of order
BooleanQuery bq = new BooleanQuery();
// Add a Query with SHOULD, since bw.Scorer() returns BooleanScorer2
// which delegates to BS if there are no mandatory clauses.
bq.Add(new MatchAllDocsQuery(), Occur.SHOULD);
// Set minNrShouldMatch to 1 so that BQ will not optimize rewrite to return
// the clause instead of BQ.
bq.MinimumNumberShouldMatch = 1;
hits = idxS.Search(bq, f, hitCount, sort, random.NextBoolean(), random.NextBoolean());
}
else if (queryType == 1)
{
hits = idxS.Search(new ConstantScoreQuery(f), null, hitCount, sort, random.NextBoolean(), random.NextBoolean());
}
else
{
hits = idxS.Search(new MatchAllDocsQuery(), f, hitCount, sort, random.NextBoolean(), random.NextBoolean());
}
if (VERBOSE)
{
Console.WriteLine("\nTEST: iter=" + iter + " " + hits.TotalHits + " hits; topN=" + hitCount + "; reverse=" + reverse + "; sortMissingLast=" + sortMissingLast + " sort=" + sort);
}
// Compute expected results:
var expected = f.MatchValues.ToList();
expected.Sort(new ComparerAnonymousInnerClassHelper(this, sortMissingLast));
if (reverse)
{
expected.Reverse();
}
if (VERBOSE)
{
Console.WriteLine(" expected:");
for (int idx = 0; idx < expected.Count; idx++)
{
BytesRef br = expected[idx];
if (br == null && missingIsNull == false)
{
br = new BytesRef();
}
Console.WriteLine(" " + idx + ": " + (br == null ? "<missing>" : br.Utf8ToString()));
if (idx == hitCount - 1)
{
break;
}
}
}
if (VERBOSE)
{
Console.WriteLine(" actual:");
for (int hitIDX = 0; hitIDX < hits.ScoreDocs.Length; hitIDX++)
{
FieldDoc fd = (FieldDoc)hits.ScoreDocs[hitIDX];
BytesRef br = (BytesRef)fd.Fields[0];
Console.WriteLine(" " + hitIDX + ": " + (br == null ? "<missing>" : br.Utf8ToString()) + " id=" + idxS.Doc(fd.Doc).Get("id"));
}
}
for (int hitIDX = 0; hitIDX < hits.ScoreDocs.Length; hitIDX++)
{
FieldDoc fd = (FieldDoc)hits.ScoreDocs[hitIDX];
BytesRef br = expected[hitIDX];
if (br == null && missingIsNull == false)
{
br = new BytesRef();
}
// Normally, the old codecs (that don't support
// docsWithField via doc values) will always return
// an empty BytesRef for the missing case; however,
// if all docs in a given segment were missing, in
// that case it will return null! So we must map
// null here, too:
BytesRef br2 = (BytesRef)fd.Fields[0];
if (br2 == null && missingIsNull == false)
{
br2 = new BytesRef();
}
Assert.AreEqual(br, br2, "hit=" + hitIDX + " has wrong sort value");
}
}
r.Dispose();
dir.Dispose();
}
private class ComparerAnonymousInnerClassHelper : IComparer<BytesRef>
{
private readonly TestSortRandom OuterInstance;
private bool SortMissingLast;
public ComparerAnonymousInnerClassHelper(TestSortRandom outerInstance, bool sortMissingLast)
{
this.OuterInstance = outerInstance;
this.SortMissingLast = sortMissingLast;
}
public virtual int Compare(BytesRef a, BytesRef b)
{
if (a == null)
{
if (b == null)
{
return 0;
}
if (SortMissingLast)
{
return 1;
}
else
{
return -1;
}
}
else if (b == null)
{
if (SortMissingLast)
{
return -1;
}
else
{
return 1;
}
}
else
{
return a.CompareTo(b);
}
}
}
private class RandomFilter : Filter
{
private readonly Random Random;
private readonly float Density;
private readonly IList<BytesRef> DocValues;
public readonly IList<BytesRef> MatchValues = new SynchronizedList<BytesRef>();
// density should be 0.0 ... 1.0
public RandomFilter(Random random, float density, IList<BytesRef> docValues)
{
this.Random = random;
this.Density = density;
this.DocValues = docValues;
}
public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs)
{
int maxDoc = context.Reader.MaxDoc;
FieldCache.Int32s idSource = FieldCache.DEFAULT.GetInt32s(context.AtomicReader, "id", false);
Assert.IsNotNull(idSource);
FixedBitSet bits = new FixedBitSet(maxDoc);
for (int docID = 0; docID < maxDoc; docID++)
{
if ((float)Random.NextDouble() <= Density && (acceptDocs == null || acceptDocs.Get(docID)))
{
bits.Set(docID);
//System.out.println(" acc id=" + idSource.Get(docID) + " docID=" + docID + " id=" + idSource.Get(docID) + " v=" + docValues.Get(idSource.Get(docID)).Utf8ToString());
MatchValues.Add(DocValues[idSource.Get(docID)]);
}
}
return bits;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using UnityEditor.ShaderGraph;
using UnityEngine;
namespace UnityEditor.Graphing
{
class SlotConfigurationException : Exception
{
public SlotConfigurationException(string message)
: base(message)
{}
}
static class NodeUtils
{
public static string docURL = "https://github.com/Unity-Technologies/ScriptableRenderPipeline/tree/master/com.unity.shadergraph/Documentation%7E/";
public static void SlotConfigurationExceptionIfBadConfiguration(AbstractMaterialNode node, IEnumerable<int> expectedInputSlots, IEnumerable<int> expectedOutputSlots)
{
var missingSlots = new List<int>();
var inputSlots = expectedInputSlots as IList<int> ?? expectedInputSlots.ToList();
missingSlots.AddRange(inputSlots.Except(node.GetInputSlots<ISlot>().Select(x => x.id)));
var outputSlots = expectedOutputSlots as IList<int> ?? expectedOutputSlots.ToList();
missingSlots.AddRange(outputSlots.Except(node.GetOutputSlots<ISlot>().Select(x => x.id)));
if (missingSlots.Count == 0)
return;
var toPrint = missingSlots.Select(x => x.ToString());
throw new SlotConfigurationException(string.Format("Missing slots {0} on node {1}", string.Join(", ", toPrint.ToArray()), node));
}
public static IEnumerable<IEdge> GetAllEdges(AbstractMaterialNode node)
{
var result = new List<IEdge>();
var validSlots = ListPool<ISlot>.Get();
validSlots.AddRange(node.GetInputSlots<ISlot>());
for (int index = 0; index < validSlots.Count; index++)
{
var inputSlot = validSlots[index];
result.AddRange(node.owner.GetEdges(inputSlot.slotReference));
}
validSlots.Clear();
validSlots.AddRange(node.GetOutputSlots<ISlot>());
for (int index = 0; index < validSlots.Count; index++)
{
var outputSlot = validSlots[index];
result.AddRange(node.owner.GetEdges(outputSlot.slotReference));
}
ListPool<ISlot>.Release(validSlots);
return result;
}
public static string GetDuplicateSafeNameForSlot(AbstractMaterialNode node, int slotId, string name)
{
List<MaterialSlot> slots = new List<MaterialSlot>();
node.GetSlots(slots);
name = name.Trim();
return GraphUtil.SanitizeName(slots.Where(p => p.id != slotId).Select(p => p.RawDisplayName()), "{0} ({1})", name);
}
// CollectNodesNodeFeedsInto looks at the current node and calculates
// which child nodes it depends on for it's calculation.
// Results are returned depth first so by processing each node in
// order you can generate a valid code block.
public enum IncludeSelf
{
Include,
Exclude
}
public static void DepthFirstCollectNodesFromNode<T>(List<T> nodeList, T node, IncludeSelf includeSelf = IncludeSelf.Include, List<int> slotIds = null)
where T : AbstractMaterialNode
{
// no where to start
if (node == null)
return;
// already added this node
if (nodeList.Contains(node))
return;
IEnumerable<int> ids;
if (slotIds == null)
ids = node.GetInputSlots<ISlot>().Select(x => x.id);
else
ids = node.GetInputSlots<ISlot>().Where(x => slotIds.Contains(x.id)).Select(x => x.id);
foreach (var slot in ids)
{
foreach (var edge in node.owner.GetEdges(node.GetSlotReference(slot)))
{
var outputNode = node.owner.GetNodeFromGuid(edge.outputSlot.nodeGuid) as T;
if (outputNode != null)
DepthFirstCollectNodesFromNode(nodeList, outputNode);
}
}
if (includeSelf == IncludeSelf.Include)
nodeList.Add(node);
}
public static void CollectNodesNodeFeedsInto(List<AbstractMaterialNode> nodeList, AbstractMaterialNode node, IncludeSelf includeSelf = IncludeSelf.Include)
{
if (node == null)
return;
if (nodeList.Contains(node))
return;
foreach (var slot in node.GetOutputSlots<ISlot>())
{
foreach (var edge in node.owner.GetEdges(slot.slotReference))
{
var inputNode = node.owner.GetNodeFromGuid(edge.inputSlot.nodeGuid);
CollectNodesNodeFeedsInto(nodeList, inputNode);
}
}
if (includeSelf == IncludeSelf.Include)
nodeList.Add(node);
}
public static string GetDocumentationString(AbstractMaterialNode node)
{
return $"{docURL}{node.name.Replace(" ", "-")}"+"-Node.md";
}
static Stack<MaterialSlot> s_SlotStack = new Stack<MaterialSlot>();
public static ShaderStage GetEffectiveShaderStage(MaterialSlot initialSlot, bool goingBackwards)
{
var graph = initialSlot.owner.owner;
s_SlotStack.Clear();
s_SlotStack.Push(initialSlot);
while (s_SlotStack.Any())
{
var slot = s_SlotStack.Pop();
ShaderStage stage;
if (slot.stageCapability.TryGetShaderStage(out stage))
return stage;
if (goingBackwards && slot.isInputSlot)
{
foreach (var edge in graph.GetEdges(slot.slotReference))
{
var node = graph.GetNodeFromGuid(edge.outputSlot.nodeGuid);
s_SlotStack.Push(node.FindOutputSlot<MaterialSlot>(edge.outputSlot.slotId));
}
}
else if (!goingBackwards && slot.isOutputSlot)
{
foreach (var edge in graph.GetEdges(slot.slotReference))
{
var node = graph.GetNodeFromGuid(edge.inputSlot.nodeGuid);
s_SlotStack.Push(node.FindInputSlot<MaterialSlot>(edge.inputSlot.slotId));
}
}
else
{
var ownerSlots = Enumerable.Empty<MaterialSlot>();
if (goingBackwards && slot.isOutputSlot)
ownerSlots = slot.owner.GetInputSlots<MaterialSlot>();
else if (!goingBackwards && slot.isInputSlot)
ownerSlots = slot.owner.GetOutputSlots<MaterialSlot>();
foreach (var ownerSlot in ownerSlots)
s_SlotStack.Push(ownerSlot);
}
}
// We default to fragment shader stage if all connected nodes were compatible with both.
return ShaderStage.Fragment;
}
public static ShaderStageCapability GetEffectiveShaderStageCapability(MaterialSlot initialSlot, bool goingBackwards)
{
var graph = initialSlot.owner.owner;
s_SlotStack.Clear();
s_SlotStack.Push(initialSlot);
while (s_SlotStack.Any())
{
var slot = s_SlotStack.Pop();
ShaderStage stage;
if (slot.stageCapability.TryGetShaderStage(out stage))
return slot.stageCapability;
if (goingBackwards && slot.isInputSlot)
{
foreach (var edge in graph.GetEdges(slot.slotReference))
{
var node = graph.GetNodeFromGuid(edge.outputSlot.nodeGuid);
s_SlotStack.Push(node.FindOutputSlot<MaterialSlot>(edge.outputSlot.slotId));
}
}
else if (!goingBackwards && slot.isOutputSlot)
{
foreach (var edge in graph.GetEdges(slot.slotReference))
{
var node = graph.GetNodeFromGuid(edge.inputSlot.nodeGuid);
s_SlotStack.Push(node.FindInputSlot<MaterialSlot>(edge.inputSlot.slotId));
}
}
else
{
var ownerSlots = Enumerable.Empty<MaterialSlot>();
if (goingBackwards && slot.isOutputSlot)
ownerSlots = slot.owner.GetInputSlots<MaterialSlot>();
else if (!goingBackwards && slot.isInputSlot)
ownerSlots = slot.owner.GetOutputSlots<MaterialSlot>();
foreach (var ownerSlot in ownerSlots)
s_SlotStack.Push(ownerSlot);
}
}
return ShaderStageCapability.All;
}
public static string GetSlotDimension(ConcreteSlotValueType slotValue)
{
switch (slotValue)
{
case ConcreteSlotValueType.Vector1:
return String.Empty;
case ConcreteSlotValueType.Vector2:
return "2";
case ConcreteSlotValueType.Vector3:
return "3";
case ConcreteSlotValueType.Vector4:
return "4";
case ConcreteSlotValueType.Matrix2:
return "2x2";
case ConcreteSlotValueType.Matrix3:
return "3x3";
case ConcreteSlotValueType.Matrix4:
return "4x4";
default:
return "Error";
}
}
public static string ConvertConcreteSlotValueTypeToString(AbstractMaterialNode.OutputPrecision p, ConcreteSlotValueType slotValue)
{
switch (slotValue)
{
case ConcreteSlotValueType.Boolean:
return p.ToString();
case ConcreteSlotValueType.Vector1:
return p.ToString();
case ConcreteSlotValueType.Vector2:
return p + "2";
case ConcreteSlotValueType.Vector3:
return p + "3";
case ConcreteSlotValueType.Vector4:
return p + "4";
case ConcreteSlotValueType.Texture2D:
return "Texture2D";
case ConcreteSlotValueType.Texture2DArray:
return "Texture2DArray";
case ConcreteSlotValueType.Texture3D:
return "Texture3D";
case ConcreteSlotValueType.Cubemap:
return "TextureCube";
case ConcreteSlotValueType.Gradient:
return "Gradient";
case ConcreteSlotValueType.Matrix2:
return p + "2x2";
case ConcreteSlotValueType.Matrix3:
return p + "3x3";
case ConcreteSlotValueType.Matrix4:
return p + "4x4";
case ConcreteSlotValueType.SamplerState:
return "SamplerState";
default:
return "Error";
}
}
public static string GetHLSLSafeName(string input)
{
char[] arr = input.ToCharArray();
arr = Array.FindAll<char>(arr, (c => (Char.IsLetterOrDigit(c))));
var safeName = new string(arr);
if (char.IsDigit(safeName[0]))
{
safeName = $"var{safeName}";
}
return safeName;
}
private static string GetDisplaySafeName(string input)
{
//strip valid display characters from slot name
//current valid characters are whitespace and ( ) _ separators
StringBuilder cleanName = new StringBuilder();
foreach (var c in input)
{
if (c != ' ' && c != '(' && c != ')' && c != '_')
cleanName.Append(c);
}
return cleanName.ToString();
}
public static bool ValidateSlotName(string inName, out string errorMessage)
{
//check for invalid characters between display safe and hlsl safe name
if (GetDisplaySafeName(inName) != GetHLSLSafeName(inName))
{
errorMessage = "Slot name(s) found invalid character(s). Valid characters: A-Z, a-z, 0-9, _ ( ) ";
return true;
}
//if clean, return null and false
errorMessage = null;
return false;
}
public static string FloatToShaderValue(float value)
{
if (Single.IsPositiveInfinity(value))
return "1.#INF";
else if (Single.IsNegativeInfinity(value))
return "-1.#INF";
else if (Single.IsNaN(value))
return "NAN";
else
{
return value.ToString(CultureInfo.InvariantCulture);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Axiom.Compiler.Framework;
using NUnit.Framework;
namespace Axiom.Compiler.Framework.Unit_Tests
{
[TestFixture]
public class PrologScannerTest
{
private PrologScanner scanner = null;
private ArrayList filesToDelete = new ArrayList();
[SetUp]
public void TestSetup()
{
// Do nothing...
}
[TearDown]
public void TestEnd()
{
foreach (string filename in filesToDelete)
{
File.Delete("C:\\" + filename);
}
}
public void Write(string filename, string s)
{
StreamWriter streamWriter = new StreamWriter("C:\\" + filename,false);
streamWriter.WriteLine(s);
streamWriter.Close();
filesToDelete.Add("filename");
}
[Test]
public void StringTest()
{
Write("string.txt", " 'This is a string' ");
StreamReader stream = new StreamReader("C:\\string.txt");
scanner = new PrologScanner(stream);
scanner.Next();
Assert.AreEqual(PrologToken.ATOM, scanner.Current.Kind);
stream.Close();
}
[Test]
public void AtomTest()
{
Write("atom.txt", " atom ");
StreamReader stream = new StreamReader("C:\\atom.txt");
scanner = new PrologScanner(stream);
scanner.Next();
Assert.AreEqual(PrologToken.ATOM, scanner.Current.Kind);
stream.Close();
}
[Test]
public void VariableTest()
{
Write("var.txt", "Father ");
StreamReader stream = new StreamReader("C:\\var.txt");
scanner = new PrologScanner(stream);
scanner.Next();
Assert.AreEqual(PrologToken.VARIABLE, scanner.Current.Kind);
stream.Close();
}
[Test]
public void LParenTest()
{
Write("paren.txt", "( ");
StreamReader stream = new StreamReader("C:\\paren.txt");
scanner = new PrologScanner(stream);
scanner.Next();
Assert.AreEqual(PrologToken.LPAREN, scanner.Current.Kind);
stream.Close();
}
[Test]
public void RParenTest()
{
Write("rparen.txt", " ) ");
StreamReader stream = new StreamReader("C:\\rparen.txt");
scanner = new PrologScanner(stream);
scanner.Next();
Assert.AreEqual(PrologToken.RPAREN, scanner.Current.Kind);
stream.Close();
}
[Test]
public void DotTest()
{
Write("dot.txt", " . ");
StreamReader stream = new StreamReader("C:\\dot.txt");
scanner = new PrologScanner(stream);
scanner.Next();
Assert.AreEqual(PrologToken.DOT, scanner.Current.Kind);
stream.Close();
}
[Test]
public void LBracketTest()
{
Write("bra.txt", " [ ");
StreamReader stream = new StreamReader("C:\\bra.txt");
scanner = new PrologScanner(stream);
scanner.Next();
Assert.AreEqual(PrologToken.LBRACKET, scanner.Current.Kind);
stream.Close();
}
[Test]
public void RBracketTest()
{
Write("rbra.txt", " ] ");
StreamReader stream = new StreamReader("C:\\rbra.txt");
scanner = new PrologScanner(stream);
scanner.Next();
Assert.AreEqual(PrologToken.RBRACKET, scanner.Current.Kind);
stream.Close();
}
[Test]
public void ListSepTest()
{
Write("sep.txt", " | ");
StreamReader stream = new StreamReader("C:\\sep.txt");
scanner = new PrologScanner(stream);
scanner.Next();
Assert.AreEqual(PrologToken.LIST_SEP, scanner.Current.Kind);
stream.Close();
}
[Test]
public void CommaTest()
{
Write("comma.txt", " , ");
StreamReader stream = new StreamReader("C:\\comma.txt");
scanner = new PrologScanner(stream);
scanner.Next();
Assert.AreEqual(PrologToken.COMMA, scanner.Current.Kind);
stream.Close();
}
[Test]
public void CurrentTest()
{
Write("current.txt", "scary Variable ");
StreamReader stream = new StreamReader("C:\\current.txt");
scanner = new PrologScanner(stream);
scanner.Next();
Assert.AreEqual(PrologToken.ATOM, scanner.Current.Kind);
scanner.Next();
Assert.AreEqual(PrologToken.VARIABLE, scanner.Current.Kind);
stream.Close();
}
[Test]
public void LookaheadTest()
{
Write("lookahead.txt", "scary Variable ");
StreamReader stream = new StreamReader("C:\\lookahead.txt");
scanner = new PrologScanner(stream);
scanner.Next();
Assert.AreEqual(PrologToken.ATOM, scanner.Current.Kind);
Assert.AreEqual(PrologToken.VARIABLE, scanner.Lookahead.Kind);
stream.Close();
}
[Test]
public void FactTokensRule()
{
Write("fact_tokens.txt", "male(ali,hodroj,X,'Fine not really!',[A|B]).");
StreamReader stream = new StreamReader("C:\\fact_tokens.txt");
scanner = new PrologScanner(stream);
// male
scanner.Next();
Assert.AreEqual(PrologToken.ATOM, scanner.Current.Kind);
// (
scanner.Next();
Assert.AreEqual(PrologToken.LPAREN, scanner.Current.Kind);
// ali
scanner.Next();
Assert.AreEqual(PrologToken.ATOM, scanner.Current.Kind);
// ,
scanner.Next();
Assert.AreEqual(PrologToken.COMMA, scanner.Current.Kind);
// hodroj
scanner.Next();
Assert.AreEqual(PrologToken.ATOM, scanner.Current.Kind);
// ,
scanner.Next();
Assert.AreEqual(PrologToken.COMMA, scanner.Current.Kind);
// X
scanner.Next();
Assert.AreEqual(PrologToken.VARIABLE, scanner.Current.Kind);
// ,
scanner.Next();
Assert.AreEqual(PrologToken.COMMA, scanner.Current.Kind);
// 'Fine Not Really!'
scanner.Next();
Assert.AreEqual(PrologToken.ATOM, scanner.Current.Kind);
// ,
scanner.Next();
Assert.AreEqual(PrologToken.COMMA, scanner.Current.Kind);
// [
scanner.Next();
Assert.AreEqual(PrologToken.LBRACKET, scanner.Current.Kind);
// A
scanner.Next();
Assert.AreEqual(PrologToken.VARIABLE, scanner.Current.Kind);
// |
scanner.Next();
Assert.AreEqual(PrologToken.LIST_SEP, scanner.Current.Kind);
// B
scanner.Next();
Assert.AreEqual(PrologToken.VARIABLE, scanner.Current.Kind);
// ]
scanner.Next();
Assert.AreEqual(PrologToken.RBRACKET, scanner.Current.Kind);
// )
scanner.Next();
Assert.AreEqual(PrologToken.RPAREN, scanner.Current.Kind);
// .
scanner.Next();
Assert.AreEqual(PrologToken.DOT, scanner.Current.Kind);
stream.Close();
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
namespace System.Reflection.Emit
{
using System;
using System.Reflection;
using CultureInfo = System.Globalization.CultureInfo;
using System.Collections.Generic;
using System.Diagnostics.SymbolStore;
using System.Security;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
[HostProtection(MayLeakOnAbort = true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_ConstructorBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ConstructorBuilder : ConstructorInfo, _ConstructorBuilder
{
private readonly MethodBuilder m_methodBuilder;
internal bool m_isDefaultConstructor;
#region Constructor
private ConstructorBuilder()
{
}
[System.Security.SecurityCritical] // auto-generated
internal ConstructorBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers, ModuleBuilder mod, TypeBuilder type)
{
int sigLength;
byte[] sigBytes;
MethodToken token;
m_methodBuilder = new MethodBuilder(name, attributes, callingConvention, null, null, null,
parameterTypes, requiredCustomModifiers, optionalCustomModifiers, mod, type, false);
type.m_listMethods.Add(m_methodBuilder);
sigBytes = m_methodBuilder.GetMethodSignature().InternalGetSignature(out sigLength);
token = m_methodBuilder.GetToken();
}
[System.Security.SecurityCritical] // auto-generated
internal ConstructorBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type[] parameterTypes, ModuleBuilder mod, TypeBuilder type) :
this(name, attributes, callingConvention, parameterTypes, null, null, mod, type)
{
}
#endregion
#region Internal
internal override Type[] GetParameterTypes()
{
return m_methodBuilder.GetParameterTypes();
}
private TypeBuilder GetTypeBuilder()
{
return m_methodBuilder.GetTypeBuilder();
}
internal ModuleBuilder GetModuleBuilder()
{
return GetTypeBuilder().GetModuleBuilder();
}
#endregion
#region Object Overrides
public override String ToString()
{
return m_methodBuilder.ToString();
}
#endregion
#region MemberInfo Overrides
internal int MetadataTokenInternal
{
get { return m_methodBuilder.MetadataTokenInternal; }
}
public override Module Module
{
get { return m_methodBuilder.Module; }
}
public override Type ReflectedType
{
get { return m_methodBuilder.ReflectedType; }
}
public override Type DeclaringType
{
get { return m_methodBuilder.DeclaringType; }
}
public override String Name
{
get { return m_methodBuilder.Name; }
}
#endregion
#region MethodBase Overrides
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
[Pure]
public override ParameterInfo[] GetParameters()
{
ConstructorInfo rci = GetTypeBuilder().GetConstructor(m_methodBuilder.m_parameterTypes);
return rci.GetParameters();
}
public override MethodAttributes Attributes
{
get { return m_methodBuilder.Attributes; }
}
public override MethodImplAttributes GetMethodImplementationFlags()
{
return m_methodBuilder.GetMethodImplementationFlags();
}
public override RuntimeMethodHandle MethodHandle
{
get { return m_methodBuilder.MethodHandle; }
}
#endregion
#region ConstructorInfo Overrides
public override Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
#endregion
#region ICustomAttributeProvider Implementation
public override Object[] GetCustomAttributes(bool inherit)
{
return m_methodBuilder.GetCustomAttributes(inherit);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return m_methodBuilder.GetCustomAttributes(attributeType, inherit);
}
public override bool IsDefined (Type attributeType, bool inherit)
{
return m_methodBuilder.IsDefined(attributeType, inherit);
}
#endregion
#region Public Members
public MethodToken GetToken()
{
return m_methodBuilder.GetToken();
}
public ParameterBuilder DefineParameter(int iSequence, ParameterAttributes attributes, String strParamName)
{
// Theoretically we shouldn't allow iSequence to be 0 because in reflection ctors don't have
// return parameters. But we'll allow it for backward compatibility with V2. The attributes
// defined on the return parameters won't be very useful but won't do much harm either.
// MD will assert if we try to set the reserved bits explicitly
attributes = attributes & ~ParameterAttributes.ReservedMask;
return m_methodBuilder.DefineParameter(iSequence, attributes, strParamName);
}
public void SetSymCustomAttribute(String name, byte[] data)
{
m_methodBuilder.SetSymCustomAttribute(name, data);
}
public ILGenerator GetILGenerator()
{
if (m_isDefaultConstructor)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_DefaultConstructorILGen"));
return m_methodBuilder.GetILGenerator();
}
public ILGenerator GetILGenerator(int streamSize)
{
if (m_isDefaultConstructor)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_DefaultConstructorILGen"));
return m_methodBuilder.GetILGenerator(streamSize);
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public void SetMethodBody(byte[] il, int maxStack, byte[] localSignature, IEnumerable<ExceptionHandler> exceptionHandlers, IEnumerable<int> tokenFixups)
{
if (m_isDefaultConstructor)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_DefaultConstructorDefineBody"));
}
m_methodBuilder.SetMethodBody(il, maxStack, localSignature, exceptionHandlers, tokenFixups);
}
#if FEATURE_CAS_POLICY
[System.Security.SecuritySafeCritical] // auto-generated
public void AddDeclarativeSecurity(SecurityAction action, PermissionSet pset)
{
if (pset == null)
throw new ArgumentNullException("pset");
#pragma warning disable 618
if (!Enum.IsDefined(typeof(SecurityAction), action) ||
action == SecurityAction.RequestMinimum ||
action == SecurityAction.RequestOptional ||
action == SecurityAction.RequestRefuse)
{
throw new ArgumentOutOfRangeException("action");
}
#pragma warning restore 618
Contract.EndContractBlock();
// Cannot add declarative security after type is created.
if (m_methodBuilder.IsTypeCreated())
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TypeHasBeenCreated"));
// Translate permission set into serialized format (use standard binary serialization).
byte[] blob = pset.EncodeXml();
// Write the blob into the metadata.
TypeBuilder.AddDeclarativeSecurity(GetModuleBuilder().GetNativeHandle(), GetToken().Token, action, blob, blob.Length);
}
#endif // FEATURE_CAS_POLICY
public override CallingConventions CallingConvention
{
get
{
if (DeclaringType.IsGenericType)
return CallingConventions.HasThis;
return CallingConventions.Standard;
}
}
public Module GetModule()
{
return m_methodBuilder.GetModule();
}
[Obsolete("This property has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")] //It always returns null.
public Type ReturnType
{
get { return GetReturnType(); }
}
// This always returns null. Is that what we want?
internal override Type GetReturnType()
{
return m_methodBuilder.ReturnType;
}
public String Signature
{
get { return m_methodBuilder.Signature; }
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
m_methodBuilder.SetCustomAttribute(con, binaryAttribute);
}
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
m_methodBuilder.SetCustomAttribute(customBuilder);
}
public void SetImplementationFlags(MethodImplAttributes attributes)
{
m_methodBuilder.SetImplementationFlags(attributes);
}
public bool InitLocals
{
get { return m_methodBuilder.InitLocals; }
set { m_methodBuilder.InitLocals = value; }
}
#endregion
void _ConstructorBuilder.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _ConstructorBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _ConstructorBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
void _ConstructorBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
}
}
| |
// 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.Threading;
namespace System.Globalization
{
// Gregorian Calendars use Era Info
internal class EraInfo
{
internal int era; // The value of the era.
internal long ticks; // The time in ticks when the era starts
internal int yearOffset; // The offset to Gregorian year when the era starts.
// Gregorian Year = Era Year + yearOffset
// Era Year = Gregorian Year - yearOffset
internal int minEraYear; // Min year value in this era. Generally, this value is 1, but this may
// be affected by the DateTime.MinValue;
internal int maxEraYear; // Max year value in this era. (== the year length of the era + 1)
internal String eraName; // The era name
internal String abbrevEraName; // Abbreviated Era Name
internal String englishEraName; // English era name
internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear)
{
this.era = era;
this.yearOffset = yearOffset;
this.minEraYear = minEraYear;
this.maxEraYear = maxEraYear;
this.ticks = new DateTime(startYear, startMonth, startDay).Ticks;
}
internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear,
String eraName, String abbrevEraName, String englishEraName)
{
this.era = era;
this.yearOffset = yearOffset;
this.minEraYear = minEraYear;
this.maxEraYear = maxEraYear;
this.ticks = new DateTime(startYear, startMonth, startDay).Ticks;
this.eraName = eraName;
this.abbrevEraName = abbrevEraName;
this.englishEraName = englishEraName;
}
}
// This calendar recognizes two era values:
// 0 CurrentEra (AD)
// 1 BeforeCurrentEra (BC)
internal class GregorianCalendarHelper
{
// 1 tick = 100ns = 10E-7 second
// Number of ticks per time unit
internal const long TicksPerMillisecond = 10000;
internal const long TicksPerSecond = TicksPerMillisecond * 1000;
internal const long TicksPerMinute = TicksPerSecond * 60;
internal const long TicksPerHour = TicksPerMinute * 60;
internal const long TicksPerDay = TicksPerHour * 24;
// Number of milliseconds per time unit
internal const int MillisPerSecond = 1000;
internal const int MillisPerMinute = MillisPerSecond * 60;
internal const int MillisPerHour = MillisPerMinute * 60;
internal const int MillisPerDay = MillisPerHour * 24;
// Number of days in a non-leap year
internal const int DaysPerYear = 365;
// Number of days in 4 years
internal const int DaysPer4Years = DaysPerYear * 4 + 1;
// Number of days in 100 years
internal const int DaysPer100Years = DaysPer4Years * 25 - 1;
// Number of days in 400 years
internal const int DaysPer400Years = DaysPer100Years * 4 + 1;
// Number of days from 1/1/0001 to 1/1/10000
internal const int DaysTo10000 = DaysPer400Years * 25 - 366;
internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
internal const int DatePartYear = 0;
internal const int DatePartDayOfYear = 1;
internal const int DatePartMonth = 2;
internal const int DatePartDay = 3;
//
// This is the max Gregorian year can be represented by DateTime class. The limitation
// is derived from DateTime class.
//
internal int MaxYear
{
get
{
return (m_maxYear);
}
}
internal static readonly int[] DaysToMonth365 =
{
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
};
internal static readonly int[] DaysToMonth366 =
{
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366
};
internal int m_maxYear = 9999;
internal int m_minYear;
internal Calendar m_Cal;
internal EraInfo[] m_EraInfo;
internal int[] m_eras = null;
// Construct an instance of gregorian calendar.
internal GregorianCalendarHelper(Calendar cal, EraInfo[] eraInfo)
{
m_Cal = cal;
m_EraInfo = eraInfo;
m_maxYear = m_EraInfo[0].maxEraYear;
m_minYear = m_EraInfo[0].minEraYear; ;
}
/*=================================GetGregorianYear==========================
**Action: Get the Gregorian year value for the specified year in an era.
**Returns: The Gregorian year value.
**Arguments:
** year the year value in Japanese calendar
** era the Japanese emperor era value.
**Exceptions:
** ArgumentOutOfRangeException if year value is invalid or era value is invalid.
============================================================================*/
internal int GetGregorianYear(int year, int era)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (era == Calendar.CurrentEra)
{
era = m_Cal.CurrentEraValue;
}
for (int i = 0; i < m_EraInfo.Length; i++)
{
if (era == m_EraInfo[i].era)
{
if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
m_EraInfo[i].minEraYear,
m_EraInfo[i].maxEraYear));
}
return (m_EraInfo[i].yearOffset + year);
}
}
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
internal bool IsValidYear(int year, int era)
{
if (year < 0)
{
return false;
}
if (era == Calendar.CurrentEra)
{
era = m_Cal.CurrentEraValue;
}
for (int i = 0; i < m_EraInfo.Length; i++)
{
if (era == m_EraInfo[i].era)
{
if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear)
{
return false;
}
return true;
}
}
return false;
}
// Returns a given date part of this DateTime. This method is used
// to compute the year, day-of-year, month, or day part.
internal virtual int GetDatePart(long ticks, int part)
{
CheckTicksRange(ticks);
// n = number of days since 1/1/0001
int n = (int)(ticks / TicksPerDay);
// y400 = number of whole 400-year periods since 1/1/0001
int y400 = n / DaysPer400Years;
// n = day number within 400-year period
n -= y400 * DaysPer400Years;
// y100 = number of whole 100-year periods within 400-year period
int y100 = n / DaysPer100Years;
// Last 100-year period has an extra day, so decrement result if 4
if (y100 == 4) y100 = 3;
// n = day number within 100-year period
n -= y100 * DaysPer100Years;
// y4 = number of whole 4-year periods within 100-year period
int y4 = n / DaysPer4Years;
// n = day number within 4-year period
n -= y4 * DaysPer4Years;
// y1 = number of whole years within 4-year period
int y1 = n / DaysPerYear;
// Last year has an extra day, so decrement result if 4
if (y1 == 4) y1 = 3;
// If year was requested, compute and return it
if (part == DatePartYear)
{
return (y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1);
}
// n = day number within year
n -= y1 * DaysPerYear;
// If day-of-year was requested, return it
if (part == DatePartDayOfYear)
{
return (n + 1);
}
// Leap year calculation looks different from IsLeapYear since y1, y4,
// and y100 are relative to year 1, not year 0
bool leapYear = (y1 == 3 && (y4 != 24 || y100 == 3));
int[] days = leapYear ? DaysToMonth366 : DaysToMonth365;
// All months have less than 32 days, so n >> 5 is a good conservative
// estimate for the month
int m = (n >> 5) + 1;
// m = 1-based month number
while (n >= days[m]) m++;
// If month was requested, return it
if (part == DatePartMonth) return (m);
// Return 1-based day-of-month
return (n - days[m - 1] + 1);
}
/*=================================GetAbsoluteDate==========================
**Action: Gets the absolute date for the given Gregorian date. The absolute date means
** the number of days from January 1st, 1 A.D.
**Returns: the absolute date
**Arguments:
** year the Gregorian year
** month the Gregorian month
** day the day
**Exceptions:
** ArgumentOutOfRangException if year, month, day value is valid.
**Note:
** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars.
** Number of Days in Prior Years (both common and leap years) +
** Number of Days in Prior Months of Current Year +
** Number of Days in Current Month
**
============================================================================*/
internal static long GetAbsoluteDate(int year, int month, int day)
{
if (year >= 1 && year <= 9999 && month >= 1 && month <= 12)
{
int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366 : DaysToMonth365;
if (day >= 1 && (day <= days[month] - days[month - 1]))
{
int y = year - 1;
int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1;
return (absoluteDate);
}
}
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}
// Returns the tick count corresponding to the given year, month, and day.
// Will check the if the parameters are valid.
internal static long DateToTicks(int year, int month, int day)
{
return (GetAbsoluteDate(year, month, day) * TicksPerDay);
}
// Return the tick count corresponding to the given hour, minute, second.
// Will check the if the parameters are valid.
internal static long TimeToTicks(int hour, int minute, int second, int millisecond)
{
//TimeSpan.TimeToTicks is a family access function which does no error checking, so
//we need to put some error checking out here.
if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
{
if (millisecond < 0 || millisecond >= MillisPerSecond)
{
throw new ArgumentOutOfRangeException(
nameof(millisecond),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
MillisPerSecond - 1));
}
return (InternalGlobalizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond); ;
}
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
}
internal void CheckTicksRange(long ticks)
{
if (ticks < m_Cal.MinSupportedDateTime.Ticks || ticks > m_Cal.MaxSupportedDateTime.Ticks)
{
throw new ArgumentOutOfRangeException(
"time",
String.Format(
CultureInfo.InvariantCulture,
SR.ArgumentOutOfRange_CalendarRange,
m_Cal.MinSupportedDateTime,
m_Cal.MaxSupportedDateTime));
}
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
nameof(months),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
-120000,
120000));
}
CheckTicksRange(time.Ticks);
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366 : DaysToMonth365;
int days = (daysArray[m] - daysArray[m - 1]);
if (d > days)
{
d = days;
}
long ticks = DateToTicks(y, m, d) + (time.Ticks % TicksPerDay);
Calendar.CheckAddResult(ticks, m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public DateTime AddYears(DateTime time, int years)
{
return (AddMonths(time, years * 12));
}
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public int GetDayOfMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDay));
}
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public DayOfWeek GetDayOfWeek(DateTime time)
{
CheckTicksRange(time.Ticks);
return ((DayOfWeek)((time.Ticks / TicksPerDay + 1) % 7));
}
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public int GetDayOfYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
// Returns the number of days in the month given by the year and
// month arguments.
//
public int GetDaysInMonth(int year, int month, int era)
{
//
// Convert year/era value to Gregorain year value.
//
year = GetGregorianYear(year, era);
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month);
}
int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365);
return (days[month] - days[month - 1]);
}
// Returns the number of days in the year given by the year argument for the current era.
//
public int GetDaysInYear(int year, int era)
{
//
// Convert year/era value to Gregorain year value.
//
year = GetGregorianYear(year, era);
return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366 : 365);
}
// Returns the era for the specified DateTime value.
public int GetEra(DateTime time)
{
long ticks = time.Ticks;
// The assumption here is that m_EraInfo is listed in reverse order.
for (int i = 0; i < m_EraInfo.Length; i++)
{
if (ticks >= m_EraInfo[i].ticks)
{
return (m_EraInfo[i].era);
}
}
throw new ArgumentOutOfRangeException(nameof(time), SR.ArgumentOutOfRange_Era);
}
public int[] Eras
{
get
{
if (m_eras == null)
{
m_eras = new int[m_EraInfo.Length];
for (int i = 0; i < m_EraInfo.Length; i++)
{
m_eras[i] = m_EraInfo[i].era;
}
}
return ((int[])m_eras.Clone());
}
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public int GetMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartMonth));
}
// Returns the number of months in the specified year and era.
public int GetMonthsInYear(int year, int era)
{
year = GetGregorianYear(year, era);
return (12);
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and 9999.
//
public int GetYear(DateTime time)
{
long ticks = time.Ticks;
int year = GetDatePart(ticks, DatePartYear);
for (int i = 0; i < m_EraInfo.Length; i++)
{
if (ticks >= m_EraInfo[i].ticks)
{
return (year - m_EraInfo[i].yearOffset);
}
}
throw new ArgumentException(SR.Argument_NoEra);
}
// Returns the year that match the specified Gregorian year. The returned value is an
// integer between 1 and 9999.
//
public int GetYear(int year, DateTime time)
{
long ticks = time.Ticks;
for (int i = 0; i < m_EraInfo.Length; i++)
{
// while calculating dates with JapaneseLuniSolarCalendar, we can run into cases right after the start of the era
// and still belong to the month which is started in previous era. Calculating equivalent calendar date will cause
// using the new era info which will have the year offset equal to the year we are calculating year = m_EraInfo[i].yearOffset
// which will end up with zero as calendar year.
// We should use the previous era info instead to get the right year number. Example of such date is Feb 2nd 1989
if (ticks >= m_EraInfo[i].ticks && year > m_EraInfo[i].yearOffset)
{
return (year - m_EraInfo[i].yearOffset);
}
}
throw new ArgumentException(SR.Argument_NoEra);
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public bool IsLeapDay(int year, int month, int day, int era)
{
// year/month/era checking is done in GetDaysInMonth()
if (day < 1 || day > GetDaysInMonth(year, month, era))
{
throw new ArgumentOutOfRangeException(
nameof(day),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
GetDaysInMonth(year, month, era)));
}
if (!IsLeapYear(year, era))
{
return (false);
}
if (month == 2 && day == 29)
{
return (true);
}
return (false);
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public int GetLeapMonth(int year, int era)
{
year = GetGregorianYear(year, era);
return (0);
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public bool IsLeapMonth(int year, int month, int era)
{
year = GetGregorianYear(year, era);
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(
nameof(month),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
12));
}
return (false);
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public bool IsLeapYear(int year, int era)
{
year = GetGregorianYear(year, era);
return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
year = GetGregorianYear(year, era);
long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second, millisecond);
CheckTicksRange(ticks);
return (new DateTime(ticks));
}
public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
CheckTicksRange(time.Ticks);
// Use GregorianCalendar to get around the problem that the implmentation in Calendar.GetWeekOfYear()
// can call GetYear() that exceeds the supported range of the Gregorian-based calendars.
return (GregorianCalendar.GetDefaultInstance().GetWeekOfYear(time, rule, firstDayOfWeek));
}
public int ToFourDigitYear(int year, int twoDigitYearMax)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedPosNum);
}
if (year < 100)
{
int y = year % 100;
return ((twoDigitYearMax / 100 - (y > twoDigitYearMax % 100 ? 1 : 0)) * 100 + y);
}
if (year < m_minYear || year > m_maxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range, m_minYear, m_maxYear));
}
// If the year value is above 100, just return the year value. Don't have to do
// the TwoDigitYearMax comparison.
return (year);
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Zeltex.Util;
using Zeltex.Dialogue;
using Zeltex.Characters;
using Zeltex.Items;
using Zeltex;
using SimpleJSON;
using Newtonsoft.Json;
using System;
namespace Zeltex.Quests
{
[Serializable]
public class QuestBlock : Element
{
}
/// <summary>
/// An agreement between characters to meet certain conditions. Met with either rewards or punishment.
/// </summary>
[Serializable]
public class Quest : ElementCore
{
[JsonIgnore]
public static string QuestNameColor = "#d1d9e1";
[JsonProperty]
public int ConditionIndex = 0;
[JsonProperty]
public List<Condition> MyConditions = new List<Condition>();
[JsonProperty]
public List<Reward> MyRewards = new List<Reward>();
[JsonProperty]
public QuestBlock MyQuestBlock;
[JsonProperty, SerializeField]
private bool IsCompleted = false;
[JsonProperty]
public float TimeCompleted = 0f;
[JsonProperty]
public bool IsOrderedConditions = false;
[JsonProperty]
public bool IsHandedIn = false;
[JsonProperty]
public float TimeHandedIn = 0f;
// reference to quest partipants
[JsonIgnore]
public Character QuestGiver = null;
[JsonIgnore]
public Character QuestTaker = null;
#region Modifiers
/// <summary>
/// Sets the description of a quest
/// </summary>
public void SetDescription(string NewDescription)
{
if (Description != NewDescription)
{
Description = NewDescription;
OnModified();
}
}
#endregion
#region UI
public string GetLabelText()
{
string MyLabelText = "";
if (HasCompleted ())
MyLabelText += "[X] ";
else
MyLabelText += "[O] ";
MyLabelText += Name;
return MyLabelText;
}
public string GetDescriptionText()
{
string MyDescription = "";
string QuestGiverName = "Invalid";
if (QuestGiver)
QuestGiverName = QuestGiver.name;
MyDescription += "Quest Giver <color=" + QuestNameColor + ">[" + QuestGiverName + "]</color>\n";
MyDescription += Description;
if (MyConditions.Count > 0)
{
MyDescription += "\nConditions";
for (int i = 0; i < MyConditions.Count; i++)
{
MyDescription += "\n\t";
MyDescription += MyConditions [i].GetDescriptionText ();
}
} else {
MyDescription += "\nNo Conditions.";
}
if (MyRewards.Count > 0)
{
MyDescription += "\nRewards:";
for (int i = 0; i < MyRewards.Count; i++)
{
MyDescription += "\n\t";
MyDescription += MyRewards [i].GetDescriptionText ();
}
}
else
{
MyDescription += "\nNo Rewards.";
}
if (IsHandedIn)
{
MyDescription += "\nHanded in on: " + TimeHandedIn;
}
return MyDescription;
}
#endregion
#region QuestLog
public bool HasGivenQuestOut()
{
if (QuestTaker == null)
return false;
else
return true;
}
public void HandIn()
{
if (!IsHandedIn)
{
CompleteQuest (); // incase it isn't complete
IsHandedIn = true;
TimeHandedIn = Time.time;
}
}
public void CompleteQuest()
{
if (!IsCompleted)
{
IsCompleted = true;
TimeCompleted = Time.time;
}
}
public bool HasGivenToSomeone()
{
return (QuestTaker != null);
}
public bool HasCompleted()
{
return IsCompleted;
}
/// <summary>
/// checks if quest has been completed
/// </summary>
public void CheckCompleted()
{
if (IsAllConditionsTrue())
IsCompleted = true;
else
IsCompleted = false;
}
#endregion
#region Conditions
public bool IsAllConditionsTrue()
{
for (int i = 0; i < MyConditions.Count; i++)
{
if (MyConditions[i].HasCompleted() == false)
return false;
}
return true;
}
public Condition GetCurrentCondition()
{
if (ConditionIndex < 0 || ConditionIndex >= MyConditions.Count || MyConditions.Count == 0) // if outside bounds or no conditions
return new Condition();
if (ConditionIndex < MyConditions.Count)
return MyConditions [ConditionIndex];
else
return MyConditions [MyConditions.Count-1];
}
public void IncreaseConditionIndex()
{
if (GetCurrentCondition().HasCompleted())
{
ConditionIndex++;
if (ConditionIndex >= MyConditions.Count)
ConditionIndex = MyConditions.Count - 1;
}
}
/// <summary>
/// WHen player enters a zone
/// </summary>
public bool OnZone(string CheckZone, string Action)
{
bool DidTrigger = false;
//Debug.Log (Name + " -Checking Zone for: " + CheckZone);
for (int i = 0; i < MyConditions.Count; i++)
{
if (!MyConditions[i].HasCompleted() && MyConditions[i].ConditionType.Contains("Zone"))
{
DidTrigger = MyConditions[i].OnZone(CheckZone, Action);
}
}
if (DidTrigger)
{
IncreaseConditionIndex();
CheckCompleted();
}
return DidTrigger;
}
// tells all the conditions that items have changed, so a check is done
/// <summary>
/// To Do:
/// Make event only for the item
/// </summary>
public bool OnAddItem(Character MyCharacter)
{
// Debug.Log("Inside Quest, OnAddItem for: " + MyCharacter.name);
if (IsHandedIn)
{
return false;
}
bool DidTrigger = false;
//Zeltex.Items.Inventory MyInventory = MyCharacter.gameObject.GetComponent<Zeltex.Items.Inventory> ();
for (int i = 0; i < MyConditions.Count; i++)
{
if (MyConditions[i].ConditionType.Contains("Inventory"))
{
if (CheckInventory(MyConditions[i], MyCharacter))
{
DidTrigger = true;
}
}
}
if (DidTrigger)
{
IncreaseConditionIndex();
CheckCompleted();
}
return DidTrigger;
}
/// <summary>
/// Called on Add Item in inventory
/// </summary>
public bool CheckInventory(Condition MyCondition, Character MyCharacter)
{
//Debug.Log("Inside Quest, checking Inventory for Character: " + MyCharacter.name);
// inventory condition checks
if (MyCondition.IsInventory())
{
Inventory MyInventory = MyCharacter.GetBackpackItems();
if (MyInventory != null)
{
Item MyItem = MyInventory.GetItem(MyCondition.ObjectName);
if (MyItem != null)
{
int MyQuantity = MyItem.GetQuantity();
//Debug.Log("Character has " + MyQuantity + " items of " + MyCondition.ObjectName);
if (MyQuantity != MyCondition.ItemQuantityState)
{
MyCondition.ItemQuantityState = MyQuantity;
MyCondition.ItemQuantityState = Mathf.Clamp(MyCondition.ItemQuantityState, 0, MyCondition.ItemQuantity);
return true;
} // has updated quest variables
}
else
{
MyCondition.ItemQuantityState = 0;
// Debug.LogError("No item of: " + MyCondition.ObjectName + " in inventory.");
}
}
}
return false;
}
#endregion
}
}
/// <summary>
/// Runs the script to load the quest
/// </summary>
/*public void RunScript(List<string> SavedData)
{
for (int i = 0; i < SavedData.Count; i++)
{
string Other = ScriptUtil.RemoveCommand(SavedData[i]);
if (SavedData[i].Contains("/quest "))
{
string QuestName = Other;
Name = QuestName;
}
else if (SavedData[i].Contains("/description ")) // description
{
Description = Other;
}
else if (SavedData[i].Contains("/LeaveZone ")) // leave zone
{
Condition NewCondition = new Condition();
NewCondition.ConditionType = "LeaveZone";
NewCondition.ObjectName = Other;
MyConditions.Add(NewCondition);
}
else if (SavedData[i].Contains("/EnterZone ")) // enter zone
{
Condition NewCondition = new Condition();
NewCondition.ConditionType = "EnterZone";
NewCondition.ObjectName = Other;
MyConditions.Add(NewCondition);
}
else if (SavedData[i].Contains("/TalkTo ")) // talk to npc
{
Condition NewCondition = new Condition();
NewCondition.ConditionType = "TalkTo";
NewCondition.ObjectName = Other;
MyConditions.Add(NewCondition);
}
else if (SavedData[i].Contains("/Reward ")) // rewards
{
List<string> MyRewardCommands = ScriptUtil.SplitCommands(Other);
if (MyRewardCommands.Count > 0)
{
Reward NewReward = new Reward();
NewReward.IsInventory = true;
try
{
string QuantityString = MyRewardCommands[MyRewardCommands.Count - 1];
NewReward.ItemQuantity = int.Parse(QuantityString);
string ItemName = Other.Remove(Other.IndexOf(QuantityString) - 1, QuantityString.Length + 1);
NewReward.ItemName = //SpeechUtilities.CheckStringForLastChar
(ItemName);
}
catch (System.FormatException e)
{
NewReward.ItemName = //SpeechUtilities.CheckStringForLastChar
(Other);
NewReward.ItemQuantity = 1;
}
MyRewards.Add(NewReward);
}
}
else if (SavedData[i].Contains("/Failure ")) // failure
{
SavedData[i] = Other;
}
else if (SavedData[i].Contains("/Inventory ")) // items needed by npc
{
SavedData[i] = Other;
List<string> MyItems = ScriptUtil.SplitCommands(SavedData[i]);
if (MyItems.Count > 0)
{
Condition NewCondition = new Condition();
NewCondition.ConditionType = "Inventory";
try
{
string QuantityString = MyItems[MyItems.Count - 1]; // get last command
NewCondition.ItemQuantity = int.Parse(QuantityString); // convert it to int
SavedData[i] = SavedData[i].Remove(SavedData[i].IndexOf(QuantityString) - 1, QuantityString.Length + 1);
NewCondition.ObjectName = SavedData[i];
}
catch (System.FormatException e)
{
NewCondition.ObjectName = SavedData[i];
NewCondition.ItemQuantity = 1;
}
MyConditions.Add(NewCondition);
}
}
}*/
/*public void RunScript(string[] SavedData)
{
List<string> MyScript = new List<string>();
for (int i = 0; i < SavedData.Length; i++)
{
MyScript.Add(SavedData[i]);
}
RunScript(MyScript);
}*/
/// <summary>
//reading/writing section
/*public static string[] MyCommands = new string[] { "quest",
"description",
"LeaveZone",
"EnterZone",
"Inventory",
"TalkTo",
"reward",
"failure"
};*/
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#if !UNIX
using System.Diagnostics.Eventing;
using System.Diagnostics.CodeAnalysis;
namespace System.Management.Automation.Tracing
{
/// <summary>
/// Tracer.
/// </summary>
public sealed partial class Tracer : System.Management.Automation.Tracing.EtwActivity
{
/// <summary>
/// Critical level.
/// </summary>
public const byte LevelCritical = 1;
/// <summary>
/// Error level.
/// </summary>
public const byte LevelError = 2;
/// <summary>
/// Warning level.
/// </summary>
public const byte LevelWarning = 3;
/// <summary>
/// Informational level.
/// </summary>
public const byte LevelInformational = 4;
/// <summary>
/// Verbose level.
/// </summary>
public const byte LevelVerbose = 5;
/// <summary>
/// Keyword all.
/// </summary>
public const long KeywordAll = 0xFFFFFFFF;
private static Guid providerId = Guid.Parse("a0c1853b-5c40-4b15-8766-3cf1c58f985a");
private static EventDescriptor WriteTransferEventEvent;
private static EventDescriptor DebugMessageEvent;
private static EventDescriptor M3PAbortingWorkflowExecutionEvent;
private static EventDescriptor M3PActivityExecutionFinishedEvent;
private static EventDescriptor M3PActivityExecutionQueuedEvent;
private static EventDescriptor M3PActivityExecutionStartedEvent;
private static EventDescriptor M3PBeginContainerParentJobExecutionEvent;
private static EventDescriptor M3PBeginCreateNewJobEvent;
private static EventDescriptor M3PBeginJobLogicEvent;
private static EventDescriptor M3PBeginProxyChildJobEventHandlerEvent;
private static EventDescriptor M3PBeginProxyJobEventHandlerEvent;
private static EventDescriptor M3PBeginProxyJobExecutionEvent;
private static EventDescriptor M3PBeginRunGarbageCollectionEvent;
private static EventDescriptor M3PBeginStartWorkflowApplicationEvent;
private static EventDescriptor M3PBeginWorkflowExecutionEvent;
private static EventDescriptor M3PCancellingWorkflowExecutionEvent;
private static EventDescriptor M3PChildWorkflowJobAdditionEvent;
private static EventDescriptor M3PEndContainerParentJobExecutionEvent;
private static EventDescriptor M3PEndCreateNewJobEvent;
private static EventDescriptor M3PEndJobLogicEvent;
private static EventDescriptor M3PEndpointDisabledEvent;
private static EventDescriptor M3PEndpointEnabledEvent;
private static EventDescriptor M3PEndpointModifiedEvent;
private static EventDescriptor M3PEndpointRegisteredEvent;
private static EventDescriptor M3PEndpointUnregisteredEvent;
private static EventDescriptor M3PEndProxyChildJobEventHandlerEvent;
private static EventDescriptor M3PEndProxyJobEventHandlerEvent;
private static EventDescriptor M3PEndProxyJobExecutionEvent;
private static EventDescriptor M3PEndRunGarbageCollectionEvent;
private static EventDescriptor M3PEndStartWorkflowApplicationEvent;
private static EventDescriptor M3PEndWorkflowExecutionEvent;
private static EventDescriptor M3PErrorImportingWorkflowFromXamlEvent;
private static EventDescriptor M3PForcedWorkflowShutdownErrorEvent;
private static EventDescriptor M3PForcedWorkflowShutdownFinishedEvent;
private static EventDescriptor M3PForcedWorkflowShutdownStartedEvent;
private static EventDescriptor M3PImportedWorkflowFromXamlEvent;
private static EventDescriptor M3PImportingWorkflowFromXamlEvent;
private static EventDescriptor M3PJobCreationCompleteEvent;
private static EventDescriptor M3PJobErrorEvent;
private static EventDescriptor M3PJobRemovedEvent;
private static EventDescriptor M3PJobRemoveErrorEvent;
private static EventDescriptor M3PJobStateChangedEvent;
private static EventDescriptor M3PLoadingWorkflowForExecutionEvent;
private static EventDescriptor M3POutOfProcessRunspaceStartedEvent;
private static EventDescriptor M3PParameterSplattingWasPerformedEvent;
private static EventDescriptor M3PParentJobCreatedEvent;
private static EventDescriptor M3PPersistenceStoreMaxSizeReachedEvent;
private static EventDescriptor M3PPersistingWorkflowEvent;
private static EventDescriptor M3PProxyJobRemoteJobAssociationEvent;
private static EventDescriptor M3PRemoveJobStartedEvent;
private static EventDescriptor M3PRunspaceAvailabilityChangedEvent;
private static EventDescriptor M3PRunspaceStateChangedEvent;
private static EventDescriptor M3PTrackingGuidContainerParentJobCorrelationEvent;
private static EventDescriptor M3PUnloadingWorkflowEvent;
private static EventDescriptor M3PWorkflowActivityExecutionFailedEvent;
private static EventDescriptor M3PWorkflowActivityValidatedEvent;
private static EventDescriptor M3PWorkflowActivityValidationFailedEvent;
private static EventDescriptor M3PWorkflowCleanupPerformedEvent;
private static EventDescriptor M3PWorkflowDeletedFromDiskEvent;
private static EventDescriptor M3PWorkflowEngineStartedEvent;
private static EventDescriptor M3PWorkflowExecutionAbortedEvent;
private static EventDescriptor M3PWorkflowExecutionCancelledEvent;
private static EventDescriptor M3PWorkflowExecutionErrorEvent;
private static EventDescriptor M3PWorkflowExecutionFinishedEvent;
private static EventDescriptor M3PWorkflowExecutionStartedEvent;
private static EventDescriptor M3PWorkflowJobCreatedEvent;
private static EventDescriptor M3PWorkflowLoadedForExecutionEvent;
private static EventDescriptor M3PWorkflowLoadedFromDiskEvent;
private static EventDescriptor M3PWorkflowManagerCheckpointEvent;
private static EventDescriptor M3PWorkflowPersistedEvent;
private static EventDescriptor M3PWorkflowPluginRequestedToShutdownEvent;
private static EventDescriptor M3PWorkflowPluginRestartedEvent;
private static EventDescriptor M3PWorkflowPluginStartedEvent;
private static EventDescriptor M3PWorkflowQuotaViolatedEvent;
private static EventDescriptor M3PWorkflowResumedEvent;
private static EventDescriptor M3PWorkflowResumingEvent;
private static EventDescriptor M3PWorkflowRunspacePoolCreatedEvent;
private static EventDescriptor M3PWorkflowStateChangedEvent;
private static EventDescriptor M3PWorkflowUnloadedEvent;
private static EventDescriptor M3PWorkflowValidationErrorEvent;
private static EventDescriptor M3PWorkflowValidationFinishedEvent;
private static EventDescriptor M3PWorkflowValidationStartedEvent;
/// <summary>
/// Static constructor.
/// </summary>
static Tracer()
{
unchecked
{
WriteTransferEventEvent = new EventDescriptor(0x1f05, 0x1, 0x11, 0x5, 0x14, 0x0, (long)0x4000000000000000);
DebugMessageEvent = new EventDescriptor(0xc000, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PAbortingWorkflowExecutionEvent = new EventDescriptor(0xb038, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PActivityExecutionFinishedEvent = new EventDescriptor(0xb03f, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PActivityExecutionQueuedEvent = new EventDescriptor(0xb017, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PActivityExecutionStartedEvent = new EventDescriptor(0xb018, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PBeginContainerParentJobExecutionEvent = new EventDescriptor(0xb50c, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PBeginCreateNewJobEvent = new EventDescriptor(0xb503, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PBeginJobLogicEvent = new EventDescriptor(0xb506, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PBeginProxyChildJobEventHandlerEvent = new EventDescriptor(0xb512, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PBeginProxyJobEventHandlerEvent = new EventDescriptor(0xb510, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PBeginProxyJobExecutionEvent = new EventDescriptor(0xb50e, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PBeginRunGarbageCollectionEvent = new EventDescriptor(0xb514, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PBeginStartWorkflowApplicationEvent = new EventDescriptor(0xb501, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PBeginWorkflowExecutionEvent = new EventDescriptor(0xb508, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PCancellingWorkflowExecutionEvent = new EventDescriptor(0xb037, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PChildWorkflowJobAdditionEvent = new EventDescriptor(0xb50a, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PEndContainerParentJobExecutionEvent = new EventDescriptor(0xb50d, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PEndCreateNewJobEvent = new EventDescriptor(0xb504, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PEndJobLogicEvent = new EventDescriptor(0xb507, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PEndpointDisabledEvent = new EventDescriptor(0xb044, 0x1, 0x11, 0x5, 0x14, 0x9, (long)0x4000000000000200);
M3PEndpointEnabledEvent = new EventDescriptor(0xb045, 0x1, 0x11, 0x5, 0x14, 0x9, (long)0x4000000000000200);
M3PEndpointModifiedEvent = new EventDescriptor(0xb042, 0x1, 0x11, 0x5, 0x14, 0x9, (long)0x4000000000000200);
M3PEndpointRegisteredEvent = new EventDescriptor(0xb041, 0x1, 0x11, 0x5, 0x14, 0x9, (long)0x4000000000000200);
M3PEndpointUnregisteredEvent = new EventDescriptor(0xb043, 0x1, 0x11, 0x5, 0x14, 0x9, (long)0x4000000000000200);
M3PEndProxyChildJobEventHandlerEvent = new EventDescriptor(0xb513, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PEndProxyJobEventHandlerEvent = new EventDescriptor(0xb511, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PEndProxyJobExecutionEvent = new EventDescriptor(0xb50f, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PEndRunGarbageCollectionEvent = new EventDescriptor(0xb515, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PEndStartWorkflowApplicationEvent = new EventDescriptor(0xb502, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PEndWorkflowExecutionEvent = new EventDescriptor(0xb509, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PErrorImportingWorkflowFromXamlEvent = new EventDescriptor(0xb01b, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PForcedWorkflowShutdownErrorEvent = new EventDescriptor(0xb03c, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PForcedWorkflowShutdownFinishedEvent = new EventDescriptor(0xb03b, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PForcedWorkflowShutdownStartedEvent = new EventDescriptor(0xb03a, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PImportedWorkflowFromXamlEvent = new EventDescriptor(0xb01a, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PImportingWorkflowFromXamlEvent = new EventDescriptor(0xb019, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PJobCreationCompleteEvent = new EventDescriptor(0xb032, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PJobErrorEvent = new EventDescriptor(0xb02e, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PJobRemovedEvent = new EventDescriptor(0xb033, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PJobRemoveErrorEvent = new EventDescriptor(0xb034, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PJobStateChangedEvent = new EventDescriptor(0xb02d, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PLoadingWorkflowForExecutionEvent = new EventDescriptor(0xb035, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3POutOfProcessRunspaceStartedEvent = new EventDescriptor(0xb046, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PParameterSplattingWasPerformedEvent = new EventDescriptor(0xb047, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PParentJobCreatedEvent = new EventDescriptor(0xb031, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PPersistenceStoreMaxSizeReachedEvent = new EventDescriptor(0xb516, 0x1, 0x10, 0x3, 0x0, 0x0, (long)0x8000000000000000);
M3PPersistingWorkflowEvent = new EventDescriptor(0xb03d, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PProxyJobRemoteJobAssociationEvent = new EventDescriptor(0xb50b, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PRemoveJobStartedEvent = new EventDescriptor(0xb02c, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PRunspaceAvailabilityChangedEvent = new EventDescriptor(0xb022, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PRunspaceStateChangedEvent = new EventDescriptor(0xb023, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PTrackingGuidContainerParentJobCorrelationEvent = new EventDescriptor(0xb505, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000);
M3PUnloadingWorkflowEvent = new EventDescriptor(0xb039, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PWorkflowActivityExecutionFailedEvent = new EventDescriptor(0xb021, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PWorkflowActivityValidatedEvent = new EventDescriptor(0xb01f, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PWorkflowActivityValidationFailedEvent = new EventDescriptor(0xb020, 0x1, 0x11, 0x5, 0x14, 0x8, (long)0x4000000000000200);
M3PWorkflowCleanupPerformedEvent = new EventDescriptor(0xb028, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PWorkflowDeletedFromDiskEvent = new EventDescriptor(0xb02a, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PWorkflowEngineStartedEvent = new EventDescriptor(0xb048, 0x1, 0x11, 0x5, 0x14, 0x5, (long)0x4000000000000200);
M3PWorkflowExecutionAbortedEvent = new EventDescriptor(0xb027, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PWorkflowExecutionCancelledEvent = new EventDescriptor(0xb026, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PWorkflowExecutionErrorEvent = new EventDescriptor(0xb040, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PWorkflowExecutionFinishedEvent = new EventDescriptor(0xb036, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PWorkflowExecutionStartedEvent = new EventDescriptor(0xb008, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PWorkflowJobCreatedEvent = new EventDescriptor(0xb030, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PWorkflowLoadedForExecutionEvent = new EventDescriptor(0xb024, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PWorkflowLoadedFromDiskEvent = new EventDescriptor(0xb029, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PWorkflowManagerCheckpointEvent = new EventDescriptor(0xb049, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000200);
M3PWorkflowPersistedEvent = new EventDescriptor(0xb03e, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PWorkflowPluginRequestedToShutdownEvent = new EventDescriptor(0xb010, 0x1, 0x11, 0x5, 0x14, 0x5, (long)0x4000000000000200);
M3PWorkflowPluginRestartedEvent = new EventDescriptor(0xb011, 0x1, 0x11, 0x5, 0x14, 0x5, (long)0x4000000000000200);
M3PWorkflowPluginStartedEvent = new EventDescriptor(0xb007, 0x1, 0x11, 0x5, 0x14, 0x5, (long)0x4000000000000200);
M3PWorkflowQuotaViolatedEvent = new EventDescriptor(0xb013, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PWorkflowResumedEvent = new EventDescriptor(0xb014, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PWorkflowResumingEvent = new EventDescriptor(0xb012, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PWorkflowRunspacePoolCreatedEvent = new EventDescriptor(0xb016, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PWorkflowStateChangedEvent = new EventDescriptor(0xb009, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PWorkflowUnloadedEvent = new EventDescriptor(0xb025, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200);
M3PWorkflowValidationErrorEvent = new EventDescriptor(0xb01e, 0x1, 0x11, 0x5, 0x14, 0x8, (long)0x4000000000000200);
M3PWorkflowValidationFinishedEvent = new EventDescriptor(0xb01d, 0x1, 0x11, 0x5, 0x14, 0x8, (long)0x4000000000000200);
M3PWorkflowValidationStartedEvent = new EventDescriptor(0xb01c, 0x1, 0x11, 0x5, 0x14, 0x8, (long)0x4000000000000200);
}
}
/// <summary>
/// Constructor.
/// </summary>
public Tracer() : base() { }
/// <summary>
/// Provider Guid.
/// </summary>
protected override Guid ProviderId
{
get
{
return providerId;
}
}
/// <summary>
/// Transfer Event.
/// </summary>
protected override EventDescriptor TransferEvent
{
get
{
return WriteTransferEventEvent;
}
}
/// <summary>
/// WriteTransferEvent (EventId: 0x1f05/7941)
/// </summary>
[EtwEvent(0x1f05)]
public void WriteTransferEvent(Guid currentActivityId, Guid parentActivityId)
{
WriteEvent(WriteTransferEventEvent, currentActivityId, parentActivityId);
}
/// <summary>
/// DebugMessage (EventId: 0xc000/49152)
/// </summary>
[EtwEvent(0xc000)]
public void DebugMessage(string message)
{
WriteEvent(DebugMessageEvent, message);
}
/// <summary>
/// AbortingWorkflowExecution (EventId: 0xb038/45112)
/// </summary>
[EtwEvent(0xb038)]
public void AbortingWorkflowExecution(Guid workflowId, string reason)
{
WriteEvent(M3PAbortingWorkflowExecutionEvent, workflowId, reason);
}
/// <summary>
/// ActivityExecutionFinished (EventId: 0xb03f/45119)
/// </summary>
[EtwEvent(0xb03f)]
public void ActivityExecutionFinished(string activityName)
{
WriteEvent(M3PActivityExecutionFinishedEvent, activityName);
}
/// <summary>
/// ActivityExecutionQueued (EventId: 0xb017/45079)
/// </summary>
[EtwEvent(0xb017)]
public void ActivityExecutionQueued(Guid workflowId, string activityName)
{
WriteEvent(M3PActivityExecutionQueuedEvent, workflowId, activityName);
}
/// <summary>
/// ActivityExecutionStarted (EventId: 0xb018/45080)
/// </summary>
[EtwEvent(0xb018)]
public void ActivityExecutionStarted(string activityName, string activityTypeName)
{
WriteEvent(M3PActivityExecutionStartedEvent, activityName, activityTypeName);
}
/// <summary>
/// BeginContainerParentJobExecution (EventId: 0xb50c/46348)
/// </summary>
[EtwEvent(0xb50c)]
public void BeginContainerParentJobExecution(Guid containerParentJobInstanceId)
{
WriteEvent(M3PBeginContainerParentJobExecutionEvent, containerParentJobInstanceId);
}
/// <summary>
/// BeginCreateNewJob (EventId: 0xb503/46339)
/// </summary>
[EtwEvent(0xb503)]
public void BeginCreateNewJob(Guid trackingId)
{
WriteEvent(M3PBeginCreateNewJobEvent, trackingId);
}
/// <summary>
/// BeginJobLogic (EventId: 0xb506/46342)
/// </summary>
[EtwEvent(0xb506)]
public void BeginJobLogic(Guid workflowJobJobInstanceId)
{
WriteEvent(M3PBeginJobLogicEvent, workflowJobJobInstanceId);
}
/// <summary>
/// BeginProxyChildJobEventHandler (EventId: 0xb512/46354)
/// </summary>
[EtwEvent(0xb512)]
public void BeginProxyChildJobEventHandler(Guid proxyChildJobInstanceId)
{
WriteEvent(M3PBeginProxyChildJobEventHandlerEvent, proxyChildJobInstanceId);
}
/// <summary>
/// BeginProxyJobEventHandler (EventId: 0xb510/46352)
/// </summary>
[EtwEvent(0xb510)]
public void BeginProxyJobEventHandler(Guid proxyJobInstanceId)
{
WriteEvent(M3PBeginProxyJobEventHandlerEvent, proxyJobInstanceId);
}
/// <summary>
/// BeginProxyJobExecution (EventId: 0xb50e/46350)
/// </summary>
[EtwEvent(0xb50e)]
public void BeginProxyJobExecution(Guid proxyJobInstanceId)
{
WriteEvent(M3PBeginProxyJobExecutionEvent, proxyJobInstanceId);
}
/// <summary>
/// BeginRunGarbageCollection (EventId: 0xb514/46356)
/// </summary>
[EtwEvent(0xb514)]
public void BeginRunGarbageCollection()
{
WriteEvent(M3PBeginRunGarbageCollectionEvent);
}
/// <summary>
/// BeginStartWorkflowApplication (EventId: 0xb501/46337)
/// </summary>
[EtwEvent(0xb501)]
public void BeginStartWorkflowApplication(Guid trackingId)
{
WriteEvent(M3PBeginStartWorkflowApplicationEvent, trackingId);
}
/// <summary>
/// BeginWorkflowExecution (EventId: 0xb508/46344)
/// </summary>
[EtwEvent(0xb508)]
public void BeginWorkflowExecution(Guid workflowJobJobInstanceId)
{
WriteEvent(M3PBeginWorkflowExecutionEvent, workflowJobJobInstanceId);
}
/// <summary>
/// CancellingWorkflowExecution (EventId: 0xb037/45111)
/// </summary>
[EtwEvent(0xb037)]
public void CancellingWorkflowExecution(Guid workflowId)
{
WriteEvent(M3PCancellingWorkflowExecutionEvent, workflowId);
}
/// <summary>
/// ChildWorkflowJobAddition (EventId: 0xb50a/46346)
/// </summary>
[EtwEvent(0xb50a)]
public void ChildWorkflowJobAddition(Guid workflowJobInstanceId, Guid containerParentJobInstanceId)
{
WriteEvent(M3PChildWorkflowJobAdditionEvent, workflowJobInstanceId, containerParentJobInstanceId);
}
/// <summary>
/// EndContainerParentJobExecution (EventId: 0xb50d/46349)
/// </summary>
[EtwEvent(0xb50d)]
public void EndContainerParentJobExecution(Guid containerParentJobInstanceId)
{
WriteEvent(M3PEndContainerParentJobExecutionEvent, containerParentJobInstanceId);
}
/// <summary>
/// EndCreateNewJob (EventId: 0xb504/46340)
/// </summary>
[EtwEvent(0xb504)]
public void EndCreateNewJob(Guid trackingId)
{
WriteEvent(M3PEndCreateNewJobEvent, trackingId);
}
/// <summary>
/// EndJobLogic (EventId: 0xb507/46343)
/// </summary>
[EtwEvent(0xb507)]
public void EndJobLogic(Guid workflowJobJobInstanceId)
{
WriteEvent(M3PEndJobLogicEvent, workflowJobJobInstanceId);
}
/// <summary>
/// EndpointDisabled (EventId: 0xb044/45124)
/// </summary>
[EtwEvent(0xb044)]
public void EndpointDisabled(string endpointName, string disabledBy)
{
WriteEvent(M3PEndpointDisabledEvent, endpointName, disabledBy);
}
/// <summary>
/// EndpointEnabled (EventId: 0xb045/45125)
/// </summary>
[EtwEvent(0xb045)]
public void EndpointEnabled(string endpointName, string enabledBy)
{
WriteEvent(M3PEndpointEnabledEvent, endpointName, enabledBy);
}
/// <summary>
/// EndpointModified (EventId: 0xb042/45122)
/// </summary>
[EtwEvent(0xb042)]
public void EndpointModified(string endpointName, string modifiedBy)
{
WriteEvent(M3PEndpointModifiedEvent, endpointName, modifiedBy);
}
/// <summary>
/// EndpointRegistered (EventId: 0xb041/45121)
/// </summary>
[EtwEvent(0xb041)]
public void EndpointRegistered(string endpointName, string endpointType, string registeredBy)
{
WriteEvent(M3PEndpointRegisteredEvent, endpointName, endpointType, registeredBy);
}
/// <summary>
/// EndpointUnregistered (EventId: 0xb043/45123)
/// </summary>
[EtwEvent(0xb043)]
public void EndpointUnregistered(string endpointName, string unregisteredBy)
{
WriteEvent(M3PEndpointUnregisteredEvent, endpointName, unregisteredBy);
}
/// <summary>
/// EndProxyChildJobEventHandler (EventId: 0xb513/46355)
/// </summary>
[EtwEvent(0xb513)]
public void EndProxyChildJobEventHandler(Guid proxyChildJobInstanceId)
{
WriteEvent(M3PEndProxyChildJobEventHandlerEvent, proxyChildJobInstanceId);
}
/// <summary>
/// EndProxyJobEventHandler (EventId: 0xb511/46353)
/// </summary>
[EtwEvent(0xb511)]
public void EndProxyJobEventHandler(Guid proxyJobInstanceId)
{
WriteEvent(M3PEndProxyJobEventHandlerEvent, proxyJobInstanceId);
}
/// <summary>
/// EndProxyJobExecution (EventId: 0xb50f/46351)
/// </summary>
[EtwEvent(0xb50f)]
public void EndProxyJobExecution(Guid proxyJobInstanceId)
{
WriteEvent(M3PEndProxyJobExecutionEvent, proxyJobInstanceId);
}
/// <summary>
/// EndRunGarbageCollection (EventId: 0xb515/46357)
/// </summary>
[EtwEvent(0xb515)]
public void EndRunGarbageCollection()
{
WriteEvent(M3PEndRunGarbageCollectionEvent);
}
/// <summary>
/// EndStartWorkflowApplication (EventId: 0xb502/46338)
/// </summary>
[EtwEvent(0xb502)]
public void EndStartWorkflowApplication(Guid trackingId)
{
WriteEvent(M3PEndStartWorkflowApplicationEvent, trackingId);
}
/// <summary>
/// EndWorkflowExecution (EventId: 0xb509/46345)
/// </summary>
[EtwEvent(0xb509)]
public void EndWorkflowExecution(Guid workflowJobJobInstanceId)
{
WriteEvent(M3PEndWorkflowExecutionEvent, workflowJobJobInstanceId);
}
/// <summary>
/// ErrorImportingWorkflowFromXaml (EventId: 0xb01b/45083)
/// </summary>
[EtwEvent(0xb01b)]
public void ErrorImportingWorkflowFromXaml(Guid workflowId, string errorDescription)
{
WriteEvent(M3PErrorImportingWorkflowFromXamlEvent, workflowId, errorDescription);
}
/// <summary>
/// ForcedWorkflowShutdownError (EventId: 0xb03c/45116)
/// </summary>
[EtwEvent(0xb03c)]
public void ForcedWorkflowShutdownError(Guid workflowId, string errorDescription)
{
WriteEvent(M3PForcedWorkflowShutdownErrorEvent, workflowId, errorDescription);
}
/// <summary>
/// ForcedWorkflowShutdownFinished (EventId: 0xb03b/45115)
/// </summary>
[EtwEvent(0xb03b)]
public void ForcedWorkflowShutdownFinished(Guid workflowId)
{
WriteEvent(M3PForcedWorkflowShutdownFinishedEvent, workflowId);
}
/// <summary>
/// ForcedWorkflowShutdownStarted (EventId: 0xb03a/45114)
/// </summary>
[EtwEvent(0xb03a)]
public void ForcedWorkflowShutdownStarted(Guid workflowId)
{
WriteEvent(M3PForcedWorkflowShutdownStartedEvent, workflowId);
}
/// <summary>
/// ImportedWorkflowFromXaml (EventId: 0xb01a/45082)
/// </summary>
[EtwEvent(0xb01a)]
public void ImportedWorkflowFromXaml(Guid workflowId, string xamlFile)
{
WriteEvent(M3PImportedWorkflowFromXamlEvent, workflowId, xamlFile);
}
/// <summary>
/// ImportingWorkflowFromXaml (EventId: 0xb019/45081)
/// </summary>
[EtwEvent(0xb019)]
public void ImportingWorkflowFromXaml(Guid workflowId, string xamlFile)
{
WriteEvent(M3PImportingWorkflowFromXamlEvent, workflowId, xamlFile);
}
/// <summary>
/// JobCreationComplete (EventId: 0xb032/45106)
/// </summary>
[EtwEvent(0xb032)]
public void JobCreationComplete(Guid jobId, Guid workflowId)
{
WriteEvent(M3PJobCreationCompleteEvent, jobId, workflowId);
}
/// <summary>
/// JobError (EventId: 0xb02e/45102)
/// </summary>
[EtwEvent(0xb02e)]
public void JobError(int jobId, Guid workflowId, string errorDescription)
{
WriteEvent(M3PJobErrorEvent, jobId, workflowId, errorDescription);
}
/// <summary>
/// JobRemoved (EventId: 0xb033/45107)
/// </summary>
[EtwEvent(0xb033)]
public void JobRemoved(Guid parentJobId, Guid childJobId, Guid workflowId)
{
WriteEvent(M3PJobRemovedEvent, parentJobId, childJobId, workflowId);
}
/// <summary>
/// JobRemoveError (EventId: 0xb034/45108)
/// </summary>
[EtwEvent(0xb034)]
public void JobRemoveError(Guid parentJobId, Guid childJobId, Guid workflowId, string error)
{
WriteEvent(M3PJobRemoveErrorEvent, parentJobId, childJobId, workflowId, error);
}
/// <summary>
/// JobStateChanged (EventId: 0xb02d/45101)
/// </summary>
[EtwEvent(0xb02d)]
public void JobStateChanged(int jobId, Guid workflowId, string newState, string oldState)
{
WriteEvent(M3PJobStateChangedEvent, jobId, workflowId, newState, oldState);
}
/// <summary>
/// LoadingWorkflowForExecution (EventId: 0xb035/45109)
/// </summary>
[EtwEvent(0xb035)]
public void LoadingWorkflowForExecution(Guid workflowId)
{
WriteEvent(M3PLoadingWorkflowForExecutionEvent, workflowId);
}
/// <summary>
/// OutOfProcessRunspaceStarted (EventId: 0xb046/45126)
/// </summary>
[EtwEvent(0xb046)]
public void OutOfProcessRunspaceStarted(string command)
{
WriteEvent(M3POutOfProcessRunspaceStartedEvent, command);
}
/// <summary>
/// ParameterSplattingWasPerformed (EventId: 0xb047/45127)
/// </summary>
[EtwEvent(0xb047)]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void ParameterSplattingWasPerformed(string parameters, string computers)
{
WriteEvent(M3PParameterSplattingWasPerformedEvent, parameters, computers);
}
/// <summary>
/// ParentJobCreated (EventId: 0xb031/45105)
/// </summary>
[EtwEvent(0xb031)]
public void ParentJobCreated(Guid jobId)
{
WriteEvent(M3PParentJobCreatedEvent, jobId);
}
/// <summary>
/// PersistenceStoreMaxSizeReached (EventId: 0xb516/46358)
/// </summary>
[EtwEvent(0xb516)]
public void PersistenceStoreMaxSizeReached()
{
WriteEvent(M3PPersistenceStoreMaxSizeReachedEvent);
}
/// <summary>
/// PersistingWorkflow (EventId: 0xb03d/45117)
/// </summary>
[EtwEvent(0xb03d)]
public void PersistingWorkflow(Guid workflowId, string persistPath)
{
WriteEvent(M3PPersistingWorkflowEvent, workflowId, persistPath);
}
/// <summary>
/// ProxyJobRemoteJobAssociation (EventId: 0xb50b/46347)
/// </summary>
[EtwEvent(0xb50b)]
public void ProxyJobRemoteJobAssociation(Guid proxyJobInstanceId, Guid containerParentJobInstanceId)
{
WriteEvent(M3PProxyJobRemoteJobAssociationEvent, proxyJobInstanceId, containerParentJobInstanceId);
}
/// <summary>
/// RemoveJobStarted (EventId: 0xb02c/45100)
/// </summary>
[EtwEvent(0xb02c)]
public void RemoveJobStarted(Guid jobId)
{
WriteEvent(M3PRemoveJobStartedEvent, jobId);
}
/// <summary>
/// RunspaceAvailabilityChanged (EventId: 0xb022/45090)
/// </summary>
[EtwEvent(0xb022)]
public void RunspaceAvailabilityChanged(string runspaceId, string availability)
{
WriteEvent(M3PRunspaceAvailabilityChangedEvent, runspaceId, availability);
}
/// <summary>
/// RunspaceStateChanged (EventId: 0xb023/45091)
/// </summary>
[EtwEvent(0xb023)]
public void RunspaceStateChanged(string runspaceId, string newState, string oldState)
{
WriteEvent(M3PRunspaceStateChangedEvent, runspaceId, newState, oldState);
}
/// <summary>
/// TrackingGuidContainerParentJobCorrelation (EventId: 0xb505/46341)
/// </summary>
[EtwEvent(0xb505)]
public void TrackingGuidContainerParentJobCorrelation(Guid trackingId, Guid containerParentJobInstanceId)
{
WriteEvent(M3PTrackingGuidContainerParentJobCorrelationEvent, trackingId, containerParentJobInstanceId);
}
/// <summary>
/// UnloadingWorkflow (EventId: 0xb039/45113)
/// </summary>
[EtwEvent(0xb039)]
public void UnloadingWorkflow(Guid workflowId)
{
WriteEvent(M3PUnloadingWorkflowEvent, workflowId);
}
/// <summary>
/// WorkflowActivityExecutionFailed (EventId: 0xb021/45089)
/// </summary>
[EtwEvent(0xb021)]
public void WorkflowActivityExecutionFailed(Guid workflowId, string activityName, string failureDescription)
{
WriteEvent(M3PWorkflowActivityExecutionFailedEvent, workflowId, activityName, failureDescription);
}
/// <summary>
/// WorkflowActivityValidated (EventId: 0xb01f/45087)
/// </summary>
[EtwEvent(0xb01f)]
public void WorkflowActivityValidated(Guid workflowId, string activityDisplayName, string activityType)
{
WriteEvent(M3PWorkflowActivityValidatedEvent, workflowId, activityDisplayName, activityType);
}
/// <summary>
/// WorkflowActivityValidationFailed (EventId: 0xb020/45088)
/// </summary>
[EtwEvent(0xb020)]
public void WorkflowActivityValidationFailed(Guid workflowId, string activityDisplayName, string activityType)
{
WriteEvent(M3PWorkflowActivityValidationFailedEvent, workflowId, activityDisplayName, activityType);
}
/// <summary>
/// WorkflowCleanupPerformed (EventId: 0xb028/45096)
/// </summary>
[EtwEvent(0xb028)]
public void WorkflowCleanupPerformed(Guid workflowId)
{
WriteEvent(M3PWorkflowCleanupPerformedEvent, workflowId);
}
/// <summary>
/// WorkflowDeletedFromDisk (EventId: 0xb02a/45098)
/// </summary>
[EtwEvent(0xb02a)]
public void WorkflowDeletedFromDisk(Guid workflowId, string path)
{
WriteEvent(M3PWorkflowDeletedFromDiskEvent, workflowId, path);
}
/// <summary>
/// WorkflowEngineStarted (EventId: 0xb048/45128)
/// </summary>
[EtwEvent(0xb048)]
public void WorkflowEngineStarted(string endpointName)
{
WriteEvent(M3PWorkflowEngineStartedEvent, endpointName);
}
/// <summary>
/// WorkflowExecutionAborted (EventId: 0xb027/45095)
/// </summary>
[EtwEvent(0xb027)]
public void WorkflowExecutionAborted(Guid workflowId)
{
WriteEvent(M3PWorkflowExecutionAbortedEvent, workflowId);
}
/// <summary>
/// WorkflowExecutionCancelled (EventId: 0xb026/45094)
/// </summary>
[EtwEvent(0xb026)]
public void WorkflowExecutionCancelled(Guid workflowId)
{
WriteEvent(M3PWorkflowExecutionCancelledEvent, workflowId);
}
/// <summary>
/// WorkflowExecutionError (EventId: 0xb040/45120)
/// </summary>
[EtwEvent(0xb040)]
public void WorkflowExecutionError(Guid workflowId, string errorDescription)
{
WriteEvent(M3PWorkflowExecutionErrorEvent, workflowId, errorDescription);
}
/// <summary>
/// WorkflowExecutionFinished (EventId: 0xb036/45110)
/// </summary>
[EtwEvent(0xb036)]
public void WorkflowExecutionFinished(Guid workflowId)
{
WriteEvent(M3PWorkflowExecutionFinishedEvent, workflowId);
}
/// <summary>
/// WorkflowExecutionStarted (EventId: 0xb008/45064)
/// </summary>
[EtwEvent(0xb008)]
public void WorkflowExecutionStarted(Guid workflowId, string managedNodes)
{
WriteEvent(M3PWorkflowExecutionStartedEvent, workflowId, managedNodes);
}
/// <summary>
/// WorkflowJobCreated (EventId: 0xb030/45104)
/// </summary>
[EtwEvent(0xb030)]
public void WorkflowJobCreated(Guid parentJobId, Guid childJobId, Guid childWorkflowId)
{
WriteEvent(M3PWorkflowJobCreatedEvent, parentJobId, childJobId, childWorkflowId);
}
/// <summary>
/// WorkflowLoadedForExecution (EventId: 0xb024/45092)
/// </summary>
[EtwEvent(0xb024)]
public void WorkflowLoadedForExecution(Guid workflowId)
{
WriteEvent(M3PWorkflowLoadedForExecutionEvent, workflowId);
}
/// <summary>
/// WorkflowLoadedFromDisk (EventId: 0xb029/45097)
/// </summary>
[EtwEvent(0xb029)]
public void WorkflowLoadedFromDisk(Guid workflowId, string path)
{
WriteEvent(M3PWorkflowLoadedFromDiskEvent, workflowId, path);
}
/// <summary>
/// WorkflowManagerCheckpoint (EventId: 0xb049/45129)
/// </summary>
[EtwEvent(0xb049)]
public void WorkflowManagerCheckpoint(string checkpointPath, string configProviderId, string userName, string path)
{
WriteEvent(M3PWorkflowManagerCheckpointEvent, checkpointPath, configProviderId, userName, path);
}
/// <summary>
/// WorkflowPersisted (EventId: 0xb03e/45118)
/// </summary>
[EtwEvent(0xb03e)]
public void WorkflowPersisted(Guid workflowId)
{
WriteEvent(M3PWorkflowPersistedEvent, workflowId);
}
/// <summary>
/// WorkflowPluginRequestedToShutdown (EventId: 0xb010/45072)
/// </summary>
[EtwEvent(0xb010)]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void WorkflowPluginRequestedToShutdown(string endpointName)
{
WriteEvent(M3PWorkflowPluginRequestedToShutdownEvent, endpointName);
}
/// <summary>
/// WorkflowPluginRestarted (EventId: 0xb011/45073)
/// </summary>
[EtwEvent(0xb011)]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void WorkflowPluginRestarted(string endpointName)
{
WriteEvent(M3PWorkflowPluginRestartedEvent, endpointName);
}
/// <summary>
/// WorkflowPluginStarted (EventId: 0xb007/45063)
/// </summary>
[EtwEvent(0xb007)]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void WorkflowPluginStarted(string endpointName, string user, string hostingMode, string protocol, string configuration)
{
WriteEvent(M3PWorkflowPluginStartedEvent, endpointName, user, hostingMode, protocol, configuration);
}
/// <summary>
/// WorkflowQuotaViolated (EventId: 0xb013/45075)
/// </summary>
[EtwEvent(0xb013)]
public void WorkflowQuotaViolated(string endpointName, string configName, string allowedValue, string valueInQuestion)
{
WriteEvent(M3PWorkflowQuotaViolatedEvent, endpointName, configName, allowedValue, valueInQuestion);
}
/// <summary>
/// WorkflowResumed (EventId: 0xb014/45076)
/// </summary>
[EtwEvent(0xb014)]
public void WorkflowResumed(Guid workflowId)
{
WriteEvent(M3PWorkflowResumedEvent, workflowId);
}
/// <summary>
/// WorkflowResuming (EventId: 0xb012/45074)
/// </summary>
[EtwEvent(0xb012)]
public void WorkflowResuming(Guid workflowId)
{
WriteEvent(M3PWorkflowResumingEvent, workflowId);
}
/// <summary>
/// WorkflowRunspacePoolCreated (EventId: 0xb016/45078)
/// </summary>
[EtwEvent(0xb016)]
public void WorkflowRunspacePoolCreated(Guid workflowId, string managedNode)
{
WriteEvent(M3PWorkflowRunspacePoolCreatedEvent, workflowId, managedNode);
}
/// <summary>
/// WorkflowStateChanged (EventId: 0xb009/45065)
/// </summary>
[EtwEvent(0xb009)]
public void WorkflowStateChanged(Guid workflowId, string newState, string oldState)
{
WriteEvent(M3PWorkflowStateChangedEvent, workflowId, newState, oldState);
}
/// <summary>
/// WorkflowUnloaded (EventId: 0xb025/45093)
/// </summary>
[EtwEvent(0xb025)]
public void WorkflowUnloaded(Guid workflowId)
{
WriteEvent(M3PWorkflowUnloadedEvent, workflowId);
}
/// <summary>
/// WorkflowValidationError (EventId: 0xb01e/45086)
/// </summary>
[EtwEvent(0xb01e)]
public void WorkflowValidationError(Guid workflowId)
{
WriteEvent(M3PWorkflowValidationErrorEvent, workflowId);
}
/// <summary>
/// WorkflowValidationFinished (EventId: 0xb01d/45085)
/// </summary>
[EtwEvent(0xb01d)]
public void WorkflowValidationFinished(Guid workflowId)
{
WriteEvent(M3PWorkflowValidationFinishedEvent, workflowId);
}
/// <summary>
/// WorkflowValidationStarted (EventId: 0xb01c/45084)
/// </summary>
[EtwEvent(0xb01c)]
public void WorkflowValidationStarted(Guid workflowId)
{
WriteEvent(M3PWorkflowValidationStartedEvent, workflowId);
}
}
}
// This code was generated on 02/01/2012 19:52:32
#endif
| |
/*
* Analyst.cs: proxy that makes packet inspection and modifcation interactive
* See the README for usage instructions.
*
* Copyright (c) 2006 Austin Jennings
* Modified by "qode" and "mcortez" on December 21st, 2006 to work with the new
* pregen
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Reflection;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenMetaverse.Packets;
using GridProxy;
public class Analyst : ProxyPlugin
{
private ProxyFrame frame;
private Proxy proxy;
private Hashtable loggedPackets = new Hashtable();
private string logGrep = null;
private Dictionary<PacketType, Dictionary<BlockField, object>> modifiedPackets = new Dictionary<PacketType, Dictionary<BlockField, object>>();
private Assembly openmvAssembly;
private StreamWriter output;
//private PacketDecoder DecodePacket = new PacketDecoder();
public Analyst(ProxyFrame frame)
{
this.frame = frame;
this.proxy = frame.proxy;
}
~Analyst()
{
if (output != null)
output.Close();
}
public override void Init()
{
openmvAssembly = Assembly.Load("OpenMetaverse");
if (openmvAssembly == null) throw new Exception("Assembly load exception");
// build the table of /command delegates
InitializeCommandDelegates();
// handle command line arguments
foreach (string arg in frame.Args)
if (arg == "--log-all")
LogAll();
else if (arg.Contains("--log-whitelist="))
LogWhitelist(arg.Substring(arg.IndexOf('=') + 1));
else if (arg.Contains("--no-log-blacklist="))
NoLogBlacklist(arg.Substring(arg.IndexOf('=') + 1));
else if (arg.Contains("--output="))
SetOutput(arg.Substring(arg.IndexOf('=') + 1));
Console.WriteLine("Analyst loaded");
}
// InitializeCommandDelegates: configure Analyst's commands
private void InitializeCommandDelegates()
{
frame.AddCommand("/log", new ProxyFrame.CommandDelegate(CmdLog));
frame.AddCommand("/-log", new ProxyFrame.CommandDelegate(CmdNoLog));
frame.AddCommand("/grep", new ProxyFrame.CommandDelegate(CmdGrep));
frame.AddCommand("/drop", new ProxyFrame.CommandDelegate(CmdDrop));
frame.AddCommand("/-drop", new ProxyFrame.CommandDelegate(CmdNoDrop));
frame.AddCommand("/set", new ProxyFrame.CommandDelegate(CmdSet));
frame.AddCommand("/-set", new ProxyFrame.CommandDelegate(CmdNoSet));
frame.AddCommand("/inject", new ProxyFrame.CommandDelegate(CmdInject));
frame.AddCommand("/in", new ProxyFrame.CommandDelegate(CmdInject));
}
private static PacketType packetTypeFromName(string name)
{
Type packetTypeType = typeof(PacketType);
System.Reflection.FieldInfo f = packetTypeType.GetField(name);
if (f == null) throw new ArgumentException("Bad packet type");
return (PacketType)Enum.ToObject(packetTypeType, (int)f.GetValue(packetTypeType));
}
// CmdLog: handle a /log command
private void CmdLog(string[] words)
{
if (words.Length != 2)
SayToUser("Usage: /log <packet name>");
else if (words[1] == "*")
{
LogAll();
SayToUser("logging all packets");
}
else
{
PacketType pType;
try
{
pType = packetTypeFromName(words[1]);
}
catch (ArgumentException)
{
SayToUser("Bad packet name: " + words[1]);
return;
}
loggedPackets[pType] = null;
proxy.AddDelegate(pType, Direction.Incoming, new PacketDelegate(LogPacketIn));
proxy.AddDelegate(pType, Direction.Outgoing, new PacketDelegate(LogPacketOut));
SayToUser("logging " + words[1]);
}
}
// CmdNoLog: handle a /-log command
private void CmdNoLog(string[] words)
{
if (words.Length != 2)
SayToUser("Usage: /-log <packet name>");
else if (words[1] == "*")
{
NoLogAll();
SayToUser("stopped logging all packets");
}
else
{
PacketType pType = packetTypeFromName(words[1]);
loggedPackets.Remove(pType);
proxy.RemoveDelegate(pType, Direction.Incoming, new PacketDelegate(LogPacketIn));
proxy.RemoveDelegate(pType, Direction.Outgoing, new PacketDelegate(LogPacketOut));
SayToUser("stopped logging " + words[1]);
}
}
// CmdGrep: handle a /grep command
private void CmdGrep(string[] words)
{
if (words.Length == 1)
{
logGrep = null;
SayToUser("stopped filtering logs");
}
else
{
string[] regexArray = new string[words.Length - 1];
Array.Copy(words, 1, regexArray, 0, words.Length - 1);
logGrep = String.Join(" ", regexArray);
SayToUser("filtering log with " + logGrep);
}
}
private void CmdDrop(string[] words)
{
throw new NotImplementedException();
}
private void CmdNoDrop(string[] words)
{
throw new NotImplementedException();
}
// CmdSet: handle a /set command
private void CmdSet(string[] words)
{
if (words.Length < 5)
SayToUser("Usage: /set <packet name> <block> <field> <value>");
else
{
PacketType pType;
try
{
pType = packetTypeFromName(words[1]);
}
catch (ArgumentException)
{
SayToUser("Bad packet name: " + words[1]);
return;
}
string[] valueArray = new string[words.Length - 4];
Array.Copy(words, 4, valueArray, 0, words.Length - 4);
string valueString = String.Join(" ", valueArray);
object value;
try
{
value = MagicCast(words[1], words[2], words[3], valueString);
}
catch (Exception e)
{
SayToUser(e.Message);
return;
}
Dictionary<BlockField, object> fields;
if (modifiedPackets.ContainsKey(pType))
fields = (Dictionary<BlockField, object>)modifiedPackets[pType];
else
fields = new Dictionary<BlockField, object>();
fields[new BlockField(words[2], words[3])] = value;
modifiedPackets[pType] = fields;
proxy.AddDelegate(pType, Direction.Incoming, new PacketDelegate(ModifyIn));
proxy.AddDelegate(pType, Direction.Outgoing, new PacketDelegate(ModifyOut));
SayToUser("setting " + words[1] + "." + words[2] + "." + words[3] + " = " + valueString);
}
}
// CmdNoSet: handle a /-set command
private void CmdNoSet(string[] words)
{
if (words.Length == 2 && words[1] == "*")
{
foreach (PacketType pType in modifiedPackets.Keys)
{
proxy.RemoveDelegate(pType, Direction.Incoming, new PacketDelegate(ModifyIn));
proxy.RemoveDelegate(pType, Direction.Outgoing, new PacketDelegate(ModifyOut));
}
modifiedPackets = new Dictionary<PacketType, Dictionary<BlockField, object>>();
SayToUser("stopped setting all fields");
}
else if (words.Length == 4)
{
PacketType pType;
try
{
pType = packetTypeFromName(words[1]);
}
catch (ArgumentException)
{
SayToUser("Bad packet name: " + words[1]);
return;
}
if (modifiedPackets.ContainsKey(pType))
{
Dictionary<BlockField, object> fields = modifiedPackets[pType];
fields.Remove(new BlockField(words[2], words[3]));
if (fields.Count == 0)
{
modifiedPackets.Remove(pType);
proxy.RemoveDelegate(pType, Direction.Incoming, new PacketDelegate(ModifyIn));
proxy.RemoveDelegate(pType, Direction.Outgoing, new PacketDelegate(ModifyOut));
}
}
SayToUser("stopped setting " + words[1] + "." + words[2] + "." + words[3]);
}
else
SayToUser("Usage: /-set <packet name> <block> <field>");
}
// CmdInject: handle an /inject command
private void CmdInject(string[] words)
{
if (words.Length < 2)
SayToUser("Usage: /inject <packet file> [value]");
else
{
string[] valueArray = new string[words.Length - 2];
Array.Copy(words, 2, valueArray, 0, words.Length - 2);
string value = String.Join(" ", valueArray);
FileStream fs = null;
StreamReader sr = null;
Direction direction = Direction.Incoming;
string name = null;
string block = null;
object blockObj = null;
Type packetClass = null;
Packet packet = null;
try
{
fs = File.OpenRead(words[1] + ".packet");
sr = new StreamReader(fs);
string line;
while ((line = sr.ReadLine()) != null)
{
Match match;
if (name == null)
{
match = (new Regex(@"^\s*(in|out)\s+(\w+)\s*$")).Match(line);
if (!match.Success)
{
SayToUser("expecting direction and packet name, got: " + line);
return;
}
string lineDir = match.Groups[1].Captures[0].ToString();
string lineName = match.Groups[2].Captures[0].ToString();
if (lineDir == "in")
direction = Direction.Incoming;
else if (lineDir == "out")
direction = Direction.Outgoing;
else
{
SayToUser("expecting 'in' or 'out', got: " + line);
return;
}
name = lineName;
packetClass = openmvAssembly.GetType("OpenMetaverse.Packets." + name + "Packet");
if (packetClass == null) throw new Exception("Couldn't get class " + name + "Packet");
ConstructorInfo ctr = packetClass.GetConstructor(new Type[] { });
if (ctr == null) throw new Exception("Couldn't get suitable constructor for " + name + "Packet");
packet = (Packet)ctr.Invoke(new object[] { });
//Console.WriteLine("Created new " + name + "Packet");
}
else
{
match = (new Regex(@"^\s*\[(\w+)\]\s*$")).Match(line);
if (match.Success)
{
block = match.Groups[1].Captures[0].ToString();
FieldInfo blockField = packetClass.GetField(block);
if (blockField == null) throw new Exception("Couldn't get " + name + "Packet." + block);
Type blockClass = blockField.FieldType;
if (blockClass.IsArray)
{
blockClass = blockClass.GetElementType();
ConstructorInfo ctr = blockClass.GetConstructor(new Type[] { });
if (ctr == null) throw new Exception("Couldn't get suitable constructor for " + blockClass.Name);
blockObj = ctr.Invoke(new object[] { });
object[] arr = (object[])blockField.GetValue(packet);
object[] narr = (object[])Array.CreateInstance(blockClass, arr.Length + 1);
Array.Copy(arr, narr, arr.Length);
narr[arr.Length] = blockObj;
blockField.SetValue(packet, narr);
//Console.WriteLine("Added block "+block);
}
else
{
blockObj = blockField.GetValue(packet);
}
if (blockObj == null) throw new Exception("Got " + name + "Packet." + block + " == null");
//Console.WriteLine("Got block " + name + "Packet." + block);
continue;
}
if (block == null)
{
SayToUser("expecting block name, got: " + line);
return;
}
match = (new Regex(@"^\s*(\w+)\s*=\s*(.*)$")).Match(line);
if (match.Success)
{
string lineField = match.Groups[1].Captures[0].ToString();
string lineValue = match.Groups[2].Captures[0].ToString();
object fval;
//FIXME: use of MagicCast inefficient
if (lineValue == "$Value")
fval = MagicCast(name, block, lineField, value);
else if (lineValue == "$UUID")
fval = UUID.Random();
else if (lineValue == "$AgentID")
fval = frame.AgentID;
else if (lineValue == "$SessionID")
fval = frame.SessionID;
else
fval = MagicCast(name, block, lineField, lineValue);
MagicSetField(blockObj, lineField, fval);
continue;
}
SayToUser("expecting block name or field, got: " + line);
return;
}
}
if (name == null)
{
SayToUser("expecting direction and packet name, got EOF");
return;
}
packet.Header.Reliable = true;
//if (protocolManager.Command(name).Encoded)
// packet.Header.Zerocoded = true;
proxy.InjectPacket(packet, direction);
SayToUser("injected " + words[1]);
}
catch (Exception e)
{
SayToUser("failed to inject " + words[1] + ": " + e.Message);
Console.WriteLine("failed to inject " + words[1] + ": " + e.Message + "\n" + e.StackTrace);
}
finally
{
if (fs != null)
fs.Close();
if (sr != null)
sr.Close();
}
}
}
// SayToUser: send a message to the user as in-world chat
private void SayToUser(string message)
{
ChatFromSimulatorPacket packet = new ChatFromSimulatorPacket();
packet.ChatData.FromName = Utils.StringToBytes("Analyst");
packet.ChatData.SourceID = UUID.Random();
packet.ChatData.OwnerID = frame.AgentID;
packet.ChatData.SourceType = (byte)2;
packet.ChatData.ChatType = (byte)1;
packet.ChatData.Audible = (byte)1;
packet.ChatData.Position = new Vector3(0, 0, 0);
packet.ChatData.Message = Utils.StringToBytes(message);
proxy.InjectPacket(packet, Direction.Incoming);
}
// BlockField: product type for a block name and field name
private struct BlockField
{
public string block;
public string field;
public BlockField(string block, string field)
{
this.block = block;
this.field = field;
}
}
private static void MagicSetField(object obj, string field, object val)
{
Type cls = obj.GetType();
FieldInfo fieldInf = cls.GetField(field);
if (fieldInf == null)
{
PropertyInfo prop = cls.GetProperty(field);
if (prop == null) throw new Exception("Couldn't find field " + cls.Name + "." + field);
prop.SetValue(obj, val, null);
//throw new Exception("FIXME: can't set properties");
}
else
{
fieldInf.SetValue(obj, val);
}
}
// MagicCast: given a packet/block/field name and a string, convert the string to a value of the appropriate type
private object MagicCast(string name, string block, string field, string value)
{
Type packetClass = openmvAssembly.GetType("OpenMetaverse.Packets." + name + "Packet");
if (packetClass == null) throw new Exception("Couldn't get class " + name + "Packet");
FieldInfo blockField = packetClass.GetField(block);
if (blockField == null) throw new Exception("Couldn't get " + name + "Packet." + block);
Type blockClass = blockField.FieldType;
if (blockClass.IsArray) blockClass = blockClass.GetElementType();
// Console.WriteLine("DEBUG: " + blockClass.Name);
FieldInfo fieldField = blockClass.GetField(field); PropertyInfo fieldProp = null;
Type fieldClass = null;
if (fieldField == null)
{
fieldProp = blockClass.GetProperty(field);
if (fieldProp == null) throw new Exception("Couldn't get " + name + "Packet." + block + "." + field);
fieldClass = fieldProp.PropertyType;
}
else
{
fieldClass = fieldField.FieldType;
}
try
{
if (fieldClass == typeof(byte))
{
return Convert.ToByte(value);
}
else if (fieldClass == typeof(ushort))
{
return Convert.ToUInt16(value);
}
else if (fieldClass == typeof(uint))
{
return Convert.ToUInt32(value);
}
else if (fieldClass == typeof(ulong))
{
return Convert.ToUInt64(value);
}
else if (fieldClass == typeof(sbyte))
{
return Convert.ToSByte(value);
}
else if (fieldClass == typeof(short))
{
return Convert.ToInt16(value);
}
else if (fieldClass == typeof(int))
{
return Convert.ToInt32(value);
}
else if (fieldClass == typeof(long))
{
return Convert.ToInt64(value);
}
else if (fieldClass == typeof(float))
{
return Convert.ToSingle(value);
}
else if (fieldClass == typeof(double))
{
return Convert.ToDouble(value);
}
else if (fieldClass == typeof(UUID))
{
return new UUID(value);
}
else if (fieldClass == typeof(bool))
{
if (value.ToLower() == "true")
return true;
else if (value.ToLower() == "false")
return false;
else
throw new Exception();
}
else if (fieldClass == typeof(byte[]))
{
return Utils.StringToBytes(value);
}
else if (fieldClass == typeof(Vector3))
{
Vector3 result;
if (Vector3.TryParse(value, out result))
return result;
else
throw new Exception();
}
else if (fieldClass == typeof(Vector3d))
{
Vector3d result;
if (Vector3d.TryParse(value, out result))
return result;
else
throw new Exception();
}
else if (fieldClass == typeof(Vector4))
{
Vector4 result;
if (Vector4.TryParse(value, out result))
return result;
else
throw new Exception();
}
else if (fieldClass == typeof(Quaternion))
{
Quaternion result;
if (Quaternion.TryParse(value, out result))
return result;
else
throw new Exception();
}
else
{
throw new Exception("unsupported field type " + fieldClass);
}
}
catch
{
throw new Exception("unable to interpret " + value + " as " + fieldClass);
}
}
// ModifyIn: modify an incoming packet
private Packet ModifyIn(Packet packet, IPEndPoint endPoint)
{
return Modify(packet, endPoint, Direction.Incoming);
}
// ModifyOut: modify an outgoing packet
private Packet ModifyOut(Packet packet, IPEndPoint endPoint)
{
return Modify(packet, endPoint, Direction.Outgoing);
}
// Modify: modify a packet
private Packet Modify(Packet packet, IPEndPoint endPoint, Direction direction)
{
if (modifiedPackets.ContainsKey(packet.Type))
{
try
{
Dictionary<BlockField, object> changes = modifiedPackets[packet.Type];
Type packetClass = packet.GetType();
foreach (KeyValuePair<BlockField, object> change in changes)
{
BlockField bf = change.Key;
FieldInfo blockField = packetClass.GetField(bf.block);
if (blockField.FieldType.IsArray) // We're modifying a variable block.
{
// Modify each block in the variable block identically.
// This is really simple, can probably be improved.
object[] blockArray = (object[])blockField.GetValue(packet);
foreach (object blockElement in blockArray)
{
MagicSetField(blockElement, bf.field, change.Value);
}
}
else
{
//Type blockClass = blockField.FieldType;
object blockObject = blockField.GetValue(packet);
MagicSetField(blockObject, bf.field, change.Value);
}
}
}
catch (Exception e)
{
Console.WriteLine("failed to modify " + packet.Type + ": " + e.Message);
Console.WriteLine(e.StackTrace);
}
}
return packet;
}
// LogPacketIn: log an incoming packet
private Packet LogPacketIn(Packet packet, IPEndPoint endPoint)
{
LogPacket(packet, endPoint, Direction.Incoming);
return packet;
}
// LogPacketOut: log an outgoing packet
private Packet LogPacketOut(Packet packet, IPEndPoint endPoint)
{
LogPacket(packet, endPoint, Direction.Outgoing);
return packet;
}
// LogAll: register logging delegates for all packets
private void LogAll()
{
Type packetTypeType = typeof(PacketType);
System.Reflection.MemberInfo[] packetTypes = packetTypeType.GetMembers();
for (int i = 0; i < packetTypes.Length; i++)
{
if (packetTypes[i].MemberType == System.Reflection.MemberTypes.Field && packetTypes[i].DeclaringType == packetTypeType)
{
string name = packetTypes[i].Name;
PacketType pType;
try
{
pType = packetTypeFromName(name);
}
catch (Exception)
{
continue;
}
loggedPackets[pType] = null;
proxy.AddDelegate(pType, Direction.Incoming, new PacketDelegate(LogPacketIn));
proxy.AddDelegate(pType, Direction.Outgoing, new PacketDelegate(LogPacketOut));
}
}
}
private void LogWhitelist(string whitelistFile)
{
try
{
string[] lines = File.ReadAllLines(whitelistFile);
int count = 0;
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i].Trim();
if (line.Length == 0)
continue;
PacketType pType;
try
{
pType = packetTypeFromName(line);
proxy.AddDelegate(pType, Direction.Incoming, new PacketDelegate(LogPacketIn));
proxy.AddDelegate(pType, Direction.Outgoing, new PacketDelegate(LogPacketOut));
++count;
}
catch (ArgumentException)
{
Console.WriteLine("Bad packet name: " + line);
}
}
Console.WriteLine(String.Format("Logging {0} packet types loaded from whitelist", count));
}
catch (Exception)
{
Console.WriteLine("Failed to load packet whitelist from " + whitelistFile);
}
}
private void NoLogBlacklist(string blacklistFile)
{
try
{
string[] lines = File.ReadAllLines(blacklistFile);
int count = 0;
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i].Trim();
if (line.Length == 0)
continue;
PacketType pType;
try
{
pType = packetTypeFromName(line);
string[] noLogStr = new string[] {"/-log", line};
CmdNoLog(noLogStr);
++count;
}
catch (ArgumentException)
{
Console.WriteLine("Bad packet name: " + line);
}
}
Console.WriteLine(String.Format("Not logging {0} packet types loaded from blacklist", count));
}
catch (Exception)
{
Console.WriteLine("Failed to load packet blacklist from " + blacklistFile);
}
}
private void SetOutput(string outputFile)
{
try
{
output = new StreamWriter(outputFile, false);
Console.WriteLine("Logging packets to " + outputFile);
}
catch (Exception)
{
Console.WriteLine(String.Format("Failed to open {0} for logging", outputFile));
}
}
// NoLogAll: unregister logging delegates for all packets
private void NoLogAll()
{
Type packetTypeType = typeof(PacketType);
System.Reflection.MemberInfo[] packetTypes = packetTypeType.GetMembers();
for (int i = 0; i < packetTypes.Length; i++)
{
if (packetTypes[i].MemberType == System.Reflection.MemberTypes.Field && packetTypes[i].DeclaringType == packetTypeType)
{
string name = packetTypes[i].Name;
PacketType pType;
try
{
pType = packetTypeFromName(name);
}
catch (Exception)
{
continue;
}
loggedPackets.Remove(pType);
proxy.RemoveDelegate(pType, Direction.Incoming, new PacketDelegate(LogPacketIn));
proxy.RemoveDelegate(pType, Direction.Outgoing, new PacketDelegate(LogPacketOut));
}
}
}
// LogPacket: dump a packet to the console
private void LogPacket(Packet packet, IPEndPoint endPoint, Direction direction)
{
//string packetText = DecodePacket.PacketToString(packet);
string packetText = PacketDecoder.PacketToString(packet);
if (logGrep == null || (logGrep != null && Regex.IsMatch(packetText, logGrep)))
{
string line = String.Format("{0}\n{1} {2,21} {3,5} {4}{5}{6}"
, packet.Type
, direction == Direction.Incoming ? "<--" : "-->"
, endPoint
, packet.Header.Sequence
, InterpretOptions(packet.Header)
, Environment.NewLine
, packetText
);
Console.WriteLine(line);
if (output != null)
output.WriteLine(line);
}
}
// InterpretOptions: produce a string representing a packet's header options
private static string InterpretOptions(Header header)
{
return "["
+ (header.AppendedAcks ? "Ack" : " ")
+ " "
+ (header.Resent ? "Res" : " ")
+ " "
+ (header.Reliable ? "Rel" : " ")
+ " "
+ (header.Zerocoded ? "Zer" : " ")
+ "]"
;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Security
{
//
// This is a wrapping stream that does data encryption/decryption based on a successfully authenticated SSPI context.
// This file contains the private implementation.
//
public partial class NegotiateStream : AuthenticatedStream
{
private static AsyncCallback s_writeCallback = new AsyncCallback(WriteCallback);
private static AsyncProtocolCallback s_readCallback = new AsyncProtocolCallback(ReadCallback);
private int _NestedWrite;
private int _NestedRead;
private byte[] _ReadHeader;
// Never updated directly, special properties are used.
private byte[] _InternalBuffer;
private int _InternalOffset;
private int _InternalBufferCount;
private void InitializeStreamPart()
{
_ReadHeader = new byte[4];
}
private byte[] InternalBuffer
{
get
{
return _InternalBuffer;
}
}
private int InternalOffset
{
get
{
return _InternalOffset;
}
}
private int InternalBufferCount
{
get
{
return _InternalBufferCount;
}
}
private void DecrementInternalBufferCount(int decrCount)
{
_InternalOffset += decrCount;
_InternalBufferCount -= decrCount;
}
private void EnsureInternalBufferSize(int bytes)
{
_InternalBufferCount = bytes;
_InternalOffset = 0;
if (InternalBuffer == null || InternalBuffer.Length < bytes)
{
_InternalBuffer = new byte[bytes];
}
}
private void AdjustInternalBufferOffsetSize(int bytes, int offset)
{
_InternalBufferCount = bytes;
_InternalOffset = offset;
}
//
// Validates user parameters for all Read/Write methods.
//
private void ValidateParameters(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
if (count > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.net_offset_plus_count);
}
}
//
// Combined sync/async write method. For sync request asyncRequest==null.
//
private void ProcessWrite(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
ValidateParameters(buffer, offset, count);
if (Interlocked.Exchange(ref _NestedWrite, 1) == 1)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, (asyncRequest != null ? "BeginWrite" : "Write"), "write"));
}
bool failed = false;
try
{
StartWriting(buffer, offset, count, asyncRequest);
}
catch (Exception e)
{
failed = true;
if (e is IOException)
{
throw;
}
throw new IOException(SR.net_io_write, e);
}
finally
{
if (asyncRequest == null || failed)
{
_NestedWrite = 0;
}
}
}
private void StartWriting(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
// We loop to this method from the callback.
// If the last chunk was just completed from async callback (count < 0), we complete user request.
if (count >= 0)
{
byte[] outBuffer = null;
do
{
int chunkBytes = Math.Min(count, NegoState.MaxWriteDataSize);
int encryptedBytes;
try
{
encryptedBytes = _negoState.EncryptData(buffer, offset, chunkBytes, ref outBuffer);
}
catch (Exception e)
{
throw new IOException(SR.net_io_encrypt, e);
}
if (asyncRequest != null)
{
// prepare for the next request
asyncRequest.SetNextRequest(buffer, offset + chunkBytes, count - chunkBytes, null);
Task t = InnerStream.WriteAsync(outBuffer, 0, encryptedBytes);
if (t.IsCompleted)
{
t.GetAwaiter().GetResult();
}
else
{
IAsyncResult ar = TaskToApm.Begin(t, s_writeCallback, asyncRequest);
if (!ar.CompletedSynchronously)
{
return;
}
TaskToApm.End(ar);
}
}
else
{
InnerStream.Write(outBuffer, 0, encryptedBytes);
}
offset += chunkBytes;
count -= chunkBytes;
} while (count != 0);
}
if (asyncRequest != null)
{
asyncRequest.CompleteUser();
}
}
//
// Combined sync/async read method. For sync request asyncRequest==null.
// There is a little overhead because we need to pass buffer/offset/count used only in sync.
// Still the benefit is that we have a common sync/async code path.
//
private int ProcessRead(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
ValidateParameters(buffer, offset, count);
if (Interlocked.Exchange(ref _NestedRead, 1) == 1)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, (asyncRequest != null ? "BeginRead" : "Read"), "read"));
}
bool failed = false;
try
{
if (InternalBufferCount != 0)
{
int copyBytes = InternalBufferCount > count ? count : InternalBufferCount;
if (copyBytes != 0)
{
Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, copyBytes);
DecrementInternalBufferCount(copyBytes);
}
asyncRequest?.CompleteUser(copyBytes);
return copyBytes;
}
// Performing actual I/O.
return StartReading(buffer, offset, count, asyncRequest);
}
catch (Exception e)
{
failed = true;
if (e is IOException)
{
throw;
}
throw new IOException(SR.net_io_read, e);
}
finally
{
if (asyncRequest == null || failed)
{
_NestedRead = 0;
}
}
}
//
// To avoid recursion when 0 bytes have been decrypted, loop until decryption results in at least 1 byte.
//
private int StartReading(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
int result;
// When we read -1 bytes means we have decrypted 0 bytes, need looping.
while ((result = StartFrameHeader(buffer, offset, count, asyncRequest)) == -1);
return result;
}
private int StartFrameHeader(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
int readBytes = 0;
if (asyncRequest != null)
{
asyncRequest.SetNextRequest(_ReadHeader, 0, _ReadHeader.Length, s_readCallback);
FixedSizeReader.ReadPacketAsync(InnerStream, asyncRequest);
if (!asyncRequest.MustCompleteSynchronously)
{
return 0;
}
readBytes = asyncRequest.Result;
}
else
{
readBytes = FixedSizeReader.ReadPacket(InnerStream, _ReadHeader, 0, _ReadHeader.Length);
}
return StartFrameBody(readBytes, buffer, offset, count, asyncRequest);
}
private int StartFrameBody(int readBytes, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
if (readBytes == 0)
{
//EOF
asyncRequest?.CompleteUser(0);
return 0;
}
if (!(readBytes == _ReadHeader.Length))
{
NetEventSource.Fail(this, $"Frame size must be 4 but received {readBytes} bytes.");
}
// Replace readBytes with the body size recovered from the header content.
readBytes = _ReadHeader[3];
readBytes = (readBytes << 8) | _ReadHeader[2];
readBytes = (readBytes << 8) | _ReadHeader[1];
readBytes = (readBytes << 8) | _ReadHeader[0];
//
// The body carries 4 bytes for trailer size slot plus trailer, hence <=4 frame size is always an error.
// Additionally we'd like to restrict the read frame size to 64k.
//
if (readBytes <= 4 || readBytes > NegoState.MaxReadFrameSize)
{
throw new IOException(SR.net_frame_read_size);
}
//
// Always pass InternalBuffer for SSPI "in place" decryption.
// A user buffer can be shared by many threads in that case decryption/integrity check may fail cause of data corruption.
//
EnsureInternalBufferSize(readBytes);
if (asyncRequest != null)
{
asyncRequest.SetNextRequest(InternalBuffer, 0, readBytes, s_readCallback);
FixedSizeReader.ReadPacketAsync(InnerStream, asyncRequest);
if (!asyncRequest.MustCompleteSynchronously)
{
return 0;
}
readBytes = asyncRequest.Result;
}
else //Sync
{
readBytes = FixedSizeReader.ReadPacket(InnerStream, InternalBuffer, 0, readBytes);
}
return ProcessFrameBody(readBytes, buffer, offset, count, asyncRequest);
}
private int ProcessFrameBody(int readBytes, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
if (readBytes == 0)
{
// We already checked that the frame body is bigger than 0 bytes
// Hence, this is an EOF ... fire.
throw new IOException(SR.net_io_eof);
}
// Decrypt into internal buffer, change "readBytes" to count now _Decrypted Bytes_
int internalOffset;
readBytes = _negoState.DecryptData(InternalBuffer, 0, readBytes, out internalOffset);
// Decrypted data start from zero offset, the size can be shrunk after decryption.
AdjustInternalBufferOffsetSize(readBytes, internalOffset);
if (readBytes == 0 && count != 0)
{
// Read again.
return -1;
}
if (readBytes > count)
{
readBytes = count;
}
Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, readBytes);
// This will adjust both the remaining internal buffer count and the offset.
DecrementInternalBufferCount(readBytes);
asyncRequest?.CompleteUser(readBytes);
return readBytes;
}
private static void WriteCallback(IAsyncResult transportResult)
{
if (transportResult.CompletedSynchronously)
{
return;
}
if (!(transportResult.AsyncState is AsyncProtocolRequest))
{
NetEventSource.Fail(transportResult, "State type is wrong, expected AsyncProtocolRequest.");
}
AsyncProtocolRequest asyncRequest = (AsyncProtocolRequest)transportResult.AsyncState;
try
{
NegotiateStream negoStream = (NegotiateStream)asyncRequest.AsyncObject;
TaskToApm.End(transportResult);
if (asyncRequest.Count == 0)
{
// This was the last chunk.
asyncRequest.Count = -1;
}
negoStream.StartWriting(asyncRequest.Buffer, asyncRequest.Offset, asyncRequest.Count, asyncRequest);
}
catch (Exception e)
{
if (asyncRequest.IsUserCompleted)
{
// This will throw on a worker thread.
throw;
}
asyncRequest.CompleteUserWithError(e);
}
}
private static void ReadCallback(AsyncProtocolRequest asyncRequest)
{
// Async ONLY completion.
try
{
NegotiateStream negoStream = (NegotiateStream)asyncRequest.AsyncObject;
BufferAsyncResult bufferResult = (BufferAsyncResult)asyncRequest.UserAsyncResult;
// This is an optimization to avoid an additional callback.
if ((object)asyncRequest.Buffer == (object)negoStream._ReadHeader)
{
negoStream.StartFrameBody(asyncRequest.Result, bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest);
}
else
{
if (-1 == negoStream.ProcessFrameBody(asyncRequest.Result, bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest))
{
// In case we decrypted 0 bytes, start another reading.
negoStream.StartReading(bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest);
}
}
}
catch (Exception e)
{
if (asyncRequest.IsUserCompleted)
{
// This will throw on a worker thread.
throw;
}
asyncRequest.CompleteUserWithError(e);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.Xml.Schema
{
using System;
using Microsoft.Xml;
using System.Collections;
using System.Text;
using System.Diagnostics;
internal class NamespaceList
{
public enum ListType
{
Any,
Other,
Set
};
private ListType _type = ListType.Any;
private Hashtable _set = null;
private string _targetNamespace;
public NamespaceList()
{
}
public NamespaceList(string namespaces, string targetNamespace)
{
Debug.Assert(targetNamespace != null);
_targetNamespace = targetNamespace;
namespaces = namespaces.Trim();
if (namespaces == "##any" || namespaces.Length == 0)
{
_type = ListType.Any;
}
else if (namespaces == "##other")
{
_type = ListType.Other;
}
else
{
_type = ListType.Set;
_set = new Hashtable();
string[] splitString = XmlConvert.SplitString(namespaces);
for (int i = 0; i < splitString.Length; ++i)
{
if (splitString[i] == "##local")
{
_set[string.Empty] = string.Empty;
}
else if (splitString[i] == "##targetNamespace")
{
_set[targetNamespace] = targetNamespace;
}
else
{
XmlConvert.ToUri(splitString[i]); // can throw
_set[splitString[i]] = splitString[i];
}
}
}
}
public NamespaceList Clone()
{
NamespaceList nsl = (NamespaceList)MemberwiseClone();
if (_type == ListType.Set)
{
Debug.Assert(_set != null);
nsl._set = (Hashtable)(_set.Clone());
}
return nsl;
}
public ListType Type
{
get { return _type; }
}
public string Excluded
{
get { return _targetNamespace; }
}
public ICollection Enumerate
{
get
{
switch (_type)
{
case ListType.Set:
return _set.Keys;
case ListType.Other:
case ListType.Any:
default:
throw new InvalidOperationException();
}
}
}
public virtual bool Allows(string ns)
{
switch (_type)
{
case ListType.Any:
return true;
case ListType.Other:
return ns != _targetNamespace && ns.Length != 0;
case ListType.Set:
return _set[ns] != null;
}
Debug.Assert(false);
return false;
}
public bool Allows(XmlQualifiedName qname)
{
return Allows(qname.Namespace);
}
public override string ToString()
{
switch (_type)
{
case ListType.Any:
return "##any";
case ListType.Other:
return "##other";
case ListType.Set:
StringBuilder sb = new StringBuilder();
bool first = true;
foreach (string s in _set.Keys)
{
if (first)
{
first = false;
}
else
{
sb.Append(" ");
}
if (s == _targetNamespace)
{
sb.Append("##targetNamespace");
}
else if (s.Length == 0)
{
sb.Append("##local");
}
else
{
sb.Append(s);
}
}
return sb.ToString();
}
Debug.Assert(false);
return string.Empty;
}
public static bool IsSubset(NamespaceList sub, NamespaceList super)
{
if (super._type == ListType.Any)
{
return true;
}
else if (sub._type == ListType.Other && super._type == ListType.Other)
{
return super._targetNamespace == sub._targetNamespace;
}
else if (sub._type == ListType.Set)
{
if (super._type == ListType.Other)
{
return !sub._set.Contains(super._targetNamespace);
}
else
{
Debug.Assert(super._type == ListType.Set);
foreach (string ns in sub._set.Keys)
{
if (!super._set.Contains(ns))
{
return false;
}
}
return true;
}
}
return false;
}
public static NamespaceList Union(NamespaceList o1, NamespaceList o2, bool v1Compat)
{
NamespaceList nslist = null;
Debug.Assert(o1 != o2);
if (o1._type == ListType.Any)
{ //clause 2 - o1 is Any
nslist = new NamespaceList();
}
else if (o2._type == ListType.Any)
{ //clause 2 - o2 is Any
nslist = new NamespaceList();
}
else if (o1._type == ListType.Set && o2._type == ListType.Set)
{ //clause 3 , both are sets
nslist = o1.Clone();
foreach (string ns in o2._set.Keys)
{
nslist._set[ns] = ns;
}
}
else if (o1._type == ListType.Other && o2._type == ListType.Other)
{ //clause 4, both are negations
if (o1._targetNamespace == o2._targetNamespace)
{ //negation of same value
nslist = o1.Clone();
}
else
{ //Not a breaking change, going from not expressible to not(absent)
nslist = new NamespaceList("##other", string.Empty); //clause 4, negations of different values, result is not(absent)
}
}
else if (o1._type == ListType.Set && o2._type == ListType.Other)
{
if (v1Compat)
{
if (o1._set.Contains(o2._targetNamespace))
{
nslist = new NamespaceList();
}
else
{ //This was not there originally in V1, added for consistency since its not breaking
nslist = o2.Clone();
}
}
else
{
if (o2._targetNamespace != string.Empty)
{ //clause 5, o1 is set S, o2 is not(tns)
nslist = o1.CompareSetToOther(o2);
}
else if (o1._set.Contains(string.Empty))
{ //clause 6.1 - set S includes absent, o2 is not(absent)
nslist = new NamespaceList();
}
else
{ //clause 6.2 - set S does not include absent, result is not(absent)
nslist = new NamespaceList("##other", string.Empty);
}
}
}
else if (o2._type == ListType.Set && o1._type == ListType.Other)
{
if (v1Compat)
{
if (o2._set.Contains(o2._targetNamespace))
{
nslist = new NamespaceList();
}
else
{
nslist = o1.Clone();
}
}
else
{ //New rules
if (o1._targetNamespace != string.Empty)
{ //clause 5, o1 is set S, o2 is not(tns)
nslist = o2.CompareSetToOther(o1);
}
else if (o2._set.Contains(string.Empty))
{ //clause 6.1 - set S includes absent, o2 is not(absent)
nslist = new NamespaceList();
}
else
{ //clause 6.2 - set S does not include absent, result is not(absent)
nslist = new NamespaceList("##other", string.Empty);
}
}
}
return nslist;
}
private NamespaceList CompareSetToOther(NamespaceList other)
{
//clause 5.1
NamespaceList nslist = null;
if (_set.Contains(other._targetNamespace))
{ //S contains negated ns
if (_set.Contains(string.Empty))
{ // AND S contains absent
nslist = new NamespaceList(); //any is the result
}
else
{ //clause 5.2
nslist = new NamespaceList("##other", string.Empty);
}
}
else if (_set.Contains(string.Empty))
{ //clause 5.3 - Not expressible
nslist = null;
}
else
{ //clause 5.4 - Set S does not contain negated ns or absent
nslist = other.Clone();
}
return nslist;
}
public static NamespaceList Intersection(NamespaceList o1, NamespaceList o2, bool v1Compat)
{
NamespaceList nslist = null;
Debug.Assert(o1 != o2); //clause 1
if (o1._type == ListType.Any)
{ //clause 2 - o1 is any
nslist = o2.Clone();
}
else if (o2._type == ListType.Any)
{ //clause 2 - o2 is any
nslist = o1.Clone();
}
else if (o1._type == ListType.Set && o2._type == ListType.Other)
{ //Clause 3 o2 is other
nslist = o1.Clone();
nslist.RemoveNamespace(o2._targetNamespace);
if (!v1Compat)
{
nslist.RemoveNamespace(string.Empty); //remove ##local
}
}
else if (o1._type == ListType.Other && o2._type == ListType.Set)
{ //Clause 3 o1 is other
nslist = o2.Clone();
nslist.RemoveNamespace(o1._targetNamespace);
if (!v1Compat)
{
nslist.RemoveNamespace(string.Empty); //remove ##local
}
}
else if (o1._type == ListType.Set && o2._type == ListType.Set)
{ //clause 4
nslist = o1.Clone();
nslist = new NamespaceList();
nslist._type = ListType.Set;
nslist._set = new Hashtable();
foreach (string ns in o1._set.Keys)
{
if (o2._set.Contains(ns))
{
nslist._set.Add(ns, ns);
}
}
}
else if (o1._type == ListType.Other && o2._type == ListType.Other)
{
if (o1._targetNamespace == o2._targetNamespace)
{ //negation of same namespace name
nslist = o1.Clone();
return nslist;
}
if (!v1Compat)
{
if (o1._targetNamespace == string.Empty)
{ // clause 6 - o1 is negation of absent
nslist = o2.Clone();
}
else if (o2._targetNamespace == string.Empty)
{ //clause 6 - o1 is negation of absent
nslist = o1.Clone();
}
}
//if it comes here, its not expressible //clause 5
}
return nslist;
}
private void RemoveNamespace(string tns)
{
if (_set[tns] != null)
{
_set.Remove(tns);
}
}
public bool IsEmpty()
{
return ((_type == ListType.Set) && ((_set == null) || _set.Count == 0));
}
};
internal class NamespaceListV1Compat : NamespaceList
{
public NamespaceListV1Compat(string namespaces, string targetNamespace) : base(namespaces, targetNamespace) { }
public override bool Allows(string ns)
{
if (this.Type == ListType.Other)
{
return ns != Excluded;
}
else
{
return base.Allows(ns);
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Globalization;
namespace xmljr.math
{
/// <summary>
/// Summary description for Vector4.
/// </summary>
///
internal class VectorConverter : ExpandableObjectConverter
{
public override bool CanConvertFrom( ITypeDescriptorContext context, Type t)
{
if (t == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, t);
}
public override object ConvertFrom( ITypeDescriptorContext context, CultureInfo info, object value)
{
/*
if (value is string)
{
return new Vector4();
}
*/
/*
if (value is string)
{
try
{
string s = (string) value;
// parse the format "Last, First (Age)"
//
int comma = s.IndexOf(',');
if (comma != -1)
{
// now that we have the comma, get
// the last name.
string last = s.Substring(0, comma);
int paren = s.LastIndexOf('(');
if (paren != -1 &&
s.LastIndexOf(')') == s.Length - 1)
{
// pick up the first name
string first =
s.Substring(comma + 1,
paren - comma - 1);
// get the age
int age = Int32.Parse(
s.Substring(paren + 1,
s.Length - paren - 2));
Person p = new Person();
p.Age = age;
p.LastName = last.Trim();
.FirstName = first.Trim();
return p;
}
}
}
catch {}
// if we got this far, complain that we
// couldn't parse the string
//
throw new ArgumentException(
"Can not convert '" + (string)value +
"' to type Person");
}
*/
return base.ConvertFrom(context, info, value);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destType)
{
if (destType == typeof(string) && value is Vector4)
{
Vector4 v = (Vector4) value;
return "" + v.x + "," + v.y + "," + v.z + "," + v.w;
}
if (destType == typeof(string) && value is Vector3)
{
Vector3 v = (Vector3) value;
return "" + v.x + "," + v.y + "," + v.z;
}
if (destType == typeof(string) && value is Vector2)
{
Vector2 v = (Vector2) value;
return "" + v.x + "," + v.y;
}
return base.ConvertTo(context, culture, value, destType);
}
}
[TypeConverter(typeof(VectorConverter))]
public class Vector4
{
private double [] data;
public double x { get { return data[0]; } set { data[0] = value; } }
public double y { get { return data[1]; } set { data[1] = value; } }
public double z { get { return data[2]; } set { data[2] = value; } }
public double w { get { return data[3]; } set { data[3] = value; } }
public double[] v { get { return data; } }
public Vector4(double X, double Y, double Z, double W)
{ data = new double[] {X,Y,Z,W}; }
public Vector4()
{ data = new double[] { 0.0, 0.0, 0.0, 0.0 }; }
public Vector4(Vector3 V, double w)
{ data = new double[] {V.x,V.y,V.z,w}; }
public Vector4(double[] A)
{ data = new double[] {A[0],A[1],A[2],A[3]}; }
public float [] getFloat()
{
float [] arr = new float[4];
arr[0] = (float) data[0];
arr[1] = (float) data[1];
arr[2] = (float) data[2];
arr[3] = (float) data[3];
return arr;
}
public static double dot2(Vector4 a, Vector4 b)
{ return a.x * b.x + a.y * b.y; }
public static double dot3(Vector4 a, Vector4 b)
{ return a.x * b.x + a.y * b.y + a.z * b.z; }
public static double dot4(Vector4 a, Vector4 b)
{ return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; }
public void normalize3()
{
double L = Length3;
x /= L;
y /= L;
z /= L;
}
public double Length3
{ get { return System.Math.Sqrt(dot3(this,this)); } }
public static Vector3 cross(Vector4 a, Vector4 b)
{
return new Vector3( a.y * b.z - a.z * b.y,
-(a.x * b.z - a.z * b.x),
a.x * b.y - a.y * b.x); }
public static Vector4 operator -(Vector4 c)
{ return new Vector4(-c.x,-c.y,-c.z,-c.w); }
public static Vector4 operator +(Vector4 a,Vector4 b)
{ return new Vector4(a.x + b.x,a.y + b.y,a.z + b.z,a.w + b.w); }
public static Vector4 operator /(Vector4 a,double s)
{ return new Vector4(a.x/s,a.y/s,a.z/s,a.w/s); }
public static Vector4 operator *(Vector4 a,double s)
{ return new Vector4(a.x*s,a.y*s,a.z*s,a.w*s); }
}
[TypeConverter(typeof(VectorConverter))]
public class Vector3
{
private double [] data;
public double x { get { return data[0]; } set { data[0] = value; } }
public double y { get { return data[1]; } set { data[1] = value; } }
public double z { get { return data[2]; } set { data[2] = value; } }
public double[] v { get { return data; } }
public Vector3(double X, double Y, double Z)
{ data = new double[] {X,Y,Z}; }
public Vector3()
{ data = new double[] { 0.0, 0.0, 0.0 }; }
public float [] getFloat()
{
float [] arr = new float[3];
arr[0] = (float) data[0];
arr[1] = (float) data[1];
arr[2] = (float) data[2];
return arr;
}
public Vector3 copy()
{ return new Vector3(x,y,z); }
public static double dot2(Vector3 a, Vector3 b)
{ return a.x * b.x + a.y * b.y; }
public static double dot3(Vector3 a, Vector3 b)
{ return a.x * b.x + a.y * b.y + a.z * b.z; }
public void normalize3()
{
double L = Length3;
x /= L;
y /= L;
z /= L;
}
public double Length3
{ get { return System.Math.Sqrt(dot3(this,this)); } }
public static Vector3 cross(Vector3 a, Vector3 b)
{
return new Vector3( a.y * b.z - a.z * b.y,
-(a.x * b.z - a.z * b.x),
a.x * b.y - a.y * b.x); }
public static Vector3 operator -(Vector3 c)
{ return new Vector3(-c.x,-c.y,-c.z); }
public static Vector3 operator +(Vector3 a,Vector3 b)
{ return new Vector3(a.x + b.x,a.y + b.y,a.z + b.z); }
public static Vector3 operator /(Vector3 a,double s)
{ return new Vector3(a.x/s,a.y/s,a.z/s); }
public static Vector3 operator *(Vector3 a,double s)
{ return new Vector3(a.x*s,a.y*s,a.z*s); }
public void pos()
{
x = Math.Abs(x);
y = Math.Abs(y);
z = Math.Abs(z);
}
public static double min(double a, double b)
{
if(a < b) return a;
return b;
} public static double max(double a, double b)
{
if(b < a) return a;
return b;
}
public static Vector3 Min(Vector3 a, Vector3 b)
{
return new Vector3( min(a.x,b.x), min(a.y,b.y), min(a.z,b.z) );
}
public static Vector3 Max(Vector3 a, Vector3 b)
{
return new Vector3( max(a.x,b.x), max(a.y,b.y), max(a.z,b.z) );
}
}
[TypeConverter(typeof(VectorConverter))]
public class Vector2
{
private double [] data;
public double x { get { return data[0]; } set { data[0] = value; } }
public double y { get { return data[1]; } set { data[1] = value; } }
public double[] v { get { return data; } }
public Vector2(double X, double Y)
{ data = new double[] {X,Y}; }
public Vector2()
{ data = new double[] { 0.0, 0.0 }; }
public static double dot2(Vector2 a, Vector2 b)
{ return a.x * b.x + a.y * b.y; }
public void normalize2()
{
double L = Length2;
x /= L;
y /= L;
}
public double Length2
{ get { return System.Math.Sqrt(dot2(this,this)); } }
public static Vector2 operator -(Vector2 c)
{ return new Vector2(-c.x,-c.y); }
public static Vector2 operator +(Vector2 a,Vector2 b)
{ return new Vector2(a.x + b.x,a.y + b.y); }
public static Vector2 operator /(Vector2 a,double s)
{ return new Vector2(a.x/s,a.y/s); }
public static Vector2 operator *(Vector2 a,double s)
{ return new Vector2(a.x*s,a.y*s); }
}
}
| |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Chutzpah.FrameworkDefinitions;
using Chutzpah.Models;
using Chutzpah.Wrappers;
using Moq;
using Xunit;
namespace Chutzpah.Facts
{
public class ReferenceProcessorFacts
{
private class TestableReferenceProcessor : Testable<ReferenceProcessor>
{
public IFrameworkDefinition FrameworkDefinition { get; set; }
public TestableReferenceProcessor()
{
var frameworkMock = Mock<IFrameworkDefinition>();
frameworkMock.Setup(x => x.FileUsesFramework(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<PathType>())).Returns(true);
frameworkMock.Setup(x => x.FrameworkKey).Returns("qunit");
frameworkMock.Setup(x => x.GetTestRunner(It.IsAny<ChutzpahTestSettingsFile>())).Returns("qunitRunner.js");
frameworkMock.Setup(x => x.GetTestHarness(It.IsAny<ChutzpahTestSettingsFile>())).Returns("qunit.html");
frameworkMock.Setup(x => x.GetFileDependencies(It.IsAny<ChutzpahTestSettingsFile>())).Returns(new[] { "qunit.js", "qunit.css" });
FrameworkDefinition = frameworkMock.Object;
Mock<IFileProbe>().Setup(x => x.FindFilePath(It.IsAny<string>())).Returns<string>(x => x);
Mock<IFileSystemWrapper>().Setup(x => x.GetText(It.IsAny<string>())).Returns(string.Empty);
}
}
public class SetupAmdFilePaths
{
[Fact]
public void Will_set_amd_path_for_reference_path()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\path";
var referencedFile = new ReferencedFile {Path = @"C:\some\path\code\test.js"};
var referenceFiles = new List<ReferencedFile> { referencedFile };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles,testHarnessDirectory, new ChutzpahTestSettingsFile().InheritFromDefault());
Assert.Equal("code/test",referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_make_amd_path_relative_to_amdbaseurl_if_no_amdappdirectory_if_given()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\path";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile { AMDBaseUrl = @"C:\some\other" };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../path/code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_make_amd_path_relative_to_amdappdirectory_if_given()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\path";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile { AMDAppDirectory = @"C:\some\other" };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../path/code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_not_replace_directory_name_containing_extension_in_relative_amd_path()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\src\folder";
var referencedFile = new ReferencedFile { Path = @"C:\some\path.jstests\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile { };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../../path.jstests/code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_not_replace_directory_name_containing_extension_in_relative_amd_path_with_legacy_setting()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\src\folder";
var referencedFile = new ReferencedFile { Path = @"C:\some\path.jstests\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile { AMDBasePath = @"C:\some\other" };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../src/folder/../../path.jstests/code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_make_amd_path_relative_to_amdbasepath_with_legacy_setting()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\path";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile {AMDBasePath = @"C:\some\other"};
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../path/code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_make_amd_path_relative_to_testHarnessLocation()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\src\folder";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile { };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../../path/code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_make_amd_path_relative_to_testHarnessLocation_and_amdbasepath()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"c:\some\path\subFolder";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
var settings = new ChutzpahTestSettingsFile { AMDBasePath = @"C:\some\other" };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, settings);
Assert.Equal("../path/subFolder/../code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_set_amd_path_ignoring_the_case()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"C:\Some\Path";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, new ChutzpahTestSettingsFile().InheritFromDefault());
Assert.Equal("code/test", referencedFile.AmdFilePath);
Assert.Null(referencedFile.AmdGeneratedFilePath);
}
[Fact]
public void Will_set_amd_path_for_reference_path_and_generated_path()
{
var processor = new TestableReferenceProcessor();
var testHarnessDirectory = @"C:\some\path";
var referencedFile = new ReferencedFile { Path = @"C:\some\path\code\test.ts", GeneratedFilePath = @"C:\some\path\code\_Chutzpah.1.test.js" };
var referenceFiles = new List<ReferencedFile> { referencedFile };
processor.ClassUnderTest.SetupAmdFilePaths(referenceFiles, testHarnessDirectory, new ChutzpahTestSettingsFile().InheritFromDefault());
Assert.Equal("code/test", referencedFile.AmdFilePath);
}
}
public class GetReferencedFiles
{
[Fact]
public void Will_add_reference_file_to_referenced_files()
{
var processor = new TestableReferenceProcessor();
var settings = new ChutzpahTestSettingsFile { }.InheritFromDefault();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var text = (@"/// <reference path=""lib.js"" />
some javascript code");
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\lib.js" && x.IncludeInTestHarness));
}
[Fact]
public void Will_handle_multiple_test_files()
{
var processor = new TestableReferenceProcessor();
var settings = new ChutzpahTestSettingsFile { }.InheritFromDefault();
var referenceFiles = new List<ReferencedFile> {
new ReferencedFile { IsFileUnderTest = true, Path = @"path\test1.js", ExpandReferenceComments = true },
new ReferencedFile { IsFileUnderTest = true, Path = @"path\test2.js", ExpandReferenceComments = true }};
var text = (@"/// <reference path=""lib.js"" />
some javascript code");
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test1.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test2.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.Equal(2, referenceFiles.Count(x => x.IsFileUnderTest));
}
[Fact]
public void Will_exclude_reference_from_harness_in_amd_mode()
{
var processor = new TestableReferenceProcessor();
var settings = new ChutzpahTestSettingsFile { }.InheritFromDefault();
settings.TestHarnessReferenceMode = TestHarnessReferenceMode.AMD;
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var text = (@"/// <reference path=""lib.js"" />
some javascript code");
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\lib.js" && !x.IncludeInTestHarness));
}
[Fact]
public void Will_change_path_root_given_SettingsFileDirectory_RootReferencePathMode()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path1\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile
{
RootReferencePathMode = RootReferencePathMode.SettingsFileDirectory,
SettingsFileDirectory = @"C:\root"
};
var text = @"/// <reference path=""/this/file.js"" />
some javascript code
";
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path1\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path.Equals(@"C:\root/this/file.js")));
}
[Fact]
public void Will_change_path_root_given_even_if_has_tilde()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path1\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile
{
RootReferencePathMode = RootReferencePathMode.SettingsFileDirectory,
SettingsFileDirectory = @"C:\root"
};
var text = @"/// <reference path=""~/this/file.js"" />
some javascript code
";
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path1\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path.Equals(@"C:\root/this/file.js")));
}
[Fact]
public void Will_not_change_path_root_given_SettingsFileDirectory_RootReferencePathMode()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path1\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {RootReferencePathMode = RootReferencePathMode.DriveRoot, SettingsFileDirectory = @"C:\root"};
var text = @"/// <reference path=""/this/file.js"" />
some javascript code
";
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path1\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path.Equals(@"/this/file.js")));
}
[Fact]
public void Will_change_path_root_given_SettingsFileDirectory_RootReferencePathMode_for_html_file()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path1\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile
{
RootReferencePathMode = RootReferencePathMode.SettingsFileDirectory,
SettingsFileDirectory = @"C:\root"
};
var text = @"/// <reference path=""/this/file.html"" />
some javascript code
";
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path1\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path.Equals(@"C:\root/this/file.html")));
}
[Fact]
public void Will_not_add_referenced_file_if_it_is_excluded()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path1\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
var text = @"/// <reference path=""lib.js"" />
/// <reference path=""../../js/excluded.js"" chutzpah-exclude=""true"" />
/// <reference path=""../../js/doublenegative.js"" chutzpah-exclude=""false"" />
/// <reference path=""../../js/excluded.js"" chutzpahExclude=""true"" />
/// <reference path=""../../js/doublenegative.js"" chutzpahExclude=""false"" />
some javascript code
";
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path1\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.False(referenceFiles.Any(x => x.Path.EndsWith("excluded.js")), "Test context contains excluded reference.");
Assert.True(referenceFiles.Any(x => x.Path.EndsWith("doublenegative.js")), "Test context does not contain negatively excluded reference.");
}
[Fact]
public void Will_put_recursively_referenced_files_before_parent_file()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileProbe>()
.Setup(x => x.FindFilePath(Path.Combine(@"path\", @"../../js/references.js")))
.Returns(@"path\references.js");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetText(@"path\references.js"))
.Returns(@"/// <reference path=""lib.js"" />");
string text = @"/// <reference path=""../../js/references.js"" />
some javascript code
";
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
var ref1 = referenceFiles.First(x => x.Path == @"path\lib.js");
var ref2 = referenceFiles.First(x => x.Path == @"path\references.js");
var pos1 = referenceFiles.IndexOf(ref1);
var pos2 = referenceFiles.IndexOf(ref2);
Assert.True(pos1 < pos2);
}
[Fact]
public void Will_stop_infinite_loop_when_processing_referenced_files()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
var text = @"/// <reference path=""../../js/references.js"" />
some javascript code
";
var loopText = @"/// <reference path=""../../js/references.js"" />";
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetText(@"path\references.js"))
.Returns(loopText);
processor.Mock<IFileProbe>()
.Setup(x => x.FindFilePath(Path.Combine(@"path\", @"../../js/references.js")))
.Returns(@"path\references.js");
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\references.js"));
}
[Fact]
public void Will_process_all_files_in_folder_references()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileProbe>()
.Setup(x => x.FindFilePath(Path.Combine(@"path\", @"../../js/somefolder")))
.Returns((string) null);
processor.Mock<IFileProbe>()
.Setup(x => x.FindFolderPath(Path.Combine(@"path\", @"../../js/somefolder")))
.Returns(@"path\someFolder");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"path\someFolder", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\subFile.js"});
var text = @"/// <reference path=""../../js/somefolder"" />
some javascript code
";
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
}
[Fact]
public void Will_skip_chutzpah_temporary_files_in_folder_references()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileProbe>()
.Setup(x => x.FindFilePath(Path.Combine(@"path\", @"../../js/somefolder")))
.Returns((string) null);
processor.Mock<IFileProbe>()
.Setup(x => x.FindFolderPath(Path.Combine(@"path\", @"../../js/somefolder")))
.Returns(@"path\someFolder");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"path\someFolder", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\subFile.js"});
var text = @"/// <reference path=""../../js/somefolder"" />
some javascript code
";
processor.Mock<IFileProbe>().Setup(x => x.IsTemporaryChutzpahFile(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.False(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
}
[Fact]
public void Will_only_include_one_reference_with_mulitple_references_in_html_template()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
var text = (@"/// <template path=""../../templates/file.html"" />
/// <template path=""../../templates/file.html"" />
some javascript code");
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.Equal(1, referenceFiles.Count(x => x.Path.EndsWith("file.html")));
}
[Fact]
public void Will_parse_html_template_in_script_mode()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile { };
var text = (@"/// <template mode=""script"" id=""my.Id"" path=""../../templates/file.html"" type=""My/Type""/>
some javascript code");
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
var file = referenceFiles.FirstOrDefault(x => x.Path.EndsWith("file.html"));
Assert.NotNull(file);
Assert.Equal(TemplateMode.Script, file.TemplateOptions.Mode);
Assert.Equal("my.Id", file.TemplateOptions.Id);
Assert.Equal("My/Type", file.TemplateOptions.Type);
}
[Fact]
public void Will_parse_html_template_in_raw_mode()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile { };
var text = (@"/// <template path=""../../templates/file.html"" />
some javascript code");
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
var file = referenceFiles.FirstOrDefault(x => x.Path.EndsWith("file.html"));
Assert.NotNull(file);
Assert.Equal(TemplateMode.Raw, file.TemplateOptions.Mode);
Assert.Null(file.TemplateOptions.Id);
Assert.Null(file.TemplateOptions.Type);
}
[Fact]
public void Will_add_reference_url_to_referenced_files()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
var text = (@"/// <reference path=""http://a.com/lib.js"" />
some javascript code");
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == "http://a.com/lib.js"));
}
[Fact]
public void Will_add_chutzpah_reference_to_referenced_files()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js", ExpandReferenceComments = true } };
var settings = new ChutzpahTestSettingsFile {};
var text = (@"/// <chutzpah_reference path=""lib.js"" />
some javascript code");
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path.EndsWith("lib.js")));
}
[Fact]
public void Will_add_file_from_settings_referenced_files()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here.js",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"c:\dir\here.js" && x.IncludeInTestHarness));
}
[Fact]
public void Will_default_path_to_settings_folder_when_adding_from_settings_references()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile().InheritFromDefault();
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\settingsDir")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\settingsDir")).Returns(@"c:\settingsDir");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\settingsDir", "*.*", SearchOption.AllDirectories))
.Returns(new[] { @"settingsDir\subFile.js", @"settingsDir\newFile.js", @"other\subFile.js" });
settings.SettingsFileDirectory = @"c:\settingsDir";
settings.References.Add(
new SettingsFileReference
{
Path = null,
Include = "*subFile.js",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"settingsDir\subFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\newFile.js"));
}
[Fact]
public void Will_exclude_from_test_harness_given_setting()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
settings.SettingsFileDirectory = @"c:\dir";
settings.TestHarnessReferenceMode = TestHarnessReferenceMode.AMD;
settings.References.Add(
new SettingsFileReference
{
Path = "here.js",
IncludeInTestHarness = true,
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"c:\dir\here.js" && x.IncludeInTestHarness));
}
[Fact]
public void Will_add_files_from_folder_from_settings_referenced_files()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\subFile.js", @"path\newFile.js"});
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
Assert.True(referenceFiles.Any(x => x.Path == @"path\newFile.js"));
}
[Fact]
public void Will_exclude_files_from_folder_from_settings_referenced_files_if_match_exclude_path()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\subFile.js", @"path\newFile.js"});
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
Exclude = @"*path\sub*",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\newFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
}
[Fact]
public void Will_exclude_files_from_folder_from_settings_referenced_files_if_they_dont_match_include_path()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\subFile.js", @"path\newFile.js"});
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
Include = @"*path\sub*",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.False(referenceFiles.Any(x => x.Path == @"path\newFile.js"));
Assert.True(referenceFiles.Any(x => x.Path == @"path\subFile.js"));
}
[Fact]
public void Will_exclude_files_from_folder_from_settings_referenced_files_if_match_exclude_path_and_dont_match_include()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile {};
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] {@"path\parentFile.js", @"other\newFile.js", @"path\sub\childFile.js"});
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
Include = @"path\*",
Exclude = @"*path\pare*",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\sub\childFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\parentFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"other\newFile.js"));
}
[Fact]
public void Will_exclude_files_from_folder_from_settings_referenced_files_if_match_excludes_path_and_dont_match_include()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile { };
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] { @"path\parentFile.js", @"other\newFile.js", @"path\sub\childFile.js" });
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
Includes = new[] { @"path\*", @"other\*", },
Excludes = new []{ @"*path\pare*", @"other\new*" },
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\sub\childFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\parentFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"other\newFile.js"));
}
[Fact]
public void Will_normlize_paths_for_case_and_slashes_for_path_include_exclude()
{
var processor = new TestableReferenceProcessor();
var referenceFiles = new List<ReferencedFile> { new ReferencedFile { IsFileUnderTest = true, Path = @"path\test.js" } };
var settings = new ChutzpahTestSettingsFile { };
processor.Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
processor.Mock<IFileProbe>().Setup(x => x.FindFilePath(@"c:\dir\here")).Returns<string>(null);
processor.Mock<IFileProbe>().Setup(x => x.FindFolderPath(@"c:\dir\here")).Returns(@"c:\dir\here");
processor.Mock<IFileSystemWrapper>()
.Setup(x => x.GetFiles(@"c:\dir\here", "*.*", SearchOption.AllDirectories))
.Returns(new[] { @"pAth/parentFile.js", @"Other/newFile.js", @"path\sub\childFile.js" });
settings.SettingsFileDirectory = @"c:\dir";
settings.References.Add(
new SettingsFileReference
{
Path = "here",
Include = @"PATH/*",
Exclude = @"*paTh/pAre*",
SettingsFileDirectory = settings.SettingsFileDirectory
});
var text = (@"some javascript code");
processor.Mock<IFileProbe>().Setup(x => x.GetReferencedFileContent(It.Is<ReferencedFile>(f => f.Path == @"path\test.js"), It.IsAny<ChutzpahTestSettingsFile>())).Returns(text);
processor.ClassUnderTest.GetReferencedFiles(referenceFiles, processor.FrameworkDefinition, settings);
Assert.True(referenceFiles.Any(x => x.Path == @"path\sub\childFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"path\parentFile.js"));
Assert.False(referenceFiles.Any(x => x.Path == @"other\newFile.js"));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using JetBrains.Application.Progress;
using JetBrains.Application.UI.Controls.BulbMenu.Anchors;
using JetBrains.Application.UI.Controls.BulbMenu.Positions;
using JetBrains.Metadata.Reader.API;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.Bulbs;
using JetBrains.ReSharper.Feature.Services.ContextActions;
using JetBrains.ReSharper.Feature.Services.CSharp.ContextActions;
using JetBrains.ReSharper.Feature.Services.Intentions;
using JetBrains.ReSharper.Plugins.Unity.Core.ProjectModel;
using JetBrains.ReSharper.Plugins.Unity.UnityEditorIntegration.Api;
using JetBrains.ReSharper.Plugins.Unity.Utils;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.Psi.CSharp.Impl;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Modules;
using JetBrains.TextControl;
using JetBrains.Util;
using JetBrains.Util.Extension;
#nullable enable
namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Feature.Services.ContextActions
{
public abstract class AddInspectorAttributeAction : IContextAction
{
protected static readonly IAnchorPosition LayoutPosition = AnchorPosition.BeforePosition;
protected static readonly IAnchorPosition AnnotationPosition = LayoutPosition.GetNext();
protected static readonly SubmenuAnchor BaseAnchor =
new(IntentionsAnchors.LowPriorityContextActionsAnchor, SubmenuBehavior.Static("Modify Inspector attributes"));
private readonly ICSharpContextActionDataProvider myDataProvider;
private readonly IAnchor myAnchor;
protected AddInspectorAttributeAction(ICSharpContextActionDataProvider dataProvider, IAnchor anchor)
{
myDataProvider = dataProvider;
myAnchor = anchor;
}
protected abstract IClrTypeName AttributeTypeName { get; }
protected virtual bool IsRemoveActionAvailable => false;
protected virtual bool SupportsSingleDeclarationOnly => false;
// A layout attribute is conceptually applied "in between" fields. As in, Header and Space are added before the
// currently selected field, while Range, Tooltip and HideInInspector are applied *to* a field. This changes
// the text of the bulb actions and the default action shown on multiple field declarations.
protected abstract bool IsLayoutAttribute { get; }
public IEnumerable<IntentionAction> CreateBulbItems()
{
var selectedFieldDeclaration = myDataProvider.GetSelectedElement<IFieldDeclaration>();
var multipleFieldDeclaration = MultipleFieldDeclarationNavigator.GetByDeclarator(selectedFieldDeclaration);
var unityApi = myDataProvider.Solution.GetComponent<UnityApi>();
if (selectedFieldDeclaration == null || multipleFieldDeclaration == null ||
!unityApi.IsSerialisedField(selectedFieldDeclaration.DeclaredElement))
{
return EmptyList<IntentionAction>.Enumerable;
}
var existingAttribute = selectedFieldDeclaration.GetAttribute(AttributeTypeName);
var actionToApplyToEntireDeclaration = GetActionToApplyToEntireFieldDeclaration(multipleFieldDeclaration,
selectedFieldDeclaration, myDataProvider.PsiModule, myDataProvider.ElementFactory,
existingAttribute)
.ToContextActionIntention(myAnchor);
// If we only have a single field in the declaration, then use the default action ("Add 'Attr'")
// This is the most likely case
if (multipleFieldDeclaration.Declarators.Count == 1)
return new[] {actionToApplyToEntireDeclaration};
var actionToExtractAndApply = GetActionToExtractAndApplyToSingleField(multipleFieldDeclaration,
selectedFieldDeclaration, myDataProvider.PsiModule, myDataProvider.ElementFactory,
existingAttribute)
.ToContextActionIntention(myAnchor);
// Only makes sense to apply to a single attribute, not all. E.g. you can't apply Range to all the fields
// in a multiple
if (SupportsSingleDeclarationOnly)
return new[] {actionToExtractAndApply};
// Change the order of main menu and submenu. If it's a layout attribute (e.g. 'Space'):
// "Add 'Attr' before all fields" -> "Add 'Attr' before 'field'"
// If it's an annotation attribute (e.g. 'Tooltip'):
// "Add 'Attr' to 'field'" -> "Add 'Attr' to all fields"
return IsLayoutAttribute
? new[] { actionToApplyToEntireDeclaration, actionToExtractAndApply }
: new[] { actionToExtractAndApply, actionToApplyToEntireDeclaration };
}
public bool IsAvailable(IUserDataHolder cache)
{
if (!myDataProvider.Project.IsUnityProject())
return false;
var unityApi = myDataProvider.Solution.GetComponent<UnityApi>();
var fieldDeclaration = myDataProvider.GetSelectedElement<IFieldDeclaration>();
if (fieldDeclaration == null || !unityApi.IsSerialisedField(fieldDeclaration.DeclaredElement))
return false;
var existingAttribute = fieldDeclaration.GetAttribute(AttributeTypeName);
if (existingAttribute != null && !IsRemoveActionAvailable)
return false;
// Only for UnityObject types, not [Serialized] types
var classDeclaration = fieldDeclaration.GetContainingTypeDeclaration();
var classElement = classDeclaration?.DeclaredElement;
return classElement.DerivesFromMonoBehaviour() || classElement.DerivesFromScriptableObject();
}
private BulbActionBase GetActionToApplyToEntireFieldDeclaration(
IMultipleFieldDeclaration multipleFieldDeclaration,
IFieldDeclaration selectedFieldDeclaration,
IPsiModule module,
CSharpElementFactory elementFactory,
IAttribute? existingAttribute)
{
// Don't pass selectedFieldDeclaration to the actions, as we're applying the action to all fields
// We only have selectedFieldDeclaration to get default attribute values, and even that's not actually used
if (existingAttribute != null)
return new RemoveAttributeAction(multipleFieldDeclaration, null, existingAttribute);
var attributeValues = GetAttributeValues(module, selectedFieldDeclaration);
return new AddAttributeAction(multipleFieldDeclaration, null, AttributeTypeName, attributeValues,
IsLayoutAttribute, module, elementFactory);
}
private BulbActionBase GetActionToExtractAndApplyToSingleField(
IMultipleFieldDeclaration multipleFieldDeclaration,
IFieldDeclaration selectedFieldDeclaration,
IPsiModule module,
CSharpElementFactory elementFactory,
IAttribute? existingAttribute)
{
if (existingAttribute != null)
return new RemoveAttributeAction(multipleFieldDeclaration, selectedFieldDeclaration, existingAttribute);
var attributeValues = GetAttributeValues(module, selectedFieldDeclaration);
return new AddAttributeAction(multipleFieldDeclaration, selectedFieldDeclaration, AttributeTypeName,
attributeValues, IsLayoutAttribute, module, elementFactory);
}
protected virtual AttributeValue[] GetAttributeValues(IPsiModule module,
IFieldDeclaration selectedFieldDeclaration)
{
return EmptyArray<AttributeValue>.Instance;
}
private class AddAttributeAction : BulbActionBase
{
private readonly IMultipleFieldDeclaration myMultipleFieldDeclaration;
private readonly IFieldDeclaration? mySelectedFieldDeclaration;
private readonly IPsiModule myModule;
private readonly CSharpElementFactory myElementFactory;
private readonly IClrTypeName myAttributeTypeName;
private readonly AttributeValue[] myAttributeValues;
private readonly bool myIsLayoutAttribute;
public AddAttributeAction(IMultipleFieldDeclaration multipleFieldDeclaration,
IFieldDeclaration? selectedFieldDeclaration,
IClrTypeName attributeTypeName,
AttributeValue[] attributeValues,
bool isLayoutAttribute,
IPsiModule module, CSharpElementFactory elementFactory)
{
myMultipleFieldDeclaration = multipleFieldDeclaration;
mySelectedFieldDeclaration = selectedFieldDeclaration;
myAttributeTypeName = attributeTypeName;
myAttributeValues = attributeValues;
myIsLayoutAttribute = isLayoutAttribute;
myModule = module;
myElementFactory = elementFactory;
}
protected override Action<ITextControl>? ExecutePsiTransaction(ISolution solution,
IProgressIndicator progress)
{
var attribute = mySelectedFieldDeclaration == null
? AttributeUtil.AddAttributeToEntireDeclaration(myMultipleFieldDeclaration,
myAttributeTypeName, myAttributeValues, null, myModule, myElementFactory)
: AttributeUtil.AddAttributeToSingleDeclaration(mySelectedFieldDeclaration,
myAttributeTypeName, myAttributeValues, null, myModule, myElementFactory);
if (attribute == null || myAttributeValues.Length == 0)
return null;
return attribute.CreateHotspotSession();
}
public override string Text
{
get
{
var displayName = myAttributeTypeName.ShortName.RemoveEnd("Attribute");
if (myMultipleFieldDeclaration.Declarators.Count == 1)
return $"Add '{displayName}'";
// Layout attribute is about position between fields, not being applied to fields
var preposition = myIsLayoutAttribute ? "before" : "to";
return mySelectedFieldDeclaration != null
? $"Add '{displayName}' {preposition} '{mySelectedFieldDeclaration.DeclaredName}'"
: $"Add '{displayName}' {preposition} all fields";
}
}
}
private class RemoveAttributeAction : BulbActionBase
{
private readonly IMultipleFieldDeclaration myMultipleFieldDeclaration;
private readonly IFieldDeclaration? mySelectedFieldDeclaration;
private readonly IAttribute myExistingAttribute;
public RemoveAttributeAction(IMultipleFieldDeclaration multipleFieldDeclaration,
IFieldDeclaration? selectedFieldDeclaration,
IAttribute existingAttribute)
{
myMultipleFieldDeclaration = multipleFieldDeclaration;
mySelectedFieldDeclaration = selectedFieldDeclaration;
myExistingAttribute = existingAttribute;
}
protected override Action<ITextControl>? ExecutePsiTransaction(
ISolution solution, IProgressIndicator progress)
{
if (mySelectedFieldDeclaration != null)
{
// This will split any multiple field declarations
mySelectedFieldDeclaration.RemoveAttribute(myExistingAttribute);
}
else
{
var fieldDeclaration = (IFieldDeclaration) myMultipleFieldDeclaration.Declarators[0];
CSharpSharedImplUtil.RemoveAttribute(fieldDeclaration, myExistingAttribute);
}
return null;
}
public override string Text
{
get
{
var displayName = myExistingAttribute.Name.ShortName;
if (myMultipleFieldDeclaration.Declarators.Count == 1)
return $"Remove '{displayName}'";
if (mySelectedFieldDeclaration != null)
{
return $"Remove '{displayName}' from '{mySelectedFieldDeclaration.DeclaredName}'";
}
return $"Remove '{displayName}' from all fields";
}
}
}
}
}
| |
namespace x360NANDManager.MMC {
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
internal sealed class MMCFlasher : FlasherOutput, IMMCFlasher {
private readonly MMCDevice _device;
private readonly int _sectorSize;
private bool _abort;
private int _bufsize;
private Stopwatch _sw;
public MMCFlasher(MMCDevice device) {
_device = device;
_sectorSize = (int) _device.DiskGeometryEX.Geometry.BytesPerSector;
}
private void SetBufSize() { _bufsize = (int) ((_device.DiskGeometryEX.Geometry.BytesPerSector * _device.DiskGeometryEX.Geometry.SectorsPerTrack) + _device.DiskGeometryEX.Geometry.BytesPerSector); }
private void SetBufSize(long sector, long lastsector) {
if (sector + (_bufsize / _sectorSize) > lastsector)
_bufsize = (int) ((lastsector - sector) * _sectorSize);
else
SetBufSize();
}
private void SetBufSizeEX(long offset, long end) {
if (offset + _bufsize > end)
_bufsize = (int) (end - offset);
else
SetBufSize();
}
private void CheckDeviceState() {
if (_device == null)
throw new NullReferenceException("_device");
_abort = false;
}
private void CheckSizeArgs(long startSector, ref long sectorCount, long filelen = 0) {
var sectorSize = _device.DiskGeometryEX.Geometry.BytesPerSector;
if (sectorCount == 0)
sectorCount = _device.Size / sectorSize;
if (filelen != 0) {
if (filelen > _device.Size)
throw new ArgumentOutOfRangeException("filelen");
if (sectorCount * sectorSize > filelen) {
sectorCount = filelen / sectorSize;
if (filelen % sectorSize != 0)
sectorCount++;
}
}
if (_device.Size >= (startSector + sectorCount) * sectorSize && startSector >= 0 && sectorCount > 0)
return;
if ((startSector * sectorSize) > _device.Size || startSector < 0)
throw new ArgumentOutOfRangeException("startSector");
if ((sectorCount * sectorSize) > _device.Size || sectorCount < 0)
throw new ArgumentOutOfRangeException("sectorCount");
throw new Exception("Too many Sectors specified!");
}
private void CheckSizeArgsEX(long offset, ref long length, long filelen = 0) {
if (length == 0)
length = _device.Size;
if (filelen != 0) {
if (filelen > _device.Size)
throw new ArgumentOutOfRangeException("filelen");
if (length > filelen)
length = filelen;
}
if (_device.Size >= offset + length && offset >= 0 && length > 0)
return;
if (offset > _device.Size || offset < 0)
throw new ArgumentOutOfRangeException("offset");
if (length > _device.Size || length < 0)
throw new ArgumentOutOfRangeException("length");
throw new Exception("Offset + Length is bigger then the device!");
}
#region Implementation of IMMCFlasher
public void Release() {
if (_device == null || !_device.IsLocked)
return;
if (_device != null)
_device.Release();
}
public void Abort() { _abort = true; }
public void ZeroData(long startSector, long sectorCount) {
_sw = Stopwatch.StartNew();
CheckDeviceState();
CheckSizeArgs(startSector, ref sectorCount);
_device.OpenHandle();
try {
var lastsector = startSector + sectorCount;
UpdateStatus(string.Format("Zeroing data on MMC Sectors: 0x{0:X} to 0x{1:X}", startSector, lastsector));
SetBufSize(startSector, lastsector);
Main.SendDebug(string.Format("Bufsize: 0x{0:X} Sector Size: 0x{1:X} Total Size: 0x{2:X}", _bufsize, _sectorSize, sectorCount * _sectorSize));
var data = new byte[_bufsize];
for (var sector = startSector; sector < lastsector;) {
if (_abort)
return;
SetBufSize(sector, lastsector);
UpdateMMCProgress(sector, lastsector, _sectorSize, _bufsize);
if (sector + (_bufsize / _sectorSize) > lastsector)
Array.Resize(ref data, (int) ((lastsector - sector) * _sectorSize));
_device.WriteToDevice(ref data, sector * _sectorSize);
sector += _bufsize / _sectorSize;
}
}
finally {
_sw.Stop();
UpdateStatus(string.Format((_abort ? "Aborted after: {0:F0} Minutes {1:F0} Seconds" : "Completed after: {0:F0} Minutes {1:F0} Seconds"), _sw.Elapsed.TotalMinutes, _sw.Elapsed.Seconds));
if (_device != null)
_device.Release();
}
}
public void ZeroDataEX(long offset = 0, long length = 0) {
CheckDeviceState();
CheckSizeArgsEX(offset, ref length);
_device.OpenHandle();
var end = offset + length;
try {
UpdateStatus(string.Format("Zeroing data on MMC Offset: 0x{0:X} to 0x{1:X}", offset, end));
Main.SendDebug(string.Format("Bufsize: 0x{0:X} Sector Size: 0x{1:X} Total Size: 0x{2:X}", _bufsize, _sectorSize, end));
for (var current = offset; current < end;) {
if (_abort)
return;
SetBufSizeEX(current, end);
UpdateMMCProgressEX(current, end, _bufsize);
var data = new byte[_bufsize];
_device.WriteToDevice(ref data, current);
current += data.Length;
}
}
finally {
if (_device != null)
_device.Release();
}
}
public void Write(byte[] data, long startSector = 0, long sectorCount = 0, bool verify = true) {
_sw = Stopwatch.StartNew();
CheckDeviceState();
CheckSizeArgs(startSector, ref sectorCount, data.Length);
_device.OpenHandle();
long doffset = 0;
try {
var lastsector = startSector + sectorCount;
var maxSector = lastsector;
if (verify)
maxSector += lastsector;
UpdateStatus(string.Format("Writing data to MMC Sectors: 0x{0:X} to 0x{1:X}", startSector, lastsector));
SetBufSize(startSector, lastsector);
Main.SendDebug(string.Format("Bufsize: 0x{0:X} Sector Size: 0x{1:X} Total Dump Size: 0x{2:X}", _bufsize, _sectorSize, sectorCount * _sectorSize));
for (var sector = startSector; sector < lastsector;) {
if (_abort)
return;
SetBufSize(sector, lastsector);
UpdateMMCProgress(sector, maxSector, _sectorSize, _bufsize);
_device.WriteToDevice(ref data, sector * _sectorSize, (int) doffset, _bufsize);
doffset += _bufsize;
sector += _bufsize / _sectorSize;
}
#region Verification
if (!verify)
return;
doffset = 0;
_device.Release();
_device.OpenHandle();
UpdateStatus(string.Format("Verifying data on MMC Sectors: 0x{0:X} to 0x{1:X}", startSector, lastsector));
for (var sector = startSector; sector < lastsector;) {
if (_abort)
return;
SetBufSize(sector, lastsector);
UpdateMMCProgress(sector + lastsector, maxSector, _sectorSize, _bufsize);
var buf = new byte[_bufsize];
var read = _device.ReadFromDevice(ref buf, sector * _sectorSize);
if (read != _bufsize)
throw new Exception("Something went wrong with the read operation!");
if (!CompareByteArrays(ref buf, ref data, (int) doffset))
SendError(string.Format("Verification failed somewhere between Sector: 0x{0:X} and 0x{1:X}", sector - (_bufsize / _sectorSize), sector));
doffset += read;
sector += read / _sectorSize;
}
#endregion Verification
}
finally {
_sw.Stop();
UpdateStatus(string.Format((_abort ? "Aborted after: {0:F0} Minutes {1:F0} Seconds" : "Completed after: {0:F0} Minutes {1:F0} Seconds"), _sw.Elapsed.TotalMinutes, _sw.Elapsed.Seconds));
if (_device != null)
_device.Release();
}
}
public void Write(string file, long startSector = 0, long sectorCount = 0, bool verify = true) {
_sw = Stopwatch.StartNew();
CheckDeviceState();
CheckSizeArgs(startSector, ref sectorCount);
_device.OpenHandle();
using (var br = OpenReader(file)) {
try {
var lastsector = startSector + sectorCount;
var maxSector = lastsector;
if (verify)
maxSector += lastsector;
UpdateStatus(string.Format("Writing data to MMC Sectors: 0x{0:X} to 0x{1:X}", startSector, lastsector));
SetBufSize(startSector, lastsector);
Main.SendDebug(string.Format("Bufsize: 0x{0:X} Sector Size: 0x{1:X} Total Dump Size: 0x{2:X}", _bufsize, _sectorSize, sectorCount * _sectorSize));
for (var sector = startSector; sector < lastsector;) {
if (_abort)
return;
SetBufSize(sector, lastsector);
UpdateMMCProgress(sector, maxSector, _sectorSize, _bufsize);
var data = br.ReadBytes(_bufsize);
_device.WriteToDevice(ref data, sector * _sectorSize);
sector += _bufsize / _sectorSize;
}
#region Verification
if (!verify)
return;
br.BaseStream.Seek(0, SeekOrigin.Begin);
UpdateStatus(string.Format("Verifying data on MMC Sectors: 0x{0:X} to 0x{1:X}", startSector, lastsector));
for (var sector = startSector; sector < lastsector;) {
if (_abort)
return;
SetBufSize(sector, lastsector);
UpdateMMCProgress(sector + lastsector, maxSector, _sectorSize, _bufsize);
var buf = new byte[_bufsize];
var read = _device.ReadFromDevice(ref buf, sector * _sectorSize);
if (read != _bufsize)
throw new Exception("Something went wrong with the read operation!");
var tmp = br.ReadBytes(_bufsize);
if (!CompareByteArrays(ref buf, ref tmp))
SendError(string.Format("Verification failed somewhere between Sector: 0x{0:X} and 0x{1:X}", sector - (_bufsize / _sectorSize), sector));
sector += read / _sectorSize;
}
#endregion Verification
}
finally {
_sw.Stop();
UpdateStatus(string.Format((_abort ? "Aborted after: {0:F0} Minutes {1:F0} Seconds" : "Completed after: {0:F0} Minutes {1:F0} Seconds"), _sw.Elapsed.TotalMinutes, _sw.Elapsed.Seconds));
if (_device != null)
_device.Release();
}
}
}
public void Write(string file, long fileSector = 0, long startSector = 0, long sectorCount = 0, bool verify = true)
{
_sw = Stopwatch.StartNew();
CheckDeviceState();
CheckSizeArgs(startSector, ref sectorCount);
_device.OpenHandle();
using (var br = OpenReader(file))
{
if (br.BaseStream.Length < (_sectorSize * fileSector) + (sectorCount * _sectorSize))
throw new ArgumentOutOfRangeException("fileSector");
br.BaseStream.Seek(_sectorSize * fileSector, SeekOrigin.Begin);
try
{
var lastsector = startSector + sectorCount;
var maxSector = lastsector;
if (verify)
maxSector += lastsector;
UpdateStatus(string.Format("Writing data to MMC Sectors: 0x{0:X} to 0x{1:X}", startSector, lastsector));
UpdateStatus("Writing data from: {0}", file);
UpdateStatus("FileOffset: 0x{0:X}", fileSector * _sectorSize);
SetBufSize(startSector, lastsector);
Main.SendDebug(string.Format("Bufsize: 0x{0:X} Sector Size: 0x{1:X} Total Dump Size: 0x{2:X}", _bufsize, _sectorSize, sectorCount * _sectorSize));
for (var sector = startSector; sector < lastsector; )
{
if (_abort)
return;
SetBufSize(sector, lastsector);
UpdateMMCProgress(sector, maxSector, _sectorSize, _bufsize);
var data = br.ReadBytes(_bufsize);
_device.WriteToDevice(ref data, sector * _sectorSize);
sector += _bufsize / _sectorSize;
}
#region Verification
if (!verify)
return;
br.BaseStream.Seek(_sectorSize * fileSector, SeekOrigin.Begin);
UpdateStatus(string.Format("Verifying data on MMC Sectors: 0x{0:X} to 0x{1:X}", startSector, lastsector));
for (var sector = startSector; sector < lastsector; )
{
if (_abort)
return;
SetBufSize(sector, lastsector);
UpdateMMCProgress(sector + lastsector, maxSector, _sectorSize, _bufsize);
var buf = new byte[_bufsize];
var read = _device.ReadFromDevice(ref buf, sector * _sectorSize);
if (read != _bufsize)
throw new Exception("Something went wrong with the read operation!");
var tmp = br.ReadBytes(_bufsize);
if (!CompareByteArrays(ref buf, ref tmp))
SendError(string.Format("Verification failed somewhere between Sector: 0x{0:X} and 0x{1:X}", sector - (_bufsize / _sectorSize), sector));
sector += read / _sectorSize;
}
#endregion Verification
}
finally
{
_sw.Stop();
UpdateStatus(string.Format((_abort ? "Aborted after: {0:F0} Minutes {1:F0} Seconds" : "Completed after: {0:F0} Minutes {1:F0} Seconds"), _sw.Elapsed.TotalMinutes, _sw.Elapsed.Seconds));
if (_device != null)
_device.Release();
}
}
}
public void WriteEX(byte[] data, long offset = 0, long length = 0, bool verify = true) {
_sw = Stopwatch.StartNew();
CheckDeviceState();
CheckSizeArgsEX(offset, ref length, data.Length);
_device.OpenHandle();
var doffset = 0;
try {
var end = offset + length;
var maxLen = end;
if (verify)
maxLen += maxLen;
UpdateStatus(string.Format("Writing data to MMC Offset: 0x{0:X} to 0x{1:X}", offset, end));
Main.SendDebug(string.Format("Bufsize: 0x{0:X} Sector Size: 0x{1:X} Total Write Size: 0x{2:X}", _bufsize, _sectorSize, length));
for (var current = offset; current < end;) {
if (_abort)
return;
SetBufSize(current, end);
UpdateMMCProgressEX(current, maxLen, _bufsize);
_device.WriteToDevice(ref data, current, doffset, _bufsize);
doffset += _bufsize;
current += _bufsize;
}
#region Verification
if (!verify)
return;
doffset = 0;
UpdateStatus(string.Format("Verifying data on MMC Offset: 0x{0:X} to 0x{1:X}", offset, end));
for (var current = offset; current < end;) {
if (_abort)
return;
SetBufSize(current, end);
UpdateMMCProgressEX(current + end, maxLen, _bufsize);
var buf = new byte[_bufsize];
if (_device.ReadFromDevice(ref buf, current) != _bufsize)
throw new Exception("Something went wrong with the read operation!");
if (!CompareByteArrays(ref buf, ref data, doffset))
SendError(string.Format("Verification failed somewhere between Offset: 0x{0:X} and 0x{1:X}", current - _bufsize, current));
doffset += _bufsize;
current += _bufsize;
}
#endregion Verification
}
finally {
_sw.Stop();
UpdateStatus(string.Format((_abort ? "Aborted after: {0:F0} Minutes {1:F0} Seconds" : "Completed after: {0:F0} Minutes {1:F0} Seconds"), _sw.Elapsed.TotalMinutes, _sw.Elapsed.Seconds));
if (_device != null)
_device.Release();
}
}
public void WriteEX(string file, long offset = 0, long length = 0, bool verify = true) {
_sw = Stopwatch.StartNew();
CheckDeviceState();
CheckSizeArgsEX(offset, ref length, new FileInfo(file).Length);
_device.OpenHandle();
using (var br = OpenReader(file)) {
try {
var end = offset + length;
var maxLen = end;
if (verify)
maxLen += maxLen;
UpdateStatus(string.Format("Writing data to MMC Offset: 0x{0:X} to 0x{1:X}", offset, end));
UpdateStatus(string.Format("Writing data from: {0}", file));
Main.SendDebug(string.Format("Bufsize: 0x{0:X} Sector Size: 0x{1:X} Total Dump Size: 0x{2:X}", _bufsize, _sectorSize, length));
for (var current = offset; current < end;) {
if (_abort)
return;
SetBufSize(current, end);
UpdateMMCProgressEX(current, maxLen, _bufsize);
var data = br.ReadBytes(_bufsize);
_device.WriteToDevice(ref data, current);
current += data.Length;
}
#region Verification
if (!verify)
return;
br.BaseStream.Seek(0, SeekOrigin.Begin);
UpdateStatus(string.Format("Verifying data on MMC Offset: 0x{0:X} to 0x{1:X}", offset, end));
for (var current = offset; current < end;) {
if (_abort)
return;
SetBufSize(current, end);
UpdateMMCProgressEX(current + end, maxLen, _bufsize);
var buf = new byte[_bufsize];
if (_device.ReadFromDevice(ref buf, current) != _bufsize)
throw new Exception("Something went wrong with the read operation!");
var tmp = br.ReadBytes(_bufsize);
if (!CompareByteArrays(ref buf, ref tmp))
SendError(string.Format("Verification failed somewhere between Offset: 0x{0:X} and 0x{1:X}", current - _bufsize, current));
current += _bufsize;
}
#endregion Verification
}
finally {
_sw.Stop();
UpdateStatus(string.Format((_abort ? "Aborted after: {0:F0} Minutes {1:F0} Seconds" : "Completed after: {0:F0} Minutes {1:F0} Seconds"), _sw.Elapsed.TotalMinutes, _sw.Elapsed.Seconds));
if (_device != null)
_device.Release();
}
}
}
public void WriteEX(string file, long fileOffset = 0, long offset = 0, long length = 0, bool verify = true)
{
_sw = Stopwatch.StartNew();
CheckDeviceState();
CheckSizeArgsEX(offset, ref length, new FileInfo(file).Length);
_device.OpenHandle();
using (var br = OpenReader(file))
{
if (br.BaseStream.Length < fileOffset + length)
throw new ArgumentOutOfRangeException("fileOffset");
br.BaseStream.Seek(fileOffset, SeekOrigin.Begin);
try
{
var end = offset + length;
var maxLen = end;
if (verify)
maxLen += maxLen;
UpdateStatus(string.Format("Writing data to MMC Offset: 0x{0:X} to 0x{1:X}", offset, end));
UpdateStatus(string.Format("Writing data from: {0}", file));
UpdateStatus("FileOffset: 0x{0:X}", fileOffset);
Main.SendDebug(string.Format("Bufsize: 0x{0:X} Sector Size: 0x{1:X} Total Dump Size: 0x{2:X}", _bufsize, _sectorSize, length));
for (var current = offset; current < end; )
{
if (_abort)
return;
SetBufSize(current, end);
UpdateMMCProgressEX(current, maxLen, _bufsize);
var data = br.ReadBytes(_bufsize);
_device.WriteToDevice(ref data, current);
current += data.Length;
}
#region Verification
if (!verify)
return;
br.BaseStream.Seek(fileOffset, SeekOrigin.Begin);
UpdateStatus(string.Format("Verifying data on MMC Offset: 0x{0:X} to 0x{1:X}", offset, end));
for (var current = offset; current < end; )
{
if (_abort)
return;
SetBufSize(current, end);
UpdateMMCProgressEX(current + end, maxLen, _bufsize);
var buf = new byte[_bufsize];
if (_device.ReadFromDevice(ref buf, current) != _bufsize)
throw new Exception("Something went wrong with the read operation!");
var tmp = br.ReadBytes(_bufsize);
if (!CompareByteArrays(ref buf, ref tmp))
SendError(string.Format("Verification failed somewhere between Offset: 0x{0:X} and 0x{1:X}", current - _bufsize, current));
current += _bufsize;
}
#endregion Verification
}
finally
{
_sw.Stop();
UpdateStatus(string.Format((_abort ? "Aborted after: {0:F0} Minutes {1:F0} Seconds" : "Completed after: {0:F0} Minutes {1:F0} Seconds"), _sw.Elapsed.TotalMinutes, _sw.Elapsed.Seconds));
if (_device != null)
_device.Release();
}
}
}
public byte[] Read(long startSector = 0, long sectorCount = 0) {
_sw = Stopwatch.StartNew();
CheckDeviceState();
CheckSizeArgs(startSector, ref sectorCount);
_device.OpenHandle();
var data = new List <byte>();
try {
var lastsector = startSector + sectorCount;
UpdateStatus(string.Format("Reading data from MMC Sectors: 0x{0:X} to 0x{1:X}", startSector, lastsector));
Main.SendDebug(string.Format("Bufsize: 0x{0:X} Sector Size: 0x{1:X} Total Dump Size: 0x{2:X}", _bufsize, _sectorSize, sectorCount * _sectorSize));
for (var sector = startSector; sector < lastsector;) {
if (_abort)
return data.ToArray();
SetBufSize(sector, lastsector);
UpdateMMCProgress(sector, lastsector, _sectorSize, _bufsize);
var buf = new byte[_bufsize];
var read = _device.ReadFromDevice(ref buf, sector * _sectorSize);
if (read != _bufsize)
throw new Exception("Something went wrong with the read operation!");
data.AddRange(buf);
sector += read / _sectorSize;
}
return data.ToArray();
}
finally {
_sw.Stop();
UpdateStatus(string.Format((_abort ? "Aborted after: {0:F0} Minutes {1:F0} Seconds" : "Completed after: {0:F0} Minutes {1:F0} Seconds"), _sw.Elapsed.TotalMinutes, _sw.Elapsed.Seconds));
if (_device != null)
_device.Release();
}
}
public void Read(string file, long startSector = 0, long sectorCount = 0) {
_sw = Stopwatch.StartNew();
CheckDeviceState();
CheckSizeArgs(startSector, ref sectorCount);
_device.OpenHandle();
if (GetTotalFreeSpace(file) < sectorCount * _sectorSize)
throw new Exception("Not enough space for the dump!");
using (var bw = OpenWriter(file)) {
try {
var lastsector = startSector + sectorCount;
UpdateStatus(string.Format("Reading data from MMC Sectors: 0x{0:X} to 0x{1:X}", startSector, lastsector));
UpdateStatus(string.Format("Saving data to: {0}", file));
SetBufSize(startSector, lastsector);
Main.SendDebug(string.Format("Bufsize: 0x{0:X} Sector Size: 0x{1:X} Total Dump Size: 0x{2:X}", _bufsize, _sectorSize, sectorCount * _sectorSize));
for (var sector = startSector; sector < lastsector;) {
if (_abort)
return;
SetBufSize(sector, lastsector);
UpdateMMCProgress(sector, lastsector, _sectorSize, _bufsize);
var buf = new byte[_bufsize];
var read = _device.ReadFromDevice(ref buf, sector * _sectorSize);
if (read != _bufsize)
throw new Exception("Something went wrong with the read operation!");
bw.Write(buf);
sector += read / _sectorSize;
}
}
finally {
_sw.Stop();
UpdateStatus(string.Format((_abort ? "Aborted after: {0:F0} Minutes {1:F0} Seconds" : "Completed after: {0:F0} Minutes {1:F0} Seconds"), _sw.Elapsed.TotalMinutes, _sw.Elapsed.Seconds));
if (_device != null)
_device.Release();
}
}
}
public void Read(IEnumerable <string> files, long startSector = 0, long sectorCount = 0) {
_abort = false;
var sw = Stopwatch.StartNew();
files = RemoveDuplicatesInList(files);
foreach (var file in files) {
if (_abort) {
sw.Stop();
UpdateStatus(string.Format("Read aborted after {0:F0} Minutes and {1:F0} Seconds!", sw.Elapsed.TotalMinutes, sw.Elapsed.Seconds));
break;
}
Read(file, startSector, sectorCount);
}
if (_abort)
return;
sw.Stop();
UpdateStatus(string.Format("Read completed after {0:F0} Minutes and {1:F0} Seconds!", sw.Elapsed.TotalMinutes, sw.Elapsed.Seconds));
}
public byte[] ReadEX(long offset = 0, long length = 0) {
_sw = Stopwatch.StartNew();
CheckDeviceState();
CheckSizeArgsEX(offset, ref length);
_device.OpenHandle();
var data = new List <byte>();
try {
var end = offset + length;
UpdateStatus(string.Format("Reading data from MMC Offset: 0x{0:X} to 0x{1:X}", offset, end));
Main.SendDebug(string.Format("Bufsize: 0x{0:X} Sector Size: 0x{1:X} Total Dump Size: 0x{2:X}", _bufsize, _sectorSize, length));
for (var current = offset; current < end;) {
if (_abort)
return data.ToArray();
SetBufSizeEX(current, end);
UpdateMMCProgressEX(current, end, _bufsize);
var buf = new byte[_bufsize];
if (_device.ReadFromDevice(ref buf, current) != _bufsize)
throw new Exception("Something went wrong with the read operation!");
data.AddRange(buf);
current += buf.Length;
}
return data.ToArray();
}
finally {
_sw.Stop();
UpdateStatus(string.Format((_abort ? "Aborted after: {0:F0} Minutes {1:F0} Seconds" : "Completed after: {0:F0} Minutes {1:F0} Seconds"), _sw.Elapsed.TotalMinutes, _sw.Elapsed.Seconds));
if (_device != null)
_device.Release();
}
}
public void ReadEX(string file, long offset = 0, long length = 0) {
_sw = Stopwatch.StartNew();
CheckDeviceState();
CheckSizeArgsEX(offset, ref length);
_device.OpenHandle();
if (GetTotalFreeSpace(file) < length)
throw new Exception("Not enough space for the dump!");
using (var bw = OpenWriter(file)) {
try {
var end = offset + length;
UpdateStatus(string.Format("Reading data from MMC Offset: 0x{0:X} to 0x{1:X}", offset, end));
Main.SendDebug(string.Format("Bufsize: 0x{0:X} Sector Size: 0x{1:X} Total Dump Size: 0x{2:X}", _bufsize, _sectorSize, length));
for (var current = offset; current < end;) {
if (_abort)
return;
SetBufSizeEX(current, end);
UpdateMMCProgressEX(current, end, _bufsize);
var buf = new byte[_bufsize];
if (_device.ReadFromDevice(ref buf, current) != _bufsize)
throw new Exception("Something went wrong with the read operation!");
bw.Write(buf);
current += buf.Length;
}
}
finally {
_sw.Stop();
UpdateStatus(string.Format((_abort ? "Aborted after: {0:F0} Minutes {1:F0} Seconds" : "Completed after: {0:F0} Minutes {1:F0} Seconds"), _sw.Elapsed.TotalMinutes, _sw.Elapsed.Seconds));
if (_device != null)
_device.Release();
}
}
}
public void ReadEX(IEnumerable <string> files, long offset = 0, long length = 0) {
_abort = false;
var sw = Stopwatch.StartNew();
files = RemoveDuplicatesInList(files);
foreach (var file in files) {
if (_abort) {
sw.Stop();
UpdateStatus(string.Format("Read aborted after {0:F0} Minutes and {1:F0} Seconds!", sw.Elapsed.TotalMinutes, sw.Elapsed.Seconds));
break;
}
ReadEX(file, offset, length);
}
if (_abort)
return;
sw.Stop();
UpdateStatus(string.Format("Read completed after {0:F0} Minutes and {1:F0} Seconds!", sw.Elapsed.TotalMinutes, sw.Elapsed.Seconds));
}
/// <summary>
/// Gets a list of Devices that can be selected
/// </summary>
/// <param name="onlyRemoveable"> If set to false also Fixed devices will be included in the list (most likely useless) </param>
/// <returns> List of devices used for the MMC Flasher </returns>
internal static IList <MMCDevice> GetDevices(bool onlyRemoveable = true) {
var tmp = new Dictionary <int, MMCDevice>();
foreach (var drive in DriveInfo.GetDrives()) {
if (drive.DriveType == DriveType.Fixed && onlyRemoveable)
continue;
if (drive.DriveType != DriveType.Removable && drive.DriveType != DriveType.Fixed)
continue;
try {
var devnum = NativeWin32.GetDeviceNumber(drive.Name);
if (!tmp.ContainsKey(devnum)) {
var path = NativeWin32.GetDevicePath(drive.Name);
tmp.Add(devnum, new MMCDevice(drive.Name, path, NativeWin32.GetGeometryEX(path)));
}
else {
tmp[devnum].DisplayName = string.Format("{0}, {1}", tmp[devnum].DisplayName, drive.Name);
tmp[devnum].AddVolume(drive.Name);
}
}
catch (Exception ex) {
var dex = ex as X360NANDManagerException;
if (dex != null && (dex.Win32ErrorNumber == 32 || dex.Win32ErrorNumber == 0 /* Success, not an error?! */|| dex.Win32ErrorNumber == 21 /* Device not ready... ignore it... */))
continue;
var wex = ex as Win32Exception;
if (wex != null && wex.NativeErrorCode == 21) //Device not ready, Win32 Error outside of my own error handling...
continue;
throw;
}
}
Main.SendDebug("Copying data to returnable object");
var ret = new MMCDevice[tmp.Values.Count];
tmp.Values.CopyTo(ret, 0);
return ret;
}
#endregion
}
}
| |
using System;
namespace dbo{
public class DatabaseLog
{
public int DatabaseLogID {get;set;}
public DateTime PostTime {get;set;}
public string DatabaseUser {get;set;}
public string Event {get;set;}
public string Schema {get;set;}
public string Object {get;set;}
public string TSQL {get;set;}
public string XmlEvent {get;set;}
}
public class ErrorLog
{
public int ErrorLogID {get;set;}
public DateTime ErrorTime {get;set;}
public string UserName {get;set;}
public int ErrorNumber {get;set;}
public int ErrorSeverity {get;set;}
public int ErrorState {get;set;}
public string ErrorProcedure {get;set;}
public int ErrorLine {get;set;}
public string ErrorMessage {get;set;}
}
public class AWBuildVersion
{
public string SystemInformationID {get;set;}
public string Database Version {get;set;}
public DateTime VersionDate {get;set;}
public DateTime ModifiedDate {get;set;}
}
}
namespace guest{
}
namespace INFORMATION_SCHEMA{
}
namespace sys{
}
namespace HumanResources{
public class Shift
{
public string ShiftID {get;set;}
public string Name {get;set;}
public string StartTime {get;set;}
public string EndTime {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class Department
{
public string DepartmentID {get;set;}
public string Name {get;set;}
public string GroupName {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class Employee
{
public int BusinessEntityID {get;set;}
public string NationalIDNumber {get;set;}
public string LoginID {get;set;}
public string OrganizationNode {get;set;}
public string OrganizationLevel {get;set;}
public string JobTitle {get;set;}
public string BirthDate {get;set;}
public string MaritalStatus {get;set;}
public string Gender {get;set;}
public string HireDate {get;set;}
public string SalariedFlag {get;set;}
public string VacationHours {get;set;}
public string SickLeaveHours {get;set;}
public string CurrentFlag {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class EmployeeDepartmentHistory
{
public int BusinessEntityID {get;set;}
public string DepartmentID {get;set;}
public string ShiftID {get;set;}
public string StartDate {get;set;}
public string EndDate {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class EmployeePayHistory
{
public int BusinessEntityID {get;set;}
public DateTime RateChangeDate {get;set;}
public string Rate {get;set;}
public string PayFrequency {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class JobCandidate
{
public int JobCandidateID {get;set;}
public int BusinessEntityID {get;set;}
public string Resume {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class vEmployee
{
public int BusinessEntityID {get;set;}
public string Title {get;set;}
public string FirstName {get;set;}
public string MiddleName {get;set;}
public string LastName {get;set;}
public string Suffix {get;set;}
public string JobTitle {get;set;}
public string PhoneNumber {get;set;}
public string PhoneNumberType {get;set;}
public string EmailAddress {get;set;}
public int EmailPromotion {get;set;}
public string AddressLine1 {get;set;}
public string AddressLine2 {get;set;}
public string City {get;set;}
public string StateProvinceName {get;set;}
public string PostalCode {get;set;}
public string CountryRegionName {get;set;}
public string AdditionalContactInfo {get;set;}
}
public class vEmployeeDepartment
{
public int BusinessEntityID {get;set;}
public string Title {get;set;}
public string FirstName {get;set;}
public string MiddleName {get;set;}
public string LastName {get;set;}
public string Suffix {get;set;}
public string JobTitle {get;set;}
public string Department {get;set;}
public string GroupName {get;set;}
public string StartDate {get;set;}
}
public class vEmployeeDepartmentHistory
{
public int BusinessEntityID {get;set;}
public string Title {get;set;}
public string FirstName {get;set;}
public string MiddleName {get;set;}
public string LastName {get;set;}
public string Suffix {get;set;}
public string Shift {get;set;}
public string Department {get;set;}
public string GroupName {get;set;}
public string StartDate {get;set;}
public string EndDate {get;set;}
}
public class vJobCandidate
{
public int JobCandidateID {get;set;}
public int BusinessEntityID {get;set;}
public string Name.Prefix {get;set;}
public string Name.First {get;set;}
public string Name.Middle {get;set;}
public string Name.Last {get;set;}
public string Name.Suffix {get;set;}
public string Skills {get;set;}
public string Addr.Type {get;set;}
public string Addr.Loc.CountryRegion {get;set;}
public string Addr.Loc.State {get;set;}
public string Addr.Loc.City {get;set;}
public string Addr.PostalCode {get;set;}
public string EMail {get;set;}
public string WebSite {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class vJobCandidateEmployment
{
public int JobCandidateID {get;set;}
public DateTime Emp.StartDate {get;set;}
public DateTime Emp.EndDate {get;set;}
public string Emp.OrgName {get;set;}
public string Emp.JobTitle {get;set;}
public string Emp.Responsibility {get;set;}
public string Emp.FunctionCategory {get;set;}
public string Emp.IndustryCategory {get;set;}
public string Emp.Loc.CountryRegion {get;set;}
public string Emp.Loc.State {get;set;}
public string Emp.Loc.City {get;set;}
}
public class vJobCandidateEducation
{
public int JobCandidateID {get;set;}
public string Edu.Level {get;set;}
public DateTime Edu.StartDate {get;set;}
public DateTime Edu.EndDate {get;set;}
public string Edu.Degree {get;set;}
public string Edu.Major {get;set;}
public string Edu.Minor {get;set;}
public string Edu.GPA {get;set;}
public string Edu.GPAScale {get;set;}
public string Edu.School {get;set;}
public string Edu.Loc.CountryRegion {get;set;}
public string Edu.Loc.State {get;set;}
public string Edu.Loc.City {get;set;}
}
}
namespace Person{
public class Address
{
public int AddressID {get;set;}
public string AddressLine1 {get;set;}
public string AddressLine2 {get;set;}
public string City {get;set;}
public int StateProvinceID {get;set;}
public string PostalCode {get;set;}
public string SpatialLocation {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class AddressType
{
public int AddressTypeID {get;set;}
public string Name {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class StateProvince
{
public int StateProvinceID {get;set;}
public string StateProvinceCode {get;set;}
public string CountryRegionCode {get;set;}
public string IsOnlyStateProvinceFlag {get;set;}
public string Name {get;set;}
public int TerritoryID {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class BusinessEntity
{
public int BusinessEntityID {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class BusinessEntityAddress
{
public int BusinessEntityID {get;set;}
public int AddressID {get;set;}
public int AddressTypeID {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class BusinessEntityContact
{
public int BusinessEntityID {get;set;}
public int PersonID {get;set;}
public int ContactTypeID {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class ContactType
{
public int ContactTypeID {get;set;}
public string Name {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class CountryRegion
{
public string CountryRegionCode {get;set;}
public string Name {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class EmailAddress
{
public int BusinessEntityID {get;set;}
public int EmailAddressID {get;set;}
public string EmailAddress {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class Password
{
public int BusinessEntityID {get;set;}
public string PasswordHash {get;set;}
public string PasswordSalt {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class Person
{
public int BusinessEntityID {get;set;}
public string PersonType {get;set;}
public string NameStyle {get;set;}
public string Title {get;set;}
public string FirstName {get;set;}
public string MiddleName {get;set;}
public string LastName {get;set;}
public string Suffix {get;set;}
public int EmailPromotion {get;set;}
public string AdditionalContactInfo {get;set;}
public string Demographics {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class vAdditionalContactInfo
{
public int BusinessEntityID {get;set;}
public string FirstName {get;set;}
public string MiddleName {get;set;}
public string LastName {get;set;}
public string TelephoneNumber {get;set;}
public string TelephoneSpecialInstructions {get;set;}
public string Street {get;set;}
public string City {get;set;}
public string StateProvince {get;set;}
public string PostalCode {get;set;}
public string CountryRegion {get;set;}
public string HomeAddressSpecialInstructions {get;set;}
public string EMailAddress {get;set;}
public string EMailSpecialInstructions {get;set;}
public string EMailTelephoneNumber {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class PersonPhone
{
public int BusinessEntityID {get;set;}
public string PhoneNumber {get;set;}
public int PhoneNumberTypeID {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class PhoneNumberType
{
public int PhoneNumberTypeID {get;set;}
public string Name {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class vStateProvinceCountryRegion
{
public int StateProvinceID {get;set;}
public string StateProvinceCode {get;set;}
public string IsOnlyStateProvinceFlag {get;set;}
public string StateProvinceName {get;set;}
public int TerritoryID {get;set;}
public string CountryRegionCode {get;set;}
public string CountryRegionName {get;set;}
}
}
namespace Production{
public class ScrapReason
{
public string ScrapReasonID {get;set;}
public string Name {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class ProductCategory
{
public int ProductCategoryID {get;set;}
public string Name {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class ProductCostHistory
{
public int ProductID {get;set;}
public DateTime StartDate {get;set;}
public DateTime EndDate {get;set;}
public string StandardCost {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class ProductDescription
{
public int ProductDescriptionID {get;set;}
public string Description {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class ProductDocument
{
public int ProductID {get;set;}
public string DocumentNode {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class ProductInventory
{
public int ProductID {get;set;}
public string LocationID {get;set;}
public string Shelf {get;set;}
public string Bin {get;set;}
public string Quantity {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class ProductListPriceHistory
{
public int ProductID {get;set;}
public DateTime StartDate {get;set;}
public DateTime EndDate {get;set;}
public string ListPrice {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class ProductModel
{
public int ProductModelID {get;set;}
public string Name {get;set;}
public string CatalogDescription {get;set;}
public string Instructions {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class ProductModelIllustration
{
public int ProductModelID {get;set;}
public int IllustrationID {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class ProductModelProductDescriptionCulture
{
public int ProductModelID {get;set;}
public int ProductDescriptionID {get;set;}
public string CultureID {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class BillOfMaterials
{
public int BillOfMaterialsID {get;set;}
public int ProductAssemblyID {get;set;}
public int ComponentID {get;set;}
public DateTime StartDate {get;set;}
public DateTime EndDate {get;set;}
public string UnitMeasureCode {get;set;}
public string BOMLevel {get;set;}
public string PerAssemblyQty {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class ProductPhoto
{
public int ProductPhotoID {get;set;}
public string ThumbNailPhoto {get;set;}
public string ThumbnailPhotoFileName {get;set;}
public string LargePhoto {get;set;}
public string LargePhotoFileName {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class ProductProductPhoto
{
public int ProductID {get;set;}
public int ProductPhotoID {get;set;}
public string Primary {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class TransactionHistory
{
public int TransactionID {get;set;}
public int ProductID {get;set;}
public int ReferenceOrderID {get;set;}
public int ReferenceOrderLineID {get;set;}
public DateTime TransactionDate {get;set;}
public string TransactionType {get;set;}
public int Quantity {get;set;}
public string ActualCost {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class ProductReview
{
public int ProductReviewID {get;set;}
public int ProductID {get;set;}
public string ReviewerName {get;set;}
public DateTime ReviewDate {get;set;}
public string EmailAddress {get;set;}
public int Rating {get;set;}
public string Comments {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class TransactionHistoryArchive
{
public int TransactionID {get;set;}
public int ProductID {get;set;}
public int ReferenceOrderID {get;set;}
public int ReferenceOrderLineID {get;set;}
public DateTime TransactionDate {get;set;}
public string TransactionType {get;set;}
public int Quantity {get;set;}
public string ActualCost {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class ProductSubcategory
{
public int ProductSubcategoryID {get;set;}
public int ProductCategoryID {get;set;}
public string Name {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class UnitMeasure
{
public string UnitMeasureCode {get;set;}
public string Name {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class WorkOrder
{
public int WorkOrderID {get;set;}
public int ProductID {get;set;}
public int OrderQty {get;set;}
public int StockedQty {get;set;}
public string ScrappedQty {get;set;}
public DateTime StartDate {get;set;}
public DateTime EndDate {get;set;}
public DateTime DueDate {get;set;}
public string ScrapReasonID {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class Culture
{
public string CultureID {get;set;}
public string Name {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class WorkOrderRouting
{
public int WorkOrderID {get;set;}
public int ProductID {get;set;}
public string OperationSequence {get;set;}
public string LocationID {get;set;}
public DateTime ScheduledStartDate {get;set;}
public DateTime ScheduledEndDate {get;set;}
public DateTime ActualStartDate {get;set;}
public DateTime ActualEndDate {get;set;}
public string ActualResourceHrs {get;set;}
public string PlannedCost {get;set;}
public string ActualCost {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class Document
{
public string DocumentNode {get;set;}
public string DocumentLevel {get;set;}
public string Title {get;set;}
public int Owner {get;set;}
public string FolderFlag {get;set;}
public string FileName {get;set;}
public string FileExtension {get;set;}
public string Revision {get;set;}
public int ChangeNumber {get;set;}
public string Status {get;set;}
public string DocumentSummary {get;set;}
public string Document {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class Illustration
{
public int IllustrationID {get;set;}
public string Diagram {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class Location
{
public string LocationID {get;set;}
public string Name {get;set;}
public string CostRate {get;set;}
public string Availability {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class Product
{
public int ProductID {get;set;}
public string Name {get;set;}
public string ProductNumber {get;set;}
public string MakeFlag {get;set;}
public string FinishedGoodsFlag {get;set;}
public string Color {get;set;}
public string SafetyStockLevel {get;set;}
public string ReorderPoint {get;set;}
public string StandardCost {get;set;}
public string ListPrice {get;set;}
public string Size {get;set;}
public string SizeUnitMeasureCode {get;set;}
public string WeightUnitMeasureCode {get;set;}
public string Weight {get;set;}
public int DaysToManufacture {get;set;}
public string ProductLine {get;set;}
public string Class {get;set;}
public string Style {get;set;}
public int ProductSubcategoryID {get;set;}
public int ProductModelID {get;set;}
public DateTime SellStartDate {get;set;}
public DateTime SellEndDate {get;set;}
public DateTime DiscontinuedDate {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class vProductAndDescription
{
public int ProductID {get;set;}
public string Name {get;set;}
public string ProductModel {get;set;}
public string CultureID {get;set;}
public string Description {get;set;}
}
public class vProductModelCatalogDescription
{
public int ProductModelID {get;set;}
public string Name {get;set;}
public string Summary {get;set;}
public string Manufacturer {get;set;}
public string Copyright {get;set;}
public string ProductURL {get;set;}
public string WarrantyPeriod {get;set;}
public string WarrantyDescription {get;set;}
public string NoOfYears {get;set;}
public string MaintenanceDescription {get;set;}
public string Wheel {get;set;}
public string Saddle {get;set;}
public string Pedal {get;set;}
public string BikeFrame {get;set;}
public string Crankset {get;set;}
public string PictureAngle {get;set;}
public string PictureSize {get;set;}
public string ProductPhotoID {get;set;}
public string Material {get;set;}
public string Color {get;set;}
public string ProductLine {get;set;}
public string Style {get;set;}
public string RiderExperience {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class vProductModelInstructions
{
public int ProductModelID {get;set;}
public string Name {get;set;}
public string Instructions {get;set;}
public int LocationID {get;set;}
public string SetupHours {get;set;}
public string MachineHours {get;set;}
public string LaborHours {get;set;}
public int LotSize {get;set;}
public string Step {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
}
namespace Purchasing{
public class vVendorWithContacts
{
public int BusinessEntityID {get;set;}
public string Name {get;set;}
public string ContactType {get;set;}
public string Title {get;set;}
public string FirstName {get;set;}
public string MiddleName {get;set;}
public string LastName {get;set;}
public string Suffix {get;set;}
public string PhoneNumber {get;set;}
public string PhoneNumberType {get;set;}
public string EmailAddress {get;set;}
public int EmailPromotion {get;set;}
}
public class vVendorWithAddresses
{
public int BusinessEntityID {get;set;}
public string Name {get;set;}
public string AddressType {get;set;}
public string AddressLine1 {get;set;}
public string AddressLine2 {get;set;}
public string City {get;set;}
public string StateProvinceName {get;set;}
public string PostalCode {get;set;}
public string CountryRegionName {get;set;}
}
public class ShipMethod
{
public int ShipMethodID {get;set;}
public string Name {get;set;}
public string ShipBase {get;set;}
public string ShipRate {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class ProductVendor
{
public int ProductID {get;set;}
public int BusinessEntityID {get;set;}
public int AverageLeadTime {get;set;}
public string StandardPrice {get;set;}
public string LastReceiptCost {get;set;}
public DateTime LastReceiptDate {get;set;}
public int MinOrderQty {get;set;}
public int MaxOrderQty {get;set;}
public int OnOrderQty {get;set;}
public string UnitMeasureCode {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class Vendor
{
public int BusinessEntityID {get;set;}
public string AccountNumber {get;set;}
public string Name {get;set;}
public string CreditRating {get;set;}
public string PreferredVendorStatus {get;set;}
public string ActiveFlag {get;set;}
public string PurchasingWebServiceURL {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class PurchaseOrderDetail
{
public int PurchaseOrderID {get;set;}
public int PurchaseOrderDetailID {get;set;}
public DateTime DueDate {get;set;}
public string OrderQty {get;set;}
public int ProductID {get;set;}
public string UnitPrice {get;set;}
public string LineTotal {get;set;}
public string ReceivedQty {get;set;}
public string RejectedQty {get;set;}
public string StockedQty {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class PurchaseOrderHeader
{
public int PurchaseOrderID {get;set;}
public string RevisionNumber {get;set;}
public string Status {get;set;}
public int EmployeeID {get;set;}
public int VendorID {get;set;}
public int ShipMethodID {get;set;}
public DateTime OrderDate {get;set;}
public DateTime ShipDate {get;set;}
public string SubTotal {get;set;}
public string TaxAmt {get;set;}
public string Freight {get;set;}
public string TotalDue {get;set;}
public DateTime ModifiedDate {get;set;}
}
}
namespace Sales{
public class vStoreWithContacts
{
public int BusinessEntityID {get;set;}
public string Name {get;set;}
public string ContactType {get;set;}
public string Title {get;set;}
public string FirstName {get;set;}
public string MiddleName {get;set;}
public string LastName {get;set;}
public string Suffix {get;set;}
public string PhoneNumber {get;set;}
public string PhoneNumberType {get;set;}
public string EmailAddress {get;set;}
public int EmailPromotion {get;set;}
}
public class vStoreWithAddresses
{
public int BusinessEntityID {get;set;}
public string Name {get;set;}
public string AddressType {get;set;}
public string AddressLine1 {get;set;}
public string AddressLine2 {get;set;}
public string City {get;set;}
public string StateProvinceName {get;set;}
public string PostalCode {get;set;}
public string CountryRegionName {get;set;}
}
public class ShoppingCartItem
{
public int ShoppingCartItemID {get;set;}
public string ShoppingCartID {get;set;}
public int Quantity {get;set;}
public int ProductID {get;set;}
public DateTime DateCreated {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class SpecialOffer
{
public int SpecialOfferID {get;set;}
public string Description {get;set;}
public string DiscountPct {get;set;}
public string Type {get;set;}
public string Category {get;set;}
public DateTime StartDate {get;set;}
public DateTime EndDate {get;set;}
public int MinQty {get;set;}
public int MaxQty {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class SpecialOfferProduct
{
public int SpecialOfferID {get;set;}
public int ProductID {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class Store
{
public int BusinessEntityID {get;set;}
public string Name {get;set;}
public int SalesPersonID {get;set;}
public string Demographics {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class CountryRegionCurrency
{
public string CountryRegionCode {get;set;}
public string CurrencyCode {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class CreditCard
{
public int CreditCardID {get;set;}
public string CardType {get;set;}
public string CardNumber {get;set;}
public string ExpMonth {get;set;}
public string ExpYear {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class Currency
{
public string CurrencyCode {get;set;}
public string Name {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class CurrencyRate
{
public int CurrencyRateID {get;set;}
public DateTime CurrencyRateDate {get;set;}
public string FromCurrencyCode {get;set;}
public string ToCurrencyCode {get;set;}
public string AverageRate {get;set;}
public string EndOfDayRate {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class Customer
{
public int CustomerID {get;set;}
public int PersonID {get;set;}
public int StoreID {get;set;}
public int TerritoryID {get;set;}
public string AccountNumber {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class SalesOrderDetail
{
public int SalesOrderID {get;set;}
public int SalesOrderDetailID {get;set;}
public string CarrierTrackingNumber {get;set;}
public string OrderQty {get;set;}
public int ProductID {get;set;}
public int SpecialOfferID {get;set;}
public string UnitPrice {get;set;}
public string UnitPriceDiscount {get;set;}
public string LineTotal {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class SalesOrderHeader
{
public int SalesOrderID {get;set;}
public string RevisionNumber {get;set;}
public DateTime OrderDate {get;set;}
public DateTime DueDate {get;set;}
public DateTime ShipDate {get;set;}
public string Status {get;set;}
public string OnlineOrderFlag {get;set;}
public string SalesOrderNumber {get;set;}
public string PurchaseOrderNumber {get;set;}
public string AccountNumber {get;set;}
public int CustomerID {get;set;}
public int SalesPersonID {get;set;}
public int TerritoryID {get;set;}
public int BillToAddressID {get;set;}
public int ShipToAddressID {get;set;}
public int ShipMethodID {get;set;}
public int CreditCardID {get;set;}
public string CreditCardApprovalCode {get;set;}
public int CurrencyRateID {get;set;}
public string SubTotal {get;set;}
public string TaxAmt {get;set;}
public string Freight {get;set;}
public string TotalDue {get;set;}
public string Comment {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class SalesOrderHeaderSalesReason
{
public int SalesOrderID {get;set;}
public int SalesReasonID {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class SalesPerson
{
public int BusinessEntityID {get;set;}
public int TerritoryID {get;set;}
public string SalesQuota {get;set;}
public string Bonus {get;set;}
public string CommissionPct {get;set;}
public string SalesYTD {get;set;}
public string SalesLastYear {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class SalesPersonQuotaHistory
{
public int BusinessEntityID {get;set;}
public DateTime QuotaDate {get;set;}
public string SalesQuota {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class SalesReason
{
public int SalesReasonID {get;set;}
public string Name {get;set;}
public string ReasonType {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class SalesTaxRate
{
public int SalesTaxRateID {get;set;}
public int StateProvinceID {get;set;}
public string TaxType {get;set;}
public string TaxRate {get;set;}
public string Name {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class PersonCreditCard
{
public int BusinessEntityID {get;set;}
public int CreditCardID {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class SalesTerritory
{
public int TerritoryID {get;set;}
public string Name {get;set;}
public string CountryRegionCode {get;set;}
public string Group {get;set;}
public string SalesYTD {get;set;}
public string SalesLastYear {get;set;}
public string CostYTD {get;set;}
public string CostLastYear {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class vIndividualCustomer
{
public int BusinessEntityID {get;set;}
public string Title {get;set;}
public string FirstName {get;set;}
public string MiddleName {get;set;}
public string LastName {get;set;}
public string Suffix {get;set;}
public string PhoneNumber {get;set;}
public string PhoneNumberType {get;set;}
public string EmailAddress {get;set;}
public int EmailPromotion {get;set;}
public string AddressType {get;set;}
public string AddressLine1 {get;set;}
public string AddressLine2 {get;set;}
public string City {get;set;}
public string StateProvinceName {get;set;}
public string PostalCode {get;set;}
public string CountryRegionName {get;set;}
public string Demographics {get;set;}
}
public class vPersonDemographics
{
public int BusinessEntityID {get;set;}
public string TotalPurchaseYTD {get;set;}
public DateTime DateFirstPurchase {get;set;}
public DateTime BirthDate {get;set;}
public string MaritalStatus {get;set;}
public string YearlyIncome {get;set;}
public string Gender {get;set;}
public int TotalChildren {get;set;}
public int NumberChildrenAtHome {get;set;}
public string Education {get;set;}
public string Occupation {get;set;}
public string HomeOwnerFlag {get;set;}
public int NumberCarsOwned {get;set;}
}
public class vSalesPerson
{
public int BusinessEntityID {get;set;}
public string Title {get;set;}
public string FirstName {get;set;}
public string MiddleName {get;set;}
public string LastName {get;set;}
public string Suffix {get;set;}
public string JobTitle {get;set;}
public string PhoneNumber {get;set;}
public string PhoneNumberType {get;set;}
public string EmailAddress {get;set;}
public int EmailPromotion {get;set;}
public string AddressLine1 {get;set;}
public string AddressLine2 {get;set;}
public string City {get;set;}
public string StateProvinceName {get;set;}
public string PostalCode {get;set;}
public string CountryRegionName {get;set;}
public string TerritoryName {get;set;}
public string TerritoryGroup {get;set;}
public string SalesQuota {get;set;}
public string SalesYTD {get;set;}
public string SalesLastYear {get;set;}
}
public class SalesTerritoryHistory
{
public int BusinessEntityID {get;set;}
public int TerritoryID {get;set;}
public DateTime StartDate {get;set;}
public DateTime EndDate {get;set;}
public string rowguid {get;set;}
public DateTime ModifiedDate {get;set;}
}
public class vSalesPersonSalesByFiscalYears
{
public int SalesPersonID {get;set;}
public string FullName {get;set;}
public string JobTitle {get;set;}
public string SalesTerritory {get;set;}
public string 2002 {get;set;}
public string 2003 {get;set;}
public string 2004 {get;set;}
}
public class vStoreWithDemographics
{
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Projection
// Description: The basic module for MapWindow version 6.0
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The original content was ported from the C language from the 4.6 version of Proj4 libraries.
// Frank Warmerdam has released the full content of that version under the MIT license which is
// recognized as being approximately equivalent to public domain. The original work was done
// mostly by Gerald Evenden. The latest versions of the C libraries can be obtained here:
// http://trac.osgeo.org/proj/
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 8/13/2009 1:23:04 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// Name | Date | Comment
// --------------------|------------|------------------------------------------------------------
// Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL
// ********************************************************************************************************
using System;
namespace DotSpatial.Projections.Transforms
{
/// <summary>
/// Krovak
/// NOTES: According to EPSG the full Krovak projection method should have
/// the following parameters. Within PROJ.4 the azimuth, and pseudo
/// standard parallel are hardcoded in the algorithm and can't be
/// altered from outside. The others all have defaults to match the
/// common usage with Krovak projection.
///
/// lat_0 = latitude of centre of the projection
///
/// lon_0 = longitude of centre of the projection
///
/// ** = azimuth (true) of the centre line passing through the centre of the projection
///
/// ** = latitude of pseudo standard parallel
///
/// k = scale factor on the pseudo standard parallel
///
/// x_0 = False Easting of the centre of the projection at the apex of the cone
///
/// y_0 = False Northing of the centre of the projection at the apex of the cone
///
/// _czech = specifies the EAST-NORTH GIS usage where the axis are reversed:
/// X [S-JTSK KROVAK EAST NORTH] = -Y [KROVAK]
/// Y [S-JTSK KROVAK EAST NORTH] = -X [KROVAK]
/// </summary>
public class Krovak : Transform
{
#region Private Variables
//private double _cX;
private bool _czech;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of Krovak
/// </summary>
public Krovak()
{
Proj4Name = "krovak";
Name = "Krovak";
}
#endregion
#region Methods
/// <inheritdoc />
protected override void OnForward(double[] lp, double[] xy, int startIndex, int numPoints)
{
for (int i = startIndex; i < startIndex + numPoints; i++)
{
int phi = i * 2 + PHI;
int lam = i * 2 + LAMBDA;
int x = i * 2 + X;
int y = i * 2 + Y;
/* calculate xy from lat/lon */
/* Constants, identical to inverse transform function */
const double s45 = 0.785398163397448;
const double s90 = 2 * s45;
double fi0 = Phi0;
/* Ellipsoid is used as Parameter in for.c and inv.c, therefore a must
be set to 1 here.
Ellipsoid Bessel 1841 a = 6377397.155m 1/f = 299.1528128,
e2=0.006674372230614;
*/
const double a = 1;
/* e2 = Es;*/
/* 0.006674372230614; */
const double e2 = 0.006674372230614;
double e = Math.Sqrt(e2);
double alfa = Math.Sqrt(1 + (e2 * Math.Pow(Math.Cos(fi0), 4)) / (1 - e2));
const double uq = 1.04216856380474;
double u0 = Math.Asin(Math.Sin(fi0) / alfa);
double g = Math.Pow((1 + e * Math.Sin(fi0)) / (1 - e * Math.Sin(fi0)), alfa * e / 2);
double k = Math.Tan(u0 / 2 + s45) / Math.Pow(Math.Tan(fi0 / 2 + s45), alfa) * g;
double k1 = K0;
double n0 = a * Math.Sqrt(1 - e2) / (1 - e2 * Math.Pow(Math.Sin(fi0), 2));
const double s0 = 1.37008346281555;
double n = Math.Sin(s0);
double ro0 = k1 * n0 / Math.Tan(s0);
const double ad = s90 - uq;
/* Transformation */
double gfi = Math.Pow(((1 + e * Math.Sin(lp[phi])) /
(1 - e * Math.Sin(lp[phi]))), (alfa * e / 2));
double u = 2 * (Math.Atan(k * Math.Pow(Math.Tan(lp[phi] / 2 + s45), alfa) / gfi) - s45);
double deltav = -lp[lam] * alfa;
double s = Math.Asin(Math.Cos(ad) * Math.Sin(u) + Math.Sin(ad) * Math.Cos(u) * Math.Cos(deltav));
double d = Math.Asin(Math.Cos(u) * Math.Sin(deltav) / Math.Cos(s));
double eps = n * d;
double ro = ro0 * Math.Pow(Math.Tan(s0 / 2 + s45), n) / Math.Pow(Math.Tan(s / 2 + s45), n);
/* x and y are reverted! */
if (!_czech)
{
xy[y] = ro * Math.Sin(eps) / a;
xy[x] = ro * Math.Cos(eps) / a;
}
else
{
/* in Czech version, Y = -X and X = -Y */
xy[x] = -ro * Math.Sin(eps) / a;
xy[y] = -ro * Math.Cos(eps) / a;
}
}
}
/// <inheritdoc />
protected override void OnInverse(double[] xy, double[] lp, int startIndex, int numPoints)
{
/* calculate lat/lon from xy */
/* Constants, identisch wie in der Umkehrfunktion */
for (int i = startIndex; i < startIndex + numPoints; i++)
{
int phi = i * 2 + PHI;
int lam = i * 2 + LAMBDA;
int x = i * 2 + X;
int y = i * 2 + Y;
const double s45 = 0.785398163397448;
const double s90 = 2 * s45;
double fi0 = Phi0;
/* Ellipsoid is used as Parameter in for.c and inv.c, therefore a must
be set to 1 here.
Ellipsoid Bessel 1841 a = 6377397.155m 1/f = 299.1528128,
e2=0.006674372230614;
*/
const double a = 1;
/* e2 = Es; */
/* 0.006674372230614; */
const double e2 = 0.006674372230614;
double e = Math.Sqrt(e2);
double alfa = Math.Sqrt(1 + (e2 * Math.Pow(Math.Cos(fi0), 4)) / (1 - e2));
const double uq = 1.04216856380474;
double u0 = Math.Asin(Math.Sin(fi0) / alfa);
double g = Math.Pow((1 + e * Math.Sin(fi0)) / (1 - e * Math.Sin(fi0)), alfa * e / 2);
double k = Math.Tan(u0 / 2 + s45) / Math.Pow(Math.Tan(fi0 / 2 + s45), alfa) * g;
double k1 = K0;
double n0 = a * Math.Sqrt(1 - e2) / (1 - e2 * Math.Pow(Math.Sin(fi0), 2));
const double s0 = 1.37008346281555;
double n = Math.Sin(s0);
double ro0 = k1 * n0 / Math.Tan(s0);
const double ad = s90 - uq;
/* Transformation */
/* revert y, x*/
double xy0 = xy[x];
xy[x] = xy[y];
xy[y] = xy0;
if (_czech)
{
xy[x] *= -1.0;
xy[y] *= -1.0;
}
double ro = Math.Sqrt(xy[x] * xy[x] + xy[y] * xy[y]);
double eps = Math.Atan2(xy[y], xy[x]);
double d = eps / Math.Sin(s0);
double s = 2 * (Math.Atan(Math.Pow(ro0 / ro, 1 / n) * Math.Tan(s0 / 2 + s45)) - s45);
double u = Math.Asin(Math.Cos(ad) * Math.Sin(s) - Math.Sin(ad) * Math.Cos(s) * Math.Cos(d));
double deltav = Math.Asin(Math.Cos(s) * Math.Sin(d) / Math.Cos(u));
lp[lam] = Lam0 - deltav / alfa;
/* ITERATION FOR lp[phi] */
double fi1 = u;
int ok = 0;
do
{
lp[phi] = 2 * (Math.Atan(Math.Pow(k, -1 / alfa) *
Math.Pow(Math.Tan(u / 2 + s45), 1 / alfa) *
Math.Pow((1 + e * Math.Sin(fi1)) / (1 - e * Math.Sin(fi1)), e / 2)
) - s45);
if (Math.Abs(fi1 - lp[phi]) < 0.000000000000001) ok = 1;
fi1 = lp[phi];
} while (ok == 0);
lp[lam] -= Lam0;
}
}
/// <summary>
/// Initializes the transform using the parameters from the specified coordinate system information
/// </summary>
/// <param name="projInfo">A ProjectionInfo class contains all the standard and custom parameters needed to initialize this transform</param>
/// <remarks>The default value of CZECH is true: The X and Y axis are reversed and multiplied by -1 as typically used in GIS applications of Krovak</remarks>
protected override void OnInit(ProjectionInfo projInfo)
{
/* read some Parameters,
* here Latitude Truescale */
//double ts = 0;
//if (projInfo.StandardParallel1 != null) ts = projInfo.StandardParallel1.Value*Math.PI/180;
//_cX = ts;
/* we want Bessel as fixed ellipsoid */
A = 6377397.155;
E = Math.Sqrt(Es = 0.006674372230614);
/* if latitude of projection center is not set, use 49d30'N */
Phi0 = projInfo.LatitudeOfOrigin != null ? projInfo.Phi0 : 0.863937979737193;
/* if center long is not set use 42d30'E of Ferro - 17d40' for Ferro */
/* that will correspond to using longitudes relative to greenwich */
/* as input and output, instead of lat/long relative to Ferro */
Lam0 = projInfo.CentralMeridian != null ? projInfo.Lam0 : 0.7417649320975901 - 0.308341501185665;
/* if scale not set default to 0.9999 */
K0 = (projInfo.ScaleFactor != 1) ? projInfo.ScaleFactor : 0.9999;
//Previous BAD CODE (commented out!)
//K0 = projInfo.CentralMeridian != null ? projInfo.Lam0 : 0.9999;
if (projInfo.czech.HasValue)
{
if (projInfo.czech.Value != 0) _czech = true;
}
else
{
//By default set Czech to TRUE
_czech = true;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using MRTutorial.Identity.Client.Areas.HelpPage.ModelDescriptions;
using MRTutorial.Identity.Client.Areas.HelpPage.Models;
namespace MRTutorial.Identity.Client.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class VirtualKeywordRecommenderTests : KeywordRecommenderTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAtRoot_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterClass_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"class C { }
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterGlobalStatement_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterGlobalVariableDeclaration_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInUsingAlias()
{
VerifyAbsence(
@"using Foo = $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInEmptyStatement()
{
VerifyAbsence(AddInsideMethod(
@"$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInCompilationUnit()
{
VerifyAbsence(@"$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterExtern()
{
VerifyAbsence(@"extern alias Foo;
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterUsing()
{
VerifyAbsence(@"using Foo;
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNamespace()
{
VerifyAbsence(@"namespace N {}
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterTypeDeclaration()
{
VerifyAbsence(@"class C {}
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterDelegateDeclaration()
{
VerifyAbsence(@"delegate void Foo();
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethodInClass()
{
VerifyKeyword(
@"class C {
void Foo() {}
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterFieldInClass()
{
VerifyKeyword(
@"class C {
int i;
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPropertyInClass()
{
VerifyKeyword(
@"class C {
int i { get; }
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotBeforeUsing()
{
VerifyAbsence(
@"$$
using Foo;");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterAssemblyAttribute()
{
VerifyAbsence(@"[assembly: foo]
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterRootAttribute()
{
VerifyAbsence(@"[foo]
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedAttribute()
{
VerifyKeyword(
@"class C {
[foo]
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInsideStruct()
{
VerifyAbsence(@"struct S {
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInsideInterface()
{
VerifyAbsence(@"interface I {
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideClass()
{
VerifyKeyword(
@"class C {
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterPartial()
{
VerifyAbsence(@"partial $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterAbstract()
{
VerifyAbsence(@"abstract $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterInternal()
{
VerifyAbsence(@"internal $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterPublic()
{
VerifyAbsence(@"public $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterStaticInternal()
{
VerifyAbsence(@"static internal $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterInternalStatic()
{
VerifyAbsence(@"internal static $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterInvalidInternal()
{
VerifyAbsence(@"virtual internal $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterClass()
{
VerifyAbsence(@"class $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterPrivate()
{
VerifyAbsence(@"private $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterSealed()
{
VerifyAbsence(@"sealed $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterStatic()
{
VerifyAbsence(@"static $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNestedStatic()
{
VerifyAbsence(@"class C {
static $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedInternal()
{
VerifyKeyword(
@"class C {
internal $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNestedPrivate()
{
VerifyAbsence(@"class C {
private $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterDelegate()
{
VerifyAbsence(@"delegate $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNestedAbstract()
{
VerifyAbsence(@"class C {
abstract $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNestedVirtual()
{
VerifyAbsence(@"class C {
virtual $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNestedOverride()
{
VerifyAbsence(@"class C {
override $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNestedSealed()
{
VerifyAbsence(@"class C {
sealed $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInProperty()
{
VerifyAbsence(
@"class C {
int Foo { $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPropertyAfterAccessor()
{
VerifyAbsence(
@"class C {
int Foo { get; $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPropertyAfterAccessibility()
{
VerifyAbsence(
@"class C {
int Foo { get; protected $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPropertyAfterInternal()
{
VerifyAbsence(
@"class C {
int Foo { get; internal $$");
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SimpleErlangConverter.cs" company="The original author or authors.">
// Copyright 2002-2012 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
#region Using Directives
using System.Collections.Generic;
using Erlang.NET;
#endregion
namespace Spring.Erlang.Support.Converter
{
/// <summary>
/// Converter that supports the basic types.
/// </summary>
/// <author>Mark Pollack</author>
public class SimpleErlangConverter : IErlangConverter
{
#region Implementation of IErlangConverter
/// <summary>Convert from an Erlang data type to a .NET data type.</summary>
/// <param name="erlangObject">The erlang object.</param>
/// <returns>The converted .NET object</returns>
/// <exception cref="ErlangConversionException">in case of conversion failures</exception>
public virtual object FromErlang(OtpErlangObject erlangObject)
{
// TODO: support arrays
return this.ConvertErlangToBasicType(erlangObject);
}
/// <summary>The return value from executing the Erlang RPC.</summary>
/// <param name="module">The module to call</param>
/// <param name="function">The function to invoke</param>
/// <param name="erlangObject">The erlang object that is passed in as a parameter</param>
/// <returns>The converted .NET object return value from the RPC call.</returns>
/// <exception cref="ErlangConversionException">in case of conversion failures</exception>
public virtual object FromErlangRpc(string module, string function, OtpErlangObject erlangObject) { return this.FromErlang(erlangObject); }
/// <summary>Convert a .NET object to a Erlang data type.</summary>
/// <param name="objectToConvert">The object to convert.</param>
/// <returns>the Erlang data type</returns>
/// <exception cref="ErlangConversionException">in case of conversion failures</exception>
public virtual OtpErlangObject ToErlang(object objectToConvert)
{
if (objectToConvert is OtpErlangObject)
{
return (OtpErlangObject)objectToConvert;
}
if (objectToConvert is object[])
{
var objectsToConvert = (object[])objectToConvert;
if (objectsToConvert.Length != 0)
{
var tempList = new List<OtpErlangObject>();
foreach (var toConvert in objectsToConvert)
{
var erlangObject = this.ConvertBasicTypeToErlang(toConvert);
tempList.Add(erlangObject);
}
var ia = tempList.ToArray();
return new OtpErlangList(ia);
}
else
{
return new OtpErlangList();
}
}
else
{
return this.ConvertBasicTypeToErlang(objectToConvert);
}
}
/// <summary>Converts the basic type to erlang.</summary>
/// <param name="obj">The obj.</param>
/// <returns>The object.</returns>
private OtpErlangObject ConvertBasicTypeToErlang(object obj)
{
if (obj is byte[])
{
return new OtpErlangBinary((byte[])obj);
}
else if (obj is bool)
{
return new OtpErlangBoolean((bool)obj);
}
else if (obj is byte)
{
return new OtpErlangByte((byte)obj);
}
else if (obj is char)
{
return new OtpErlangChar((char)obj);
}
else if (obj is double)
{
return new OtpErlangDouble((double)obj);
}
else if (obj is float)
{
return new OtpErlangFloat((float)obj);
}
else if (obj is int)
{
return new OtpErlangInt((int)obj);
}
else if (obj is long)
{
return new OtpErlangLong((long)obj);
}
else if (obj is short)
{
return new OtpErlangShort((short)obj);
}
else if (obj is string)
{
return new OtpErlangString((string)obj);
}
else
{
throw new ErlangConversionException(
"Could not convert .NET object of type [" + obj.GetType()
+ "] to an Erlang data type.");
}
}
/// <summary>Converts the type of the erlang to basic.</summary>
/// <param name="erlangObject">The erlang object.</param>
/// <returns>The object.</returns>
private object ConvertErlangToBasicType(OtpErlangObject erlangObject)
{
try
{
if (erlangObject is OtpErlangBinary)
{
return ((OtpErlangBinary)erlangObject).binaryValue();
}
else if (erlangObject is OtpErlangAtom)
{
return ((OtpErlangAtom)erlangObject).atomValue();
}
else if (erlangObject is OtpErlangBinary)
{
return ((OtpErlangBinary)erlangObject).binaryValue();
}
else if (erlangObject is OtpErlangBoolean)
{
return ExtractBoolean(erlangObject);
}
else if (erlangObject is OtpErlangByte)
{
return ((OtpErlangByte)erlangObject).byteValue();
}
else if (erlangObject is OtpErlangChar)
{
return ((OtpErlangChar)erlangObject).charValue();
}
else if (erlangObject is OtpErlangDouble)
{
return ((OtpErlangDouble)erlangObject).doubleValue();
}
else if (erlangObject is OtpErlangFloat)
{
return ((OtpErlangFloat)erlangObject).floatValue();
}
else if (erlangObject is OtpErlangInt)
{
return ((OtpErlangInt)erlangObject).intValue();
}
else if (erlangObject is OtpErlangLong)
{
return ((OtpErlangLong)erlangObject).longValue();
}
else if (erlangObject is OtpErlangShort)
{
return ((OtpErlangShort)erlangObject).shortValue();
}
else if (erlangObject is OtpErlangString)
{
return ((OtpErlangString)erlangObject).stringValue();
}
else if (erlangObject is OtpErlangPid)
{
return erlangObject.ToString();
}
else
{
throw new ErlangConversionException(
"Could not convert Erlang object ["
+ erlangObject.GetType() + "] to .NET type.");
}
}
catch (OtpErlangRangeException ex)
{
// TODO: Erlang.NET exceptions do not support nesting root exceptions.
throw new ErlangConversionException(
"Could not convert Erlang object [" + erlangObject.GetType()
+ "] to .NET type. OtpErlangRangeException msg [" + ex.Message +
"]");
}
}
#endregion
/// <summary>Extracts the boolean.</summary>
/// <param name="erlangObject">The erlang object.</param>
/// <returns>The boolean.</returns>
public static bool ExtractBoolean(OtpErlangObject erlangObject)
{
// TODO Erlang.NET has wrong capitilization
return ((OtpErlangBoolean)erlangObject).boolValue();
}
/// <summary>The extract pid.</summary>
/// <param name="value">The value.</param>
/// <returns>The System.String.</returns>
public static string ExtractPid(OtpErlangObject value) { return value.ToString(); }
/// <summary>Extracts the long.</summary>
/// <param name="value">The value.</param>
/// <returns>The long.</returns>
public static long ExtractLong(OtpErlangObject value) { return ((OtpErlangLong)value).longValue(); }
}
}
| |
// 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.Reflection;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Reflection.Runtime.Assemblies;
using Internal.LowLevelLinq;
using Internal.Reflection.Core;
using Internal.Runtime.Augments;
using Internal.Metadata.NativeFormat;
using NativeFormatAssemblyFlags = global::Internal.Metadata.NativeFormat.AssemblyFlags;
namespace System.Reflection.Runtime.General
{
//
// Collect various metadata reading tasks for better chunking...
//
internal static class NativeFormatMetadataReaderExtensions
{
public static bool StringOrNullEquals(this ConstantStringValueHandle handle, String valueOrNull, MetadataReader reader)
{
if (valueOrNull == null)
return handle.IsNull(reader);
if (handle.IsNull(reader))
return false;
return handle.StringEquals(valueOrNull, reader);
}
// Needed for RuntimeMappingTable access
public static int AsInt(this TypeDefinitionHandle typeDefinitionHandle)
{
unsafe
{
return *(int*)&typeDefinitionHandle;
}
}
public static TypeDefinitionHandle AsTypeDefinitionHandle(this int i)
{
unsafe
{
return *(TypeDefinitionHandle*)&i;
}
}
public static int AsInt(this MethodHandle methodHandle)
{
unsafe
{
return *(int*)&methodHandle;
}
}
public static MethodHandle AsMethodHandle(this int i)
{
unsafe
{
return *(MethodHandle*)&i;
}
}
public static int AsInt(this FieldHandle fieldHandle)
{
unsafe
{
return *(int*)&fieldHandle;
}
}
public static FieldHandle AsFieldHandle(this int i)
{
unsafe
{
return *(FieldHandle*)&i;
}
}
public static bool IsNamespaceDefinitionHandle(this Handle handle, MetadataReader reader)
{
HandleType handleType = handle.HandleType;
return handleType == HandleType.NamespaceDefinition;
}
public static bool IsNamespaceReferenceHandle(this Handle handle, MetadataReader reader)
{
HandleType handleType = handle.HandleType;
return handleType == HandleType.NamespaceReference;
}
// Conversion where a invalid handle type indicates bad metadata rather a mistake by the caller.
public static ScopeReferenceHandle ToExpectedScopeReferenceHandle(this Handle handle, MetadataReader reader)
{
try
{
return handle.ToScopeReferenceHandle(reader);
}
catch (ArgumentException)
{
throw new BadImageFormatException();
}
}
// Conversion where a invalid handle type indicates bad metadata rather a mistake by the caller.
public static NamespaceReferenceHandle ToExpectedNamespaceReferenceHandle(this Handle handle, MetadataReader reader)
{
try
{
return handle.ToNamespaceReferenceHandle(reader);
}
catch (ArgumentException)
{
throw new BadImageFormatException();
}
}
// Conversion where a invalid handle type indicates bad metadata rather a mistake by the caller.
public static TypeDefinitionHandle ToExpectedTypeDefinitionHandle(this Handle handle, MetadataReader reader)
{
try
{
return handle.ToTypeDefinitionHandle(reader);
}
catch (ArgumentException)
{
throw new BadImageFormatException();
}
}
// Return any custom modifiers modifying the passed-in type and whose required/optional bit matches the passed in boolean.
// Because this is intended to service the GetCustomModifiers() apis, this helper will always return a freshly allocated array
// safe for returning to api callers.
public static Type[] GetCustomModifiers(this Handle handle, MetadataReader reader, TypeContext typeContext, bool optional)
{
HandleType handleType = handle.HandleType;
Debug.Assert(handleType == HandleType.TypeDefinition || handleType == HandleType.TypeReference || handleType == HandleType.TypeSpecification || handleType == HandleType.ModifiedType);
if (handleType != HandleType.ModifiedType)
return Array.Empty<Type>();
LowLevelList<Type> customModifiers = new LowLevelList<Type>();
do
{
ModifiedType modifiedType = handle.ToModifiedTypeHandle(reader).GetModifiedType(reader);
if (optional == modifiedType.IsOptional)
{
Type customModifier = modifiedType.ModifierType.Resolve(reader, typeContext);
customModifiers.Insert(0, customModifier);
}
handle = modifiedType.Type;
handleType = handle.HandleType;
}
while (handleType == HandleType.ModifiedType);
return customModifiers.ToArray();
}
public static MethodSignature ParseMethodSignature(this Handle handle, MetadataReader reader)
{
return handle.ToMethodSignatureHandle(reader).GetMethodSignature(reader);
}
public static FieldSignature ParseFieldSignature(this Handle handle, MetadataReader reader)
{
return handle.ToFieldSignatureHandle(reader).GetFieldSignature(reader);
}
public static PropertySignature ParsePropertySignature(this Handle handle, MetadataReader reader)
{
return handle.ToPropertySignatureHandle(reader).GetPropertySignature(reader);
}
//
// Used to split methods between DeclaredMethods and DeclaredConstructors.
//
public static bool IsConstructor(this MethodHandle methodHandle, MetadataReader reader)
{
Method method = methodHandle.GetMethod(reader);
return IsConstructor(ref method, reader);
}
// This is specially designed for a hot path so we make some compromises in the signature:
//
// - "method" is passed by reference even though no side-effects are intended.
//
public static bool IsConstructor(ref Method method, MetadataReader reader)
{
if ((method.Flags & (MethodAttributes.RTSpecialName | MethodAttributes.SpecialName)) != (MethodAttributes.RTSpecialName | MethodAttributes.SpecialName))
return false;
ConstantStringValueHandle nameHandle = method.Name;
return nameHandle.StringEquals(ConstructorInfo.ConstructorName, reader) || nameHandle.StringEquals(ConstructorInfo.TypeConstructorName, reader);
}
private static Exception ParseBoxedEnumConstantValue(this ConstantBoxedEnumValueHandle handle, MetadataReader reader, out Object value)
{
ConstantBoxedEnumValue record = handle.GetConstantBoxedEnumValue(reader);
Exception exception = null;
Type enumType = record.Type.TryResolve(reader, new TypeContext(null, null), ref exception);
if (enumType == null)
{
value = null;
return exception;
}
if (!enumType.IsEnum)
throw new BadImageFormatException();
Type underlyingType = Enum.GetUnderlyingType(enumType);
// Now box the value as the specified enum type.
unsafe
{
switch (record.Value.HandleType)
{
case HandleType.ConstantByteValue:
{
if (underlyingType != CommonRuntimeTypes.Byte)
throw new BadImageFormatException();
byte v = record.Value.ToConstantByteValueHandle(reader).GetConstantByteValue(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantSByteValue:
{
if (underlyingType != CommonRuntimeTypes.SByte)
throw new BadImageFormatException();
sbyte v = record.Value.ToConstantSByteValueHandle(reader).GetConstantSByteValue(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantInt16Value:
{
if (underlyingType != CommonRuntimeTypes.Int16)
throw new BadImageFormatException();
short v = record.Value.ToConstantInt16ValueHandle(reader).GetConstantInt16Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantUInt16Value:
{
if (underlyingType != CommonRuntimeTypes.UInt16)
throw new BadImageFormatException();
ushort v = record.Value.ToConstantUInt16ValueHandle(reader).GetConstantUInt16Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantInt32Value:
{
if (underlyingType != CommonRuntimeTypes.Int32)
throw new BadImageFormatException();
int v = record.Value.ToConstantInt32ValueHandle(reader).GetConstantInt32Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantUInt32Value:
{
if (underlyingType != CommonRuntimeTypes.UInt32)
throw new BadImageFormatException();
uint v = record.Value.ToConstantUInt32ValueHandle(reader).GetConstantUInt32Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantInt64Value:
{
if (underlyingType != CommonRuntimeTypes.Int64)
throw new BadImageFormatException();
long v = record.Value.ToConstantInt64ValueHandle(reader).GetConstantInt64Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantUInt64Value:
{
if (underlyingType != CommonRuntimeTypes.UInt64)
throw new BadImageFormatException();
ulong v = record.Value.ToConstantUInt64ValueHandle(reader).GetConstantUInt64Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
default:
throw new BadImageFormatException();
}
}
}
public static Object ParseConstantValue(this Handle handle, MetadataReader reader)
{
Object value;
Exception exception = handle.TryParseConstantValue(reader, out value);
if (exception != null)
throw exception;
return value;
}
public static Exception TryParseConstantValue(this Handle handle, MetadataReader reader, out Object value)
{
HandleType handleType = handle.HandleType;
switch (handleType)
{
case HandleType.ConstantBooleanValue:
value = handle.ToConstantBooleanValueHandle(reader).GetConstantBooleanValue(reader).Value;
return null;
case HandleType.ConstantStringValue:
value = handle.ToConstantStringValueHandle(reader).GetConstantStringValue(reader).Value;
return null;
case HandleType.ConstantCharValue:
value = handle.ToConstantCharValueHandle(reader).GetConstantCharValue(reader).Value;
return null;
case HandleType.ConstantByteValue:
value = handle.ToConstantByteValueHandle(reader).GetConstantByteValue(reader).Value;
return null;
case HandleType.ConstantSByteValue:
value = handle.ToConstantSByteValueHandle(reader).GetConstantSByteValue(reader).Value;
return null;
case HandleType.ConstantInt16Value:
value = handle.ToConstantInt16ValueHandle(reader).GetConstantInt16Value(reader).Value;
return null;
case HandleType.ConstantUInt16Value:
value = handle.ToConstantUInt16ValueHandle(reader).GetConstantUInt16Value(reader).Value;
return null;
case HandleType.ConstantInt32Value:
value = handle.ToConstantInt32ValueHandle(reader).GetConstantInt32Value(reader).Value;
return null;
case HandleType.ConstantUInt32Value:
value = handle.ToConstantUInt32ValueHandle(reader).GetConstantUInt32Value(reader).Value;
return null;
case HandleType.ConstantInt64Value:
value = handle.ToConstantInt64ValueHandle(reader).GetConstantInt64Value(reader).Value;
return null;
case HandleType.ConstantUInt64Value:
value = handle.ToConstantUInt64ValueHandle(reader).GetConstantUInt64Value(reader).Value;
return null;
case HandleType.ConstantSingleValue:
value = handle.ToConstantSingleValueHandle(reader).GetConstantSingleValue(reader).Value;
return null;
case HandleType.ConstantDoubleValue:
value = handle.ToConstantDoubleValueHandle(reader).GetConstantDoubleValue(reader).Value;
return null;
case HandleType.TypeDefinition:
case HandleType.TypeReference:
case HandleType.TypeSpecification:
{
Exception exception = null;
Type type = handle.TryResolve(reader, new TypeContext(null, null), ref exception);
value = type;
return (value == null) ? exception : null;
}
case HandleType.ConstantReferenceValue:
value = null;
return null;
case HandleType.ConstantBoxedEnumValue:
{
return handle.ToConstantBoxedEnumValueHandle(reader).ParseBoxedEnumConstantValue(reader, out value);
}
default:
{
Exception exception;
value = handle.TryParseConstantArray(reader, out exception);
if (value == null)
return exception;
return null;
}
}
}
private static Array TryParseConstantArray(this Handle handle, MetadataReader reader, out Exception exception)
{
exception = null;
HandleType handleType = handle.HandleType;
switch (handleType)
{
case HandleType.ConstantBooleanArray:
return handle.ToConstantBooleanArrayHandle(reader).GetConstantBooleanArray(reader).Value.ToArray();
case HandleType.ConstantCharArray:
return handle.ToConstantCharArrayHandle(reader).GetConstantCharArray(reader).Value.ToArray();
case HandleType.ConstantByteArray:
return handle.ToConstantByteArrayHandle(reader).GetConstantByteArray(reader).Value.ToArray();
case HandleType.ConstantSByteArray:
return handle.ToConstantSByteArrayHandle(reader).GetConstantSByteArray(reader).Value.ToArray();
case HandleType.ConstantInt16Array:
return handle.ToConstantInt16ArrayHandle(reader).GetConstantInt16Array(reader).Value.ToArray();
case HandleType.ConstantUInt16Array:
return handle.ToConstantUInt16ArrayHandle(reader).GetConstantUInt16Array(reader).Value.ToArray();
case HandleType.ConstantInt32Array:
return handle.ToConstantInt32ArrayHandle(reader).GetConstantInt32Array(reader).Value.ToArray();
case HandleType.ConstantUInt32Array:
return handle.ToConstantUInt32ArrayHandle(reader).GetConstantUInt32Array(reader).Value.ToArray();
case HandleType.ConstantInt64Array:
return handle.ToConstantInt64ArrayHandle(reader).GetConstantInt64Array(reader).Value.ToArray();
case HandleType.ConstantUInt64Array:
return handle.ToConstantUInt64ArrayHandle(reader).GetConstantUInt64Array(reader).Value.ToArray();
case HandleType.ConstantSingleArray:
return handle.ToConstantSingleArrayHandle(reader).GetConstantSingleArray(reader).Value.ToArray();
case HandleType.ConstantDoubleArray:
return handle.ToConstantDoubleArrayHandle(reader).GetConstantDoubleArray(reader).Value.ToArray();
case HandleType.ConstantEnumArray:
return TryParseConstantEnumArray(handle.ToConstantEnumArrayHandle(reader), reader, out exception);
case HandleType.ConstantStringArray:
{
HandleCollection constantHandles = handle.ToConstantStringArrayHandle(reader).GetConstantStringArray(reader).Value;
string[] elements = new string[constantHandles.Count];
int i = 0;
foreach (Handle constantHandle in constantHandles)
{
object elementValue;
exception = constantHandle.TryParseConstantValue(reader, out elementValue);
if (exception != null)
return null;
elements[i] = (string)elementValue;
i++;
}
return elements;
}
case HandleType.ConstantHandleArray:
{
HandleCollection constantHandles = handle.ToConstantHandleArrayHandle(reader).GetConstantHandleArray(reader).Value;
object[] elements = new object[constantHandles.Count];
int i = 0;
foreach (Handle constantHandle in constantHandles)
{
exception = constantHandle.TryParseConstantValue(reader, out elements[i]);
if (exception != null)
return null;
i++;
}
return elements;
}
default:
throw new BadImageFormatException();
}
}
private static Array TryParseConstantEnumArray(this ConstantEnumArrayHandle handle, MetadataReader reader, out Exception exception)
{
exception = null;
ConstantEnumArray enumArray = handle.GetConstantEnumArray(reader);
Type elementType = enumArray.ElementType.TryResolve(reader, new TypeContext(null, null), ref exception);
if (exception != null)
return null;
switch (enumArray.Value.HandleType)
{
case HandleType.ConstantByteArray:
return enumArray.Value.ToConstantByteArrayHandle(reader).GetConstantByteArray(reader).Value.ToArray(elementType);
case HandleType.ConstantSByteArray:
return enumArray.Value.ToConstantSByteArrayHandle(reader).GetConstantSByteArray(reader).Value.ToArray(elementType);
case HandleType.ConstantInt16Array:
return enumArray.Value.ToConstantInt16ArrayHandle(reader).GetConstantInt16Array(reader).Value.ToArray(elementType);
case HandleType.ConstantUInt16Array:
return enumArray.Value.ToConstantUInt16ArrayHandle(reader).GetConstantUInt16Array(reader).Value.ToArray(elementType);
case HandleType.ConstantInt32Array:
return enumArray.Value.ToConstantInt32ArrayHandle(reader).GetConstantInt32Array(reader).Value.ToArray(elementType);
case HandleType.ConstantUInt32Array:
return enumArray.Value.ToConstantUInt32ArrayHandle(reader).GetConstantUInt32Array(reader).Value.ToArray(elementType);
case HandleType.ConstantInt64Array:
return enumArray.Value.ToConstantInt64ArrayHandle(reader).GetConstantInt64Array(reader).Value.ToArray(elementType);
case HandleType.ConstantUInt64Array:
return enumArray.Value.ToConstantUInt64ArrayHandle(reader).GetConstantUInt64Array(reader).Value.ToArray(elementType);
default:
throw new BadImageFormatException();
}
}
public static Handle GetAttributeTypeHandle(this CustomAttribute customAttribute,
MetadataReader reader)
{
HandleType constructorHandleType = customAttribute.Constructor.HandleType;
if (constructorHandleType == HandleType.QualifiedMethod)
return customAttribute.Constructor.ToQualifiedMethodHandle(reader).GetQualifiedMethod(reader).EnclosingType;
else if (constructorHandleType == HandleType.MemberReference)
return customAttribute.Constructor.ToMemberReferenceHandle(reader).GetMemberReference(reader).Parent;
else
throw new BadImageFormatException();
}
//
// Lightweight check to see if a custom attribute's is of a well-known type.
//
// This check performs without instantating the Type object and bloating memory usage. On the flip side,
// it doesn't check on whether the type is defined in a paricular assembly. The desktop CLR typically doesn't
// check this either so this is useful from a compat persective as well.
//
public static bool IsCustomAttributeOfType(this CustomAttributeHandle customAttributeHandle,
MetadataReader reader,
String ns,
String name)
{
String[] namespaceParts = ns.Split('.');
Handle typeHandle = customAttributeHandle.GetCustomAttribute(reader).GetAttributeTypeHandle(reader);
HandleType handleType = typeHandle.HandleType;
if (handleType == HandleType.TypeDefinition)
{
TypeDefinition typeDefinition = typeHandle.ToTypeDefinitionHandle(reader).GetTypeDefinition(reader);
if (!typeDefinition.Name.StringEquals(name, reader))
return false;
NamespaceDefinitionHandle nsHandle = typeDefinition.NamespaceDefinition;
int idx = namespaceParts.Length;
while (idx-- != 0)
{
String namespacePart = namespaceParts[idx];
NamespaceDefinition namespaceDefinition = nsHandle.GetNamespaceDefinition(reader);
if (!namespaceDefinition.Name.StringOrNullEquals(namespacePart, reader))
return false;
if (!namespaceDefinition.ParentScopeOrNamespace.IsNamespaceDefinitionHandle(reader))
return false;
nsHandle = namespaceDefinition.ParentScopeOrNamespace.ToNamespaceDefinitionHandle(reader);
}
if (!nsHandle.GetNamespaceDefinition(reader).Name.StringOrNullEquals(null, reader))
return false;
return true;
}
else if (handleType == HandleType.TypeReference)
{
TypeReference typeReference = typeHandle.ToTypeReferenceHandle(reader).GetTypeReference(reader);
if (!typeReference.TypeName.StringEquals(name, reader))
return false;
if (!typeReference.ParentNamespaceOrType.IsNamespaceReferenceHandle(reader))
return false;
NamespaceReferenceHandle nsHandle = typeReference.ParentNamespaceOrType.ToNamespaceReferenceHandle(reader);
int idx = namespaceParts.Length;
while (idx-- != 0)
{
String namespacePart = namespaceParts[idx];
NamespaceReference namespaceReference = nsHandle.GetNamespaceReference(reader);
if (!namespaceReference.Name.StringOrNullEquals(namespacePart, reader))
return false;
if (!namespaceReference.ParentScopeOrNamespace.IsNamespaceReferenceHandle(reader))
return false;
nsHandle = namespaceReference.ParentScopeOrNamespace.ToNamespaceReferenceHandle(reader);
}
if (!nsHandle.GetNamespaceReference(reader).Name.StringOrNullEquals(null, reader))
return false;
return true;
}
else
throw new NotSupportedException();
}
public static String ToNamespaceName(this NamespaceDefinitionHandle namespaceDefinitionHandle, MetadataReader reader)
{
String ns = "";
for (;;)
{
NamespaceDefinition currentNamespaceDefinition = namespaceDefinitionHandle.GetNamespaceDefinition(reader);
String name = currentNamespaceDefinition.Name.GetStringOrNull(reader);
if (name != null)
{
if (ns.Length != 0)
ns = "." + ns;
ns = name + ns;
}
Handle nextHandle = currentNamespaceDefinition.ParentScopeOrNamespace;
HandleType handleType = nextHandle.HandleType;
if (handleType == HandleType.ScopeDefinition)
break;
if (handleType == HandleType.NamespaceDefinition)
{
namespaceDefinitionHandle = nextHandle.ToNamespaceDefinitionHandle(reader);
continue;
}
throw new BadImageFormatException(SR.Bif_InvalidMetadata);
}
return ns;
}
public static IEnumerable<NamespaceDefinitionHandle> GetTransitiveNamespaces(this MetadataReader reader, IEnumerable<NamespaceDefinitionHandle> namespaceHandles)
{
foreach (NamespaceDefinitionHandle namespaceHandle in namespaceHandles)
{
yield return namespaceHandle;
NamespaceDefinition namespaceDefinition = namespaceHandle.GetNamespaceDefinition(reader);
foreach (NamespaceDefinitionHandle childNamespaceHandle in GetTransitiveNamespaces(reader, namespaceDefinition.NamespaceDefinitions.AsEnumerable()))
yield return childNamespaceHandle;
}
}
public static IEnumerable<TypeDefinitionHandle> GetTopLevelTypes(this MetadataReader reader, IEnumerable<NamespaceDefinitionHandle> namespaceHandles)
{
foreach (NamespaceDefinitionHandle namespaceHandle in namespaceHandles)
{
NamespaceDefinition namespaceDefinition = namespaceHandle.GetNamespaceDefinition(reader);
foreach (TypeDefinitionHandle typeDefinitionHandle in namespaceDefinition.TypeDefinitions)
{
yield return typeDefinitionHandle;
}
}
}
public static IEnumerable<TypeDefinitionHandle> GetTransitiveTypes(this MetadataReader reader, IEnumerable<TypeDefinitionHandle> typeDefinitionHandles, bool publicOnly)
{
foreach (TypeDefinitionHandle typeDefinitionHandle in typeDefinitionHandles)
{
TypeDefinition typeDefinition = typeDefinitionHandle.GetTypeDefinition(reader);
if (publicOnly)
{
TypeAttributes visibility = typeDefinition.Flags & TypeAttributes.VisibilityMask;
if (visibility != TypeAttributes.Public && visibility != TypeAttributes.NestedPublic)
continue;
}
yield return typeDefinitionHandle;
foreach (TypeDefinitionHandle nestedTypeDefinitionHandle in GetTransitiveTypes(reader, typeDefinition.NestedTypes.AsEnumerable(), publicOnly))
yield return nestedTypeDefinitionHandle;
}
}
/// <summary>
/// Reverse len characters in a StringBuilder starting at offset index
/// </summary>
private static void ReverseStringInStringBuilder(StringBuilder builder, int index, int len)
{
int back = index + len - 1;
int front = index;
while (front < back)
{
char temp = builder[front];
builder[front] = builder[back];
builder[back] = temp;
front++;
back--;
}
}
public static string ToFullyQualifiedTypeName(this NamespaceReferenceHandle namespaceReferenceHandle, string typeName, MetadataReader reader)
{
StringBuilder fullName = new StringBuilder(64);
NamespaceReference namespaceReference;
for (;;)
{
namespaceReference = namespaceReferenceHandle.GetNamespaceReference(reader);
String namespacePart = namespaceReference.Name.GetStringOrNull(reader);
if (namespacePart == null)
break;
fullName.Append('.');
int index = fullName.Length;
fullName.Append(namespacePart);
ReverseStringInStringBuilder(fullName, index, namespacePart.Length);
namespaceReferenceHandle = namespaceReference.ParentScopeOrNamespace.ToExpectedNamespaceReferenceHandle(reader);
}
ReverseStringInStringBuilder(fullName, 0, fullName.Length);
fullName.Append(typeName);
return fullName.ToString();
}
public static IEnumerable<NamespaceDefinitionHandle> AsEnumerable(this NamespaceDefinitionHandleCollection collection)
{
foreach (NamespaceDefinitionHandle handle in collection)
yield return handle;
}
public static IEnumerable<TypeDefinitionHandle> AsEnumerable(this TypeDefinitionHandleCollection collection)
{
foreach (TypeDefinitionHandle handle in collection)
yield return handle;
}
public static Handle[] ToArray(this HandleCollection collection)
{
int count = collection.Count;
Handle[] result = new Handle[count];
int i = 0;
foreach (Handle element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static bool[] ToArray(this BooleanCollection collection)
{
int count = collection.Count;
bool[] result = new bool[count];
int i = 0;
foreach (bool element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static char[] ToArray(this CharCollection collection)
{
int count = collection.Count;
char[] result = new char[count];
int i = 0;
foreach (char element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static float[] ToArray(this SingleCollection collection)
{
int count = collection.Count;
float[] result = new float[count];
int i = 0;
foreach (float element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static double[] ToArray(this DoubleCollection collection)
{
int count = collection.Count;
double[] result = new double[count];
int i = 0;
foreach (double element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static byte[] ToArray(this ByteCollection collection, Type enumType = null)
{
int count = collection.Count;
byte[] result;
if (enumType != null)
{
Debug.Assert(enumType.IsEnum);
result = (byte[])Array.CreateInstance(enumType, count);
}
else
{
result = new byte[count];
}
int i = 0;
foreach (byte element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static sbyte[] ToArray(this SByteCollection collection, Type enumType = null)
{
int count = collection.Count;
sbyte[] result;
if (enumType != null)
{
Debug.Assert(enumType.IsEnum);
result = (sbyte[])Array.CreateInstance(enumType, count);
}
else
{
result = new sbyte[count];
}
int i = 0;
foreach (sbyte element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static ushort[] ToArray(this UInt16Collection collection, Type enumType = null)
{
int count = collection.Count;
ushort[] result;
if (enumType != null)
{
Debug.Assert(enumType.IsEnum);
result = (ushort[])Array.CreateInstance(enumType, count);
}
else
{
result = new ushort[count];
}
int i = 0;
foreach (ushort element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static short[] ToArray(this Int16Collection collection, Type enumType = null)
{
int count = collection.Count;
short[] result;
if (enumType != null)
{
Debug.Assert(enumType.IsEnum);
result = (short[])Array.CreateInstance(enumType, count);
}
else
{
result = new short[count];
}
int i = 0;
foreach (short element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static uint[] ToArray(this UInt32Collection collection, Type enumType = null)
{
int count = collection.Count;
uint[] result;
if (enumType != null)
{
Debug.Assert(enumType.IsEnum);
result = (uint[])Array.CreateInstance(enumType, count);
}
else
{
result = new uint[count];
}
int i = 0;
foreach (uint element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static int[] ToArray(this Int32Collection collection, Type enumType = null)
{
int count = collection.Count;
int[] result;
if (enumType != null)
{
Debug.Assert(enumType.IsEnum);
result = (int[])Array.CreateInstance(enumType, count);
}
else
{
result = new int[count];
}
int i = 0;
foreach (int element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static ulong[] ToArray(this UInt64Collection collection, Type enumType = null)
{
int count = collection.Count;
ulong[] result;
if (enumType != null)
{
Debug.Assert(enumType.IsEnum);
result = (ulong[])Array.CreateInstance(enumType, count);
}
else
{
result = new ulong[count];
}
int i = 0;
foreach (ulong element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static long[] ToArray(this Int64Collection collection, Type enumType = null)
{
int count = collection.Count;
long[] result;
if (enumType != null)
{
Debug.Assert(enumType.IsEnum);
result = (long[])Array.CreateInstance(enumType, count);
}
else
{
result = new long[count];
}
int i = 0;
foreach (long element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyrightD
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using OpenSim.Framework;
using OMV = OpenMetaverse;
namespace OpenSim.Region.Physics.BulletSPlugin
{
public sealed class BSLinksetCompound : BSLinkset
{
#pragma warning disable 414
private static string LogHeader = "[BULLETSIM LINKSET COMPOUND]";
#pragma warning restore 414
public BSLinksetCompound(BSScene scene, BSPrimLinkable parent)
: base(scene, parent)
{
LinksetImpl = LinksetImplementation.Compound;
}
// ================================================================
// Changing the physical property of the linkset only needs to change the root
public override void SetPhysicalFriction(float friction)
{
if (LinksetRoot.PhysBody.HasPhysicalBody)
m_physicsScene.PE.SetFriction(LinksetRoot.PhysBody, friction);
}
public override void SetPhysicalRestitution(float restitution)
{
if (LinksetRoot.PhysBody.HasPhysicalBody)
m_physicsScene.PE.SetRestitution(LinksetRoot.PhysBody, restitution);
}
public override void SetPhysicalGravity(OMV.Vector3 gravity)
{
if (LinksetRoot.PhysBody.HasPhysicalBody)
m_physicsScene.PE.SetGravity(LinksetRoot.PhysBody, gravity);
}
public override void ComputeAndSetLocalInertia(OMV.Vector3 inertiaFactor, float linksetMass)
{
OMV.Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(LinksetRoot.PhysShape.physShapeInfo, linksetMass);
LinksetRoot.Inertia = inertia * inertiaFactor;
m_physicsScene.PE.SetMassProps(LinksetRoot.PhysBody, linksetMass, LinksetRoot.Inertia);
m_physicsScene.PE.UpdateInertiaTensor(LinksetRoot.PhysBody);
}
public override void SetPhysicalCollisionFlags(CollisionFlags collFlags)
{
if (LinksetRoot.PhysBody.HasPhysicalBody)
m_physicsScene.PE.SetCollisionFlags(LinksetRoot.PhysBody, collFlags);
}
public override void AddToPhysicalCollisionFlags(CollisionFlags collFlags)
{
if (LinksetRoot.PhysBody.HasPhysicalBody)
m_physicsScene.PE.AddToCollisionFlags(LinksetRoot.PhysBody, collFlags);
}
public override void RemoveFromPhysicalCollisionFlags(CollisionFlags collFlags)
{
if (LinksetRoot.PhysBody.HasPhysicalBody)
m_physicsScene.PE.RemoveFromCollisionFlags(LinksetRoot.PhysBody, collFlags);
}
// ================================================================
// When physical properties are changed the linkset needs to recalculate
// its internal properties.
public override void Refresh(BSPrimLinkable requestor)
{
// Something changed so do the rebuilding thing
ScheduleRebuild(requestor);
base.Refresh(requestor);
}
// Schedule a refresh to happen after all the other taint processing.
private void ScheduleRebuild(BSPrimLinkable requestor)
{
// When rebuilding, it is possible to set properties that would normally require a rebuild.
// If already rebuilding, don't request another rebuild.
// If a linkset with just a root prim (simple non-linked prim) don't bother rebuilding.
lock (m_linksetActivityLock)
{
if (!RebuildScheduled && !Rebuilding && HasAnyChildren)
{
InternalScheduleRebuild(requestor);
}
}
}
// Must be called with m_linksetActivityLock or race conditions will haunt you.
private void InternalScheduleRebuild(BSPrimLinkable requestor)
{
DetailLog("{0},BSLinksetCompound.InternalScheduleRebuild,,rebuilding={1},hasChildren={2}",
requestor.LocalID, Rebuilding, HasAnyChildren);
RebuildScheduled = true;
m_physicsScene.PostTaintObject("BSLinksetCompound.ScheduleRebuild", LinksetRoot.LocalID, delegate()
{
if (HasAnyChildren)
{
if (this.AllPartsComplete)
{
RecomputeLinksetCompound();
}
else
{
DetailLog("{0},BSLinksetCompound.InternalScheduleRebuild,,rescheduling because not all children complete",
requestor.LocalID);
InternalScheduleRebuild(requestor);
}
}
RebuildScheduled = false;
});
}
// The object is going dynamic (physical). Do any setup necessary for a dynamic linkset.
// Only the state of the passed object can be modified. The rest of the linkset
// has not yet been fully constructed.
// Return 'true' if any properties updated on the passed object.
// Called at taint-time!
public override bool MakeDynamic(BSPrimLinkable child)
{
bool ret = false;
DetailLog("{0},BSLinksetCompound.MakeDynamic,call,IsRoot={1}", child.LocalID, IsRoot(child));
if (IsRoot(child))
{
// The root is going dynamic. Rebuild the linkset so parts and mass get computed properly.
Refresh(LinksetRoot);
}
return ret;
}
// The object is going static (non-physical). We do not do anything for static linksets.
// Return 'true' if any properties updated on the passed object.
// Called at taint-time!
public override bool MakeStatic(BSPrimLinkable child)
{
bool ret = false;
DetailLog("{0},BSLinksetCompound.MakeStatic,call,IsRoot={1}", child.LocalID, IsRoot(child));
child.ClearDisplacement();
if (IsRoot(child))
{
// Schedule a rebuild to verify that the root shape is set to the real shape.
Refresh(LinksetRoot);
}
return ret;
}
// 'physicalUpdate' is true if these changes came directly from the physics engine. Don't need to rebuild then.
// Called at taint-time.
public override void UpdateProperties(UpdatedProperties whichUpdated, BSPrimLinkable updated)
{
if (!LinksetRoot.IsPhysicallyActive)
{
// No reason to do this physical stuff for static linksets.
DetailLog("{0},BSLinksetCompound.UpdateProperties,notPhysical", LinksetRoot.LocalID);
return;
}
// The user moving a child around requires the rebuilding of the linkset compound shape
// One problem is this happens when a border is crossed -- the simulator implementation
// stores the position into the group which causes the move of the object
// but it also means all the child positions get updated.
// What would cause an unnecessary rebuild so we make sure the linkset is in a
// region before bothering to do a rebuild.
if (!IsRoot(updated) && m_physicsScene.TerrainManager.IsWithinKnownTerrain(LinksetRoot.RawPosition))
{
// If a child of the linkset is updating only the position or rotation, that can be done
// without rebuilding the linkset.
// If a handle for the child can be fetch, we update the child here. If a rebuild was
// scheduled by someone else, the rebuild will just replace this setting.
bool updatedChild = false;
// Anything other than updating position or orientation usually means a physical update
// and that is caused by us updating the object.
if ((whichUpdated & ~(UpdatedProperties.Position | UpdatedProperties.Orientation)) == 0)
{
// Find the physical instance of the child
if (!RebuildScheduled // if rebuilding, let the rebuild do it
&& !LinksetRoot.IsIncomplete // if waiting for assets or whatever, don't change
&& LinksetRoot.PhysShape.HasPhysicalShape // there must be a physical shape assigned
&& m_physicsScene.PE.IsCompound(LinksetRoot.PhysShape.physShapeInfo))
{
// It is possible that the linkset is still under construction and the child is not yet
// inserted into the compound shape. A rebuild of the linkset in a pre-step action will
// build the whole thing with the new position or rotation.
// The index must be checked because Bullet references the child array but does no validity
// checking of the child index passed.
int numLinksetChildren = m_physicsScene.PE.GetNumberOfCompoundChildren(LinksetRoot.PhysShape.physShapeInfo);
if (updated.LinksetChildIndex < numLinksetChildren)
{
BulletShape linksetChildShape = m_physicsScene.PE.GetChildShapeFromCompoundShapeIndex(LinksetRoot.PhysShape.physShapeInfo, updated.LinksetChildIndex);
if (linksetChildShape.HasPhysicalShape)
{
// Found the child shape within the compound shape
m_physicsScene.PE.UpdateChildTransform(LinksetRoot.PhysShape.physShapeInfo, updated.LinksetChildIndex,
updated.RawPosition - LinksetRoot.RawPosition,
updated.RawOrientation * OMV.Quaternion.Inverse(LinksetRoot.RawOrientation),
true /* shouldRecalculateLocalAabb */);
updatedChild = true;
DetailLog("{0},BSLinksetCompound.UpdateProperties,changeChildPosRot,whichUpdated={1},pos={2},rot={3}",
updated.LocalID, whichUpdated, updated.RawPosition, updated.RawOrientation);
}
else // DEBUG DEBUG
{ // DEBUG DEBUG
DetailLog("{0},BSLinksetCompound.UpdateProperties,couldNotUpdateChild,noChildShape,shape={1}",
updated.LocalID, linksetChildShape);
} // DEBUG DEBUG
}
else // DEBUG DEBUG
{ // DEBUG DEBUG
// the child is not yet in the compound shape. This is non-fatal.
DetailLog("{0},BSLinksetCompound.UpdateProperties,couldNotUpdateChild,childNotInCompoundShape,numChildren={1},index={2}",
updated.LocalID, numLinksetChildren, updated.LinksetChildIndex);
} // DEBUG DEBUG
}
else // DEBUG DEBUG
{ // DEBUG DEBUG
DetailLog("{0},BSLinksetCompound.UpdateProperties,couldNotUpdateChild,noBodyOrNotCompound", updated.LocalID);
} // DEBUG DEBUG
if (!updatedChild)
{
// If couldn't do the individual child, the linkset needs a rebuild to incorporate the new child info.
// Note: there are several ways through this code that will not update the child if
// the linkset is being rebuilt. In this case, scheduling a rebuild is a NOOP since
// there will already be a rebuild scheduled.
DetailLog("{0},BSLinksetCompound.UpdateProperties,couldNotUpdateChild.schedulingRebuild,whichUpdated={1}",
updated.LocalID, whichUpdated);
Refresh(updated);
}
}
}
}
// Routine called when rebuilding the body of some member of the linkset.
// If one of the bodies is being changed, the linkset needs rebuilding.
// For instance, a linkset is built and then a mesh asset is read in and the mesh is recreated.
// Returns 'true' of something was actually removed and would need restoring
// Called at taint-time!!
public override bool RemoveDependencies(BSPrimLinkable child)
{
bool ret = false;
DetailLog("{0},BSLinksetCompound.RemoveDependencies,refreshIfChild,rID={1},rBody={2},isRoot={3}",
child.LocalID, LinksetRoot.LocalID, LinksetRoot.PhysBody, IsRoot(child));
Refresh(child);
return ret;
}
// ================================================================
// Add a new child to the linkset.
// Called while LinkActivity is locked.
protected override void AddChildToLinkset(BSPrimLinkable child)
{
if (!HasChild(child))
{
m_children.Add(child, new BSLinkInfo(child));
DetailLog("{0},BSLinksetCompound.AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID);
// Rebuild the compound shape with the new child shape included
Refresh(child);
}
return;
}
// Remove the specified child from the linkset.
// Safe to call even if the child is not really in the linkset.
protected override void RemoveChildFromLinkset(BSPrimLinkable child, bool inTaintTime)
{
child.ClearDisplacement();
if (m_children.Remove(child))
{
DetailLog("{0},BSLinksetCompound.RemoveChildFromLinkset,call,rID={1},rBody={2},cID={3},cBody={4}",
child.LocalID,
LinksetRoot.LocalID, LinksetRoot.PhysBody.AddrString,
child.LocalID, child.PhysBody.AddrString);
// Cause the child's body to be rebuilt and thus restored to normal operation
child.ForceBodyShapeRebuild(inTaintTime);
if (!HasAnyChildren)
{
// The linkset is now empty. The root needs rebuilding.
LinksetRoot.ForceBodyShapeRebuild(inTaintTime);
}
else
{
// Rebuild the compound shape with the child removed
Refresh(LinksetRoot);
}
}
return;
}
// Called before the simulation step to make sure the compound based linkset
// is all initialized.
// Constraint linksets are rebuilt every time.
// Note that this works for rebuilding just the root after a linkset is taken apart.
// Called at taint time!!
private bool UseBulletSimRootOffsetHack = false; // Attempt to have Bullet track the coords of root compound shape
// Number of times to perform rebuilds on broken linkset children. This should only happen when
// a linkset is initially being created and should happen only one or two times at the most.
// This exists to cause a looping problem to be reported while not rebuilding a linkset forever.
private static int LinksetRebuildFailureLoopPrevention = 10;
private void RecomputeLinksetCompound()
{
try
{
Rebuilding = true;
// No matter what is being done, force the root prim's PhysBody and PhysShape to get set
// to what they should be as if the root was not in a linkset.
// Not that bad since we only get into this routine if there are children in the linkset and
// something has been updated/changed.
// Have to do the rebuild before checking for physical because this might be a linkset
// being destructed and going non-physical.
LinksetRoot.ForceBodyShapeRebuild(true);
// There is no reason to build all this physical stuff for a non-physical or empty linkset.
if (!LinksetRoot.IsPhysicallyActive || !HasAnyChildren)
{
DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,notPhysicalOrNoChildren", LinksetRoot.LocalID);
return; // Note the 'finally' clause at the botton which will get executed.
}
// Get a new compound shape to build the linkset shape in.
BSShape linksetShape = BSShapeCompound.GetReference(m_physicsScene);
// Compute a displacement for each component so it is relative to the center-of-mass.
// Bullet presumes an object's origin (relative <0,0,0>) is its center-of-mass
OMV.Vector3 centerOfMassW = ComputeLinksetCenterOfMass();
OMV.Quaternion invRootOrientation = OMV.Quaternion.Normalize(OMV.Quaternion.Inverse(LinksetRoot.RawOrientation));
OMV.Vector3 origRootPosition = LinksetRoot.RawPosition;
// 'centerDisplacementV' is the vehicle relative distance from the simulator root position to the center-of-mass
OMV.Vector3 centerDisplacementV = (centerOfMassW - LinksetRoot.RawPosition) * invRootOrientation;
if (UseBulletSimRootOffsetHack || !BSParam.LinksetOffsetCenterOfMass)
{
// Zero everything if center-of-mass displacement is not being done.
centerDisplacementV = OMV.Vector3.Zero;
LinksetRoot.ClearDisplacement();
}
else
{
// The actual center-of-mass could have been set by the user.
centerDisplacementV = LinksetRoot.SetEffectiveCenterOfMassDisplacement(centerDisplacementV);
}
DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,COM,rootPos={1},com={2},comDisp={3}",
LinksetRoot.LocalID, origRootPosition, centerOfMassW, centerDisplacementV);
// Add the shapes of all the components of the linkset
int memberIndex = 1;
ForEachMember((cPrim) =>
{
if (IsRoot(cPrim))
{
// Root shape is always index zero.
cPrim.LinksetChildIndex = 0;
}
else
{
cPrim.LinksetChildIndex = memberIndex;
memberIndex++;
}
// Get a reference to the shape of the child for adding of that shape to the linkset compound shape
BSShape childShape = cPrim.PhysShape.GetReference(m_physicsScene, cPrim);
// Offset the child shape from the center-of-mass and rotate it to root relative.
OMV.Vector3 offsetPos = (cPrim.RawPosition - origRootPosition) * invRootOrientation - centerDisplacementV;
OMV.Quaternion offsetRot = OMV.Quaternion.Normalize(cPrim.RawOrientation) * invRootOrientation;
// Add the child shape to the compound shape being built
if (childShape.physShapeInfo.HasPhysicalShape)
{
m_physicsScene.PE.AddChildShapeToCompoundShape(linksetShape.physShapeInfo, childShape.physShapeInfo, offsetPos, offsetRot);
DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addChild,indx={1},cShape={2},offPos={3},offRot={4}",
LinksetRoot.LocalID, cPrim.LinksetChildIndex, childShape, offsetPos, offsetRot);
// Since we are borrowing the shape of the child, disable the origional child body
if (!IsRoot(cPrim))
{
m_physicsScene.PE.AddToCollisionFlags(cPrim.PhysBody, CollisionFlags.CF_NO_CONTACT_RESPONSE);
m_physicsScene.PE.ForceActivationState(cPrim.PhysBody, ActivationState.DISABLE_SIMULATION);
// We don't want collisions from the old linkset children.
m_physicsScene.PE.RemoveFromCollisionFlags(cPrim.PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS);
cPrim.PhysBody.collisionType = CollisionType.LinksetChild;
}
}
else
{
// The linkset must be in an intermediate state where all the children have not yet
// been constructed. This sometimes happens on startup when everything is getting
// built and some shapes have to wait for assets to be read in.
// Just skip this linkset for the moment and cause the shape to be rebuilt next tick.
// One problem might be that the shape is broken somehow and it never becomes completely
// available. This might cause the rebuild to happen over and over.
InternalScheduleRebuild(LinksetRoot);
DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addChildWithNoShape,indx={1},cShape={2},offPos={3},offRot={4}",
LinksetRoot.LocalID, cPrim.LinksetChildIndex, childShape, offsetPos, offsetRot);
// Output an annoying warning. It should only happen once but if it keeps coming out,
// the user knows there is something wrong and will report it.
m_physicsScene.Logger.WarnFormat("{0} Linkset rebuild warning. If this happens more than one or two times, please report in Mantis 7191", LogHeader);
m_physicsScene.Logger.WarnFormat("{0} pName={1}, childIdx={2}, shape={3}",
LogHeader, LinksetRoot.Name, cPrim.LinksetChildIndex, childShape);
// This causes the loop to bail on building the rest of this linkset.
// The rebuild operation will fix it up next tick or declare the object unbuildable.
return true;
}
return false; // 'false' says to move onto the next child in the list
});
// Replace the root shape with the built compound shape.
// Object removed and added to world to get collision cache rebuilt for new shape.
LinksetRoot.PhysShape.Dereference(m_physicsScene);
LinksetRoot.PhysShape = linksetShape;
m_physicsScene.PE.RemoveObjectFromWorld(m_physicsScene.World, LinksetRoot.PhysBody);
m_physicsScene.PE.SetCollisionShape(m_physicsScene.World, LinksetRoot.PhysBody, linksetShape.physShapeInfo);
m_physicsScene.PE.AddObjectToWorld(m_physicsScene.World, LinksetRoot.PhysBody);
DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addBody,body={1},shape={2}",
LinksetRoot.LocalID, LinksetRoot.PhysBody, linksetShape);
// With all of the linkset packed into the root prim, it has the mass of everyone.
LinksetMass = ComputeLinksetMass();
LinksetRoot.UpdatePhysicalMassProperties(LinksetMass, true);
if (UseBulletSimRootOffsetHack)
{
// Enable the physical position updator to return the position and rotation of the root shape.
// This enables a feature in the C++ code to return the world coordinates of the first shape in the
// compound shape. This aleviates the need to offset the returned physical position by the
// center-of-mass offset.
// TODO: either debug this feature or remove it.
m_physicsScene.PE.AddToCollisionFlags(LinksetRoot.PhysBody, CollisionFlags.BS_RETURN_ROOT_COMPOUND_SHAPE);
}
}
finally
{
Rebuilding = false;
}
// See that the Aabb surrounds the new shape
m_physicsScene.PE.RecalculateCompoundShapeLocalAabb(LinksetRoot.PhysShape.physShapeInfo);
}
}
}
| |
using UnityEditor;
using UnityEngine;
using System.IO;
using System.Collections.Generic;
[CanEditMultipleObjects, CustomEditor(typeof(MegaShape))]
public class MegaShapeEditor : Editor
{
public bool showcommon = true;
public float outline = 0.0f;
int selected = -1;
Vector3 pm = new Vector3();
Vector3 delta = new Vector3();
bool showsplines = false;
bool showknots = false;
bool showlabels = true;
float ImportScale = 1.0f;
bool hidewire = false;
bool addingknot = false;
Vector3 addpos;
int knum;
int snum;
Bounds bounds;
string lastpath = "";
MegaKnotAnim ma;
public bool showfuncs = false;
public bool export = false;
public MegaAxis xaxis = MegaAxis.X;
public MegaAxis yaxis = MegaAxis.Z;
public float strokewidth = 1.0f;
public Color strokecol = Color.black;
static public Vector3 CursorPos = Vector3.zero;
static public Vector3 CursorSpline = Vector3.zero;
static public Vector3 CursorTangent = Vector3.zero;
static public int CursorKnot = 0;
public delegate bool ParseBinCallbackType(BinaryReader br, string id);
public delegate void ParseClassCallbackType(string classname, BinaryReader br);
public virtual bool Params()
{
MegaShape shape = (MegaShape)target;
bool rebuild = false;
float radius = EditorGUILayout.FloatField("Radius", shape.defRadius);
if ( radius != shape.defRadius )
{
if ( radius < 0.001f )
radius = 0.001f;
shape.defRadius = radius;
rebuild = true;
}
return rebuild;
}
public override void OnInspectorGUI()
{
//undoManager.CheckUndo();
bool buildmesh = false;
bool recalc = false;
MegaShape shape = (MegaShape)target;
EditorGUILayout.BeginHorizontal();
int curve = shape.selcurve;
if ( GUILayout.Button("Add Knot") )
{
if ( shape.splines == null || shape.splines.Count == 0 )
{
MegaSpline spline = new MegaSpline(); // Have methods for these
shape.splines.Add(spline);
}
MegaKnot knot = new MegaKnot();
float per = shape.CursorPercent * 0.01f;
CursorTangent = shape.splines[curve].Interpolate(per + 0.01f, true, ref CursorKnot); //this.GetPositionOnSpline(i) - p;
CursorPos = shape.splines[curve].Interpolate(per, true, ref CursorKnot); //this.GetPositionOnSpline(i) - p;
knot.p = CursorPos;
knot.outvec = (CursorTangent - knot.p);
knot.outvec.Normalize();
knot.outvec *= shape.splines[curve].knots[CursorKnot].seglength * 0.25f;
knot.invec = -knot.outvec;
knot.invec += knot.p;
knot.outvec += knot.p;
knot.twist = shape.splines[curve].knots[CursorKnot].twist;
knot.id = shape.splines[curve].knots[CursorKnot].id;
shape.splines[curve].knots.Insert(CursorKnot + 1, knot);
if ( shape.smoothonaddknot )
shape.AutoCurve(shape.splines[snum]); //, knum, knum + 2);
shape.CalcLength(); //10);
EditorUtility.SetDirty(target);
buildmesh = true;
}
if ( GUILayout.Button("Delete Knot") )
{
if ( selected != -1 )
{
shape.splines[curve].knots.RemoveAt(selected);
selected--;
shape.CalcLength(); //10);
}
EditorUtility.SetDirty(target);
buildmesh = true;
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
if ( GUILayout.Button("Match Handles") )
{
if ( selected != -1 )
{
Vector3 p = shape.splines[curve].knots[selected].p;
Vector3 d = shape.splines[curve].knots[selected].outvec - p;
shape.splines[curve].knots[selected].invec = p - d;
shape.CalcLength(); //10);
}
EditorUtility.SetDirty(target);
buildmesh = true;
}
if ( GUILayout.Button("Load") )
{
LoadShape(ImportScale);
buildmesh = true;
}
if ( GUILayout.Button("Load SXL") )
{
LoadSXL(ImportScale);
buildmesh = true;
}
if ( GUILayout.Button("Load KML") )
{
LoadKML(ImportScale);
buildmesh = true;
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
if ( GUILayout.Button("AutoCurve") )
{
shape.AutoCurve();
EditorUtility.SetDirty(target);
buildmesh = true;
}
if ( GUILayout.Button("Reverse") )
{
shape.Reverse(curve);
//shape.CalcLength();
EditorUtility.SetDirty(target);
buildmesh = true;
}
EditorGUILayout.EndHorizontal();
if ( GUILayout.Button("Centre Shape") )
{
shape.Centre(1.0f, Vector3.one);
}
if ( GUILayout.Button("Apply Scaling") )
{
shape.Scale(shape.transform.localScale);
EditorUtility.SetDirty(target);
shape.transform.localScale = Vector3.one;
buildmesh = true;
}
if ( GUILayout.Button("Import SVG") )
{
LoadSVG(ImportScale);
buildmesh = true;
}
showcommon = EditorGUILayout.Foldout(showcommon, "Common Params");
bool rebuild = false; //Params();
if ( showcommon )
{
shape.CursorPercent = EditorGUILayout.FloatField("Cursor", shape.CursorPercent);
shape.CursorPercent = Mathf.Repeat(shape.CursorPercent, 100.0f);
ImportScale = EditorGUILayout.FloatField("Import Scale", ImportScale);
MegaAxis av = (MegaAxis)EditorGUILayout.EnumPopup("Axis", shape.axis);
if ( av != shape.axis )
{
shape.axis = av;
rebuild = true;
}
if ( shape.splines.Count > 1 )
shape.selcurve = EditorGUILayout.IntSlider("Curve", shape.selcurve, 0, shape.splines.Count - 1);
if ( shape.selcurve < 0 )
shape.selcurve = 0;
if ( shape.selcurve > shape.splines.Count - 1 )
shape.selcurve = shape.splines.Count - 1;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Colors");
shape.col1 = EditorGUILayout.ColorField(shape.col1);
shape.col2 = EditorGUILayout.ColorField(shape.col2);
EditorGUILayout.EndHorizontal();
shape.VecCol = EditorGUILayout.ColorField("Vec Col", shape.VecCol);
shape.KnotSize = EditorGUILayout.FloatField("Knot Size", shape.KnotSize);
shape.stepdist = EditorGUILayout.FloatField("Step Dist", shape.stepdist);
MegaSpline spline = shape.splines[shape.selcurve];
if ( shape.stepdist < 0.01f )
shape.stepdist = 0.01f;
shape.dolateupdate = EditorGUILayout.Toggle("Do Late Update", shape.dolateupdate);
shape.normalizedInterp = EditorGUILayout.Toggle("Normalized Interp", shape.normalizedInterp);
spline.constantSpeed = EditorGUILayout.Toggle("Constant Speed", spline.constantSpeed);
int subdivs = EditorGUILayout.IntField("Calc Subdivs", spline.subdivs);
if ( subdivs < 2 )
subdivs = 2;
if ( subdivs != spline.subdivs )
spline.CalcLength(subdivs);
shape.drawHandles = EditorGUILayout.Toggle("Draw Handles", shape.drawHandles);
shape.drawKnots = EditorGUILayout.Toggle("Draw Knots", shape.drawKnots);
shape.drawTwist = EditorGUILayout.Toggle("Draw Twist", shape.drawTwist);
shape.drawspline = EditorGUILayout.Toggle("Draw Spline", shape.drawspline);
shape.showorigin = EditorGUILayout.Toggle("Origin Handle", shape.showorigin);
shape.lockhandles = EditorGUILayout.Toggle("Lock Handles", shape.lockhandles);
shape.updateondrag = EditorGUILayout.Toggle("Update On Drag", shape.updateondrag);
shape.usesnap = EditorGUILayout.BeginToggleGroup("Use Snap", shape.usesnap);
shape.usesnaphandles = EditorGUILayout.Toggle("Snap Handles", shape.usesnaphandles);
shape.snap = EditorGUILayout.Vector3Field("Snap", shape.snap);
if ( shape.snap.x < 0.0f ) shape.snap.x = 0.0f;
if ( shape.snap.y < 0.0f ) shape.snap.y = 0.0f;
if ( shape.snap.z < 0.0f ) shape.snap.z = 0.0f;
EditorGUILayout.EndToggleGroup();
//shape.autosmooth = EditorGUILayout.Toggle("Auto Smooth", shape.autosmooth);
//shape.smoothness = EditorGUILayout.FloatField("Smoothness", shape.smoothness);
float smoothness = EditorGUILayout.Slider("Smoothness", shape.smoothness, 0.0f, 1.5f);
if ( smoothness != shape.smoothness )
{
shape.smoothness = smoothness;
shape.AutoCurve();
recalc = true;
}
shape.smoothonaddknot = EditorGUILayout.Toggle("Smooth on Add Knot", shape.smoothonaddknot);
shape.handleType = (MegaHandleType)EditorGUILayout.EnumPopup("Handle Type", shape.handleType);
showlabels = EditorGUILayout.Toggle("Labels", showlabels);
bool hidewire1 = EditorGUILayout.Toggle("Hide Wire", hidewire);
if ( hidewire1 != hidewire )
{
hidewire = hidewire1;
EditorUtility.SetSelectedWireframeHidden(shape.GetComponent<Renderer>(), hidewire);
}
shape.animate = EditorGUILayout.Toggle("Animate", shape.animate);
if ( shape.animate )
{
shape.time = EditorGUILayout.FloatField("Time", shape.time);
shape.MaxTime = EditorGUILayout.FloatField("Loop Time", shape.MaxTime);
shape.speed = EditorGUILayout.FloatField("Speed", shape.speed);
shape.LoopMode = (MegaRepeatMode)EditorGUILayout.EnumPopup("Loop Mode", shape.LoopMode);
}
AnimationKeyFrames(shape);
if ( shape.splines.Count > 0 )
{
if ( spline.outlineSpline != -1 )
{
int outlineSpline = EditorGUILayout.IntSlider("Outline Spl", spline.outlineSpline, 0, shape.splines.Count - 1);
float outline = EditorGUILayout.FloatField("Outline", spline.outline);
if ( outline != spline.outline || outlineSpline != spline.outlineSpline )
{
spline.outlineSpline = outlineSpline;
spline.outline = outline;
if ( outlineSpline != shape.selcurve )
{
shape.OutlineSpline(shape.splines[spline.outlineSpline], spline, spline.outline, true);
spline.CalcLength(); //10);
EditorUtility.SetDirty(target);
buildmesh = true;
}
}
}
else
{
outline = EditorGUILayout.FloatField("Outline", outline);
if ( GUILayout.Button("Outline") )
{
shape.OutlineSpline(shape, shape.selcurve, outline, true);
shape.splines[shape.splines.Count - 1].outline = outline;
shape.splines[shape.splines.Count - 1].outlineSpline = shape.selcurve;
shape.selcurve = shape.splines.Count - 1;
EditorUtility.SetDirty(target);
buildmesh = true;
}
}
}
// Mesher
shape.makeMesh = EditorGUILayout.Toggle("Make Mesh", shape.makeMesh);
if ( shape.makeMesh )
{
shape.meshType = (MeshShapeType)EditorGUILayout.EnumPopup("Mesh Type", shape.meshType);
shape.Pivot = EditorGUILayout.Vector3Field("Pivot", shape.Pivot);
shape.CalcTangents = EditorGUILayout.Toggle("Calc Tangents", shape.CalcTangents);
shape.GenUV = EditorGUILayout.Toggle("Gen UV", shape.GenUV);
if ( GUILayout.Button("Build LightMap") )
{
MegaShapeLightMapWindow.Init();
}
EditorGUILayout.BeginVertical("Box");
switch ( shape.meshType )
{
case MeshShapeType.Fill:
shape.DoubleSided = EditorGUILayout.Toggle("Double Sided", shape.DoubleSided);
shape.Height = EditorGUILayout.FloatField("Height", shape.Height);
shape.UseHeightCurve = EditorGUILayout.Toggle("Use Height Crv", shape.UseHeightCurve);
if ( shape.UseHeightCurve )
{
shape.heightCrv = EditorGUILayout.CurveField("Height Curve", shape.heightCrv);
shape.heightOff = EditorGUILayout.Slider("Height Off", shape.heightOff, -1.0f, 1.0f);
}
shape.mat1 = (Material)EditorGUILayout.ObjectField("Top Mat", shape.mat1, typeof(Material), true);
shape.mat2 = (Material)EditorGUILayout.ObjectField("Bot Mat", shape.mat2, typeof(Material), true);
shape.mat3 = (Material)EditorGUILayout.ObjectField("Side Mat", shape.mat3, typeof(Material), true);
shape.PhysUV = EditorGUILayout.Toggle("Physical UV", shape.PhysUV);
shape.UVOffset = EditorGUILayout.Vector2Field("UV Offset", shape.UVOffset);
shape.UVRotate = EditorGUILayout.Vector2Field("UV Rotate", shape.UVRotate);
shape.UVScale = EditorGUILayout.Vector2Field("UV Scale", shape.UVScale);
shape.UVOffset1 = EditorGUILayout.Vector2Field("UV Offset1", shape.UVOffset1);
shape.UVRotate1 = EditorGUILayout.Vector2Field("UV Rotate1", shape.UVRotate1);
shape.UVScale1 = EditorGUILayout.Vector2Field("UV Scale1", shape.UVScale1);
break;
case MeshShapeType.Tube:
shape.TubeStart = EditorGUILayout.Slider("Start", shape.TubeStart, -1.0f, 2.0f);
shape.TubeLength = EditorGUILayout.Slider("Length", shape.TubeLength, 0.0f, 1.0f);
shape.rotate = EditorGUILayout.FloatField("Rotate", shape.rotate);
shape.tsides = EditorGUILayout.IntField("Sides", shape.tsides);
shape.tradius = EditorGUILayout.FloatField("Radius", shape.tradius);
shape.offset = EditorGUILayout.FloatField("Offset", shape.offset);
shape.scaleX = EditorGUILayout.CurveField("Scale X", shape.scaleX);
shape.unlinkScale = EditorGUILayout.BeginToggleGroup("unlink Scale", shape.unlinkScale);
shape.scaleY = EditorGUILayout.CurveField("Scale Y", shape.scaleY);
EditorGUILayout.EndToggleGroup();
shape.strands = EditorGUILayout.IntField("Strands", shape.strands);
if ( shape.strands > 1 )
{
shape.strandRadius = EditorGUILayout.FloatField("Strand Radius", shape.strandRadius);
shape.TwistPerUnit = EditorGUILayout.FloatField("Twist", shape.TwistPerUnit);
shape.startAng = EditorGUILayout.FloatField("Start Twist", shape.startAng);
}
shape.UVOffset = EditorGUILayout.Vector2Field("UV Offset", shape.UVOffset);
shape.uvtilex = EditorGUILayout.FloatField("UV Tile X", shape.uvtilex);
shape.uvtiley = EditorGUILayout.FloatField("UV Tile Y", shape.uvtiley);
shape.cap = EditorGUILayout.Toggle("Cap", shape.cap);
shape.RopeUp = (MegaAxis)EditorGUILayout.EnumPopup("Up", shape.RopeUp);
shape.mat1 = (Material)EditorGUILayout.ObjectField("Mat", shape.mat1, typeof(Material), true);
shape.flipNormals = EditorGUILayout.Toggle("Flip Normals", shape.flipNormals);
break;
case MeshShapeType.Ribbon:
shape.TubeStart = EditorGUILayout.Slider("Start", shape.TubeStart, -1.0f, 2.0f);
shape.TubeLength = EditorGUILayout.Slider("Length", shape.TubeLength, 0.0f, 1.0f);
shape.boxwidth = EditorGUILayout.FloatField("Width", shape.boxwidth);
shape.raxis = (MegaAxis)EditorGUILayout.EnumPopup("Axis", shape.raxis);
shape.rotate = EditorGUILayout.FloatField("Rotate", shape.rotate);
shape.ribsegs = EditorGUILayout.IntField("Segs", shape.ribsegs);
if ( shape.ribsegs < 1 )
shape.ribsegs = 1;
shape.offset = EditorGUILayout.FloatField("Offset", shape.offset);
shape.scaleX = EditorGUILayout.CurveField("Scale X", shape.scaleX);
shape.strands = EditorGUILayout.IntField("Strands", shape.strands);
if ( shape.strands > 1 )
{
shape.strandRadius = EditorGUILayout.FloatField("Strand Radius", shape.strandRadius);
shape.TwistPerUnit = EditorGUILayout.FloatField("Twist", shape.TwistPerUnit);
shape.startAng = EditorGUILayout.FloatField("Start Twist", shape.startAng);
}
shape.UVOffset = EditorGUILayout.Vector2Field("UV Offset", shape.UVOffset);
shape.uvtilex = EditorGUILayout.FloatField("UV Tile X", shape.uvtilex);
shape.uvtiley = EditorGUILayout.FloatField("UV Tile Y", shape.uvtiley);
shape.RopeUp = (MegaAxis)EditorGUILayout.EnumPopup("Up", shape.RopeUp);
shape.mat1 = (Material)EditorGUILayout.ObjectField("Mat", shape.mat1, typeof(Material), true);
shape.flipNormals = EditorGUILayout.Toggle("Flip Normals", shape.flipNormals);
break;
case MeshShapeType.Box:
shape.TubeStart = EditorGUILayout.Slider("Start", shape.TubeStart, -1.0f, 2.0f);
shape.TubeLength = EditorGUILayout.Slider("Length", shape.TubeLength, 0.0f, 1.0f);
shape.rotate = EditorGUILayout.FloatField("Rotate", shape.rotate);
shape.boxwidth = EditorGUILayout.FloatField("Box Width", shape.boxwidth);
shape.boxheight = EditorGUILayout.FloatField("Box Height", shape.boxheight);
shape.offset = EditorGUILayout.FloatField("Offset", shape.offset);
shape.scaleX = EditorGUILayout.CurveField("Scale X", shape.scaleX);
shape.unlinkScale = EditorGUILayout.BeginToggleGroup("unlink Scale", shape.unlinkScale);
shape.scaleY = EditorGUILayout.CurveField("Scale Y", shape.scaleY);
EditorGUILayout.EndToggleGroup();
shape.strands = EditorGUILayout.IntField("Strands", shape.strands);
if ( shape.strands > 1 )
{
shape.tradius = EditorGUILayout.FloatField("Radius", shape.tradius);
shape.TwistPerUnit = EditorGUILayout.FloatField("Twist", shape.TwistPerUnit);
shape.startAng = EditorGUILayout.FloatField("Start Twist", shape.startAng);
}
shape.UVOffset = EditorGUILayout.Vector2Field("UV Offset", shape.UVOffset);
shape.uvtilex = EditorGUILayout.FloatField("UV Tile X", shape.uvtilex);
shape.uvtiley = EditorGUILayout.FloatField("UV Tile Y", shape.uvtiley);
shape.cap = EditorGUILayout.Toggle("Cap", shape.cap);
shape.RopeUp = (MegaAxis)EditorGUILayout.EnumPopup("Up", shape.RopeUp);
shape.mat1 = (Material)EditorGUILayout.ObjectField("Mat", shape.mat1, typeof(Material), true);
shape.flipNormals = EditorGUILayout.Toggle("Flip Normals", shape.flipNormals);
break;
}
if ( shape.strands < 1 )
shape.strands = 1;
EditorGUILayout.EndVertical();
// Conform
shape.conform = EditorGUILayout.BeginToggleGroup("Conform", shape.conform);
GameObject contarget = (GameObject)EditorGUILayout.ObjectField("Target", shape.target, typeof(GameObject), true);
if ( contarget != shape.target )
shape.SetTarget(contarget);
shape.conformAmount = EditorGUILayout.Slider("Amount", shape.conformAmount, 0.0f, 1.0f);
shape.raystartoff = EditorGUILayout.FloatField("Ray Start Off", shape.raystartoff);
shape.conformOffset = EditorGUILayout.FloatField("Conform Offset", shape.conformOffset);
shape.raydist = EditorGUILayout.FloatField("Ray Dist", shape.raydist);
EditorGUILayout.EndToggleGroup();
}
else
{
shape.ClearMesh();
}
showsplines = EditorGUILayout.Foldout(showsplines, "Spline Data");
if ( showsplines )
{
EditorGUILayout.BeginVertical("Box");
if ( shape.splines != null && shape.splines.Count > 0 )
DisplaySpline(shape, shape.splines[shape.selcurve]);
EditorGUILayout.EndVertical();
}
EditorGUILayout.BeginHorizontal();
Color col = GUI.backgroundColor;
GUI.backgroundColor = Color.green;
if ( GUILayout.Button("Add") )
{
// Create a new spline in the shape
MegaSpline spl = MegaSpline.Copy(shape.splines[shape.selcurve]);
shape.splines.Add(spl);
shape.selcurve = shape.splines.Count - 1;
EditorUtility.SetDirty(shape);
buildmesh = true;
}
if ( shape.splines.Count > 1 )
{
GUI.backgroundColor = Color.red;
if ( GUILayout.Button("Delete") )
{
// Delete current spline
shape.splines.RemoveAt(shape.selcurve);
for ( int i = 0; i < shape.splines.Count; i++ )
{
if ( shape.splines[i].outlineSpline == shape.selcurve )
shape.splines[i].outlineSpline = -1;
if ( shape.splines[i].outlineSpline > shape.selcurve )
shape.splines[i].outlineSpline--;
}
shape.selcurve--;
if ( shape.selcurve < 0 )
shape.selcurve = 0;
EditorUtility.SetDirty(shape);
buildmesh = true;
}
}
GUI.backgroundColor = col;
EditorGUILayout.EndHorizontal();
}
if ( !shape.imported )
{
if ( Params() )
{
rebuild = true;
}
}
showfuncs = EditorGUILayout.Foldout(showfuncs, "Extra Functions");
if ( showfuncs )
{
if ( GUILayout.Button("Flatten") )
{
shape.SetHeight(shape.selcurve, 0.0f);
shape.CalcLength();
EditorUtility.SetDirty(target);
}
if ( GUILayout.Button("Remove Twist") )
{
shape.SetTwist(shape.selcurve, 0.0f);
EditorUtility.SetDirty(target);
}
if ( GUILayout.Button("Copy IDS") )
{
shape.CopyIDS(shape.selcurve);
EditorUtility.SetDirty(target);
}
}
export = EditorGUILayout.Foldout(export, "Export Options");
if ( export )
{
xaxis = (MegaAxis)EditorGUILayout.EnumPopup("X Axis", xaxis);
yaxis = (MegaAxis)EditorGUILayout.EnumPopup("Y Axis", yaxis);
strokewidth = EditorGUILayout.FloatField("Stroke Width", strokewidth);
strokecol = EditorGUILayout.ColorField("Stroke Color", strokecol);
if ( GUILayout.Button("Export") )
{
Export(shape);
}
}
if ( recalc )
{
shape.CalcLength(); //10);
shape.BuildMesh();
//MegaLoftLayerSimple[] layers = (MegaLoftLayerSimple[])FindObjectsOfType(typeof(MegaLoftLayerSimple));
//for ( int i = 0; i < layers.Length; i++ )
//{
//layers[i].Notify(shape.splines[shape.selcurve], 0);
//}
EditorUtility.SetDirty(shape);
}
if ( GUI.changed )
{
EditorUtility.SetDirty(target);
buildmesh = true;
}
if ( rebuild )
{
shape.MakeShape();
EditorUtility.SetDirty(target);
buildmesh = true;
}
if ( buildmesh )
{
if ( shape.makeMesh )
{
shape.SetMats();
shape.BuildMesh();
}
}
//undoManager.CheckDirty();
}
void DisplayKnot(MegaShape shape, MegaSpline spline, MegaKnot knot, int i)
{
bool recalc = false;
Vector3 p = EditorGUILayout.Vector3Field("Knot [" + i + "] Pos", knot.p);
delta = p - knot.p;
knot.invec += delta;
knot.outvec += delta;
if ( knot.p != p )
{
recalc = true;
knot.p = p;
}
if ( recalc )
{
shape.CalcLength(); //10);
}
knot.twist = EditorGUILayout.FloatField("Twist", knot.twist);
knot.id = EditorGUILayout.IntField("ID", knot.id);
}
void DisplaySpline(MegaShape shape, MegaSpline spline)
{
bool closed = EditorGUILayout.Toggle("Closed", spline.closed);
if ( closed != spline.closed )
{
spline.closed = closed;
shape.CalcLength(); //10);
EditorUtility.SetDirty(target);
//shape.BuildMesh();
}
spline.reverse = EditorGUILayout.Toggle("Reverse", spline.reverse);
EditorGUILayout.LabelField("Length ", spline.length.ToString("0.000"));
spline.twistmode = (MegaShapeEase)EditorGUILayout.EnumPopup("Twist Mode", spline.twistmode);
showknots = EditorGUILayout.Foldout(showknots, "Knots");
if ( showknots )
{
for ( int i = 0; i < spline.knots.Count; i++ )
{
DisplayKnot(shape, spline, spline.knots[i], i);
//EditorGUILayout.Separator();
}
}
}
static bool editmode = true;
public void OnSceneGUI()
{
MegaShape shape = (MegaShape)target;
bool mouseup = false;
bool recalc = false;
if ( Event.current.type == EventType.KeyDown )
{
if ( Event.current.keyCode == KeyCode.LeftAlt || Event.current.keyCode == KeyCode.RightAlt )
{
editmode = false;
}
}
if ( Event.current.type == EventType.KeyUp )
{
if ( Event.current.keyCode == KeyCode.LeftAlt || Event.current.keyCode == KeyCode.RightAlt )
{
editmode = true;
}
}
if ( !editmode )
{
return;
}
if ( Event.current.type == EventType.mouseUp )
{
mouseup = true;
recalc = true;
if ( addingknot )
{
addingknot = false;
MegaKnot knot = new MegaKnot();
knot.p = addpos;
knot.id = shape.splines[snum].knots[knum].id;
knot.twist = shape.splines[snum].knots[knum].twist;
shape.splines[snum].knots.Insert(knum + 1, knot);
if ( shape.smoothonaddknot )
shape.AutoCurve(shape.splines[snum]); //, knum, knum + 2);
shape.CalcLength(); //10);
EditorUtility.SetDirty(target);
if ( shape.makeMesh )
{
shape.SetMats();
shape.BuildMesh();
}
}
}
Handles.matrix = shape.transform.localToWorldMatrix;
if ( shape.selcurve > shape.splines.Count - 1 )
shape.selcurve = 0;
Vector3 dragplane = Vector3.one;
Color nocol = new Color(0, 0, 0, 0);
bounds.size = Vector3.zero;
Color twistcol = new Color(0.5f, 0.5f, 1.0f, 0.25f);
for ( int s = 0; s < shape.splines.Count; s++ )
{
for ( int p = 0; p < shape.splines[s].knots.Count; p++ )
{
if ( s == shape.selcurve )
{
bounds.Encapsulate(shape.splines[s].knots[p].p);
}
if ( shape.drawKnots && s == shape.selcurve )
{
pm = shape.splines[s].knots[p].p;
if ( showlabels )
{
if ( p == selected && s == shape.selcurve )
{
Handles.color = Color.white;
Handles.Label(pm, " Selected\n" + pm.ToString("0.000"));
}
else
{
Handles.color = shape.KnotCol;
Handles.Label(pm, " " + p);
}
}
Handles.color = nocol;
Vector3 newp = Vector3.zero;
if ( shape.usesnap )
newp = PosHandlesSnap(shape, pm, Quaternion.identity);
else
newp = PosHandles(shape, pm, Quaternion.identity);
if ( newp != pm )
{
MegaUndo.SetSnapshotTarget(shape, "Knot Move");
}
Vector3 dl = Vector3.Scale(newp - pm, dragplane);
shape.splines[s].knots[p].p += dl; //Vector3.Scale(newp - pm, dragplane);
shape.splines[s].knots[p].invec += dl; //delta;
shape.splines[s].knots[p].outvec += dl; //delta;
if ( newp != pm )
{
selected = p;
recalc = true;
}
}
if ( shape.drawHandles && s == shape.selcurve )
{
Handles.color = shape.VecCol;
pm = shape.splines[s].knots[p].p;
Vector3 ip = shape.splines[s].knots[p].invec;
Vector3 op = shape.splines[s].knots[p].outvec;
Handles.DrawLine(pm, ip);
Handles.DrawLine(pm, op);
Handles.color = shape.HandleCol;
Vector3 invec = shape.splines[s].knots[p].invec;
Handles.color = nocol;
Vector3 newinvec = Vector3.zero;
if ( shape.usesnaphandles )
newinvec = PosHandlesSnap(shape, invec, Quaternion.identity);
else
newinvec = PosHandles(shape, invec, Quaternion.identity);
if ( newinvec != invec ) //shape.splines[s].knots[p].invec )
{
MegaUndo.SetSnapshotTarget(shape, "Handle Move");
}
Vector3 dl = Vector3.Scale(newinvec - invec, dragplane);
shape.splines[s].knots[p].invec += dl; //Vector3.Scale(newinvec - invec, dragplane);
if ( invec != newinvec ) //shape.splines[s].knots[p].invec )
{
if ( shape.lockhandles )
{
shape.splines[s].knots[p].outvec -= dl;
}
selected = p;
recalc = true;
}
Vector3 outvec = shape.splines[s].knots[p].outvec;
Vector3 newoutvec = Vector3.zero;
if ( shape.usesnaphandles )
newoutvec = PosHandlesSnap(shape, outvec, Quaternion.identity);
else
newoutvec = PosHandles(shape, outvec, Quaternion.identity);
if ( newoutvec != outvec ) //shape.splines[s].knots[p].outvec )
{
MegaUndo.SetSnapshotTarget(shape, "Handle Move");
}
dl = Vector3.Scale(newoutvec - outvec, dragplane);
shape.splines[s].knots[p].outvec += dl;
if ( outvec != newoutvec ) //shape.splines[s].knots[p].outvec )
{
if ( shape.lockhandles )
{
shape.splines[s].knots[p].invec -= dl;
}
selected = p;
recalc = true;
}
Vector3 hp = shape.splines[s].knots[p].invec;
if ( selected == p )
Handles.Label(hp, " " + p);
hp = shape.splines[s].knots[p].outvec;
if ( selected == p )
Handles.Label(hp, " " + p);
}
// TODO: Draw a wedge to show the twist angle
// Twist handles
if ( shape.drawTwist && s == shape.selcurve )
{
Vector3 np = Vector3.zero;
if ( p == 0 || p < shape.splines[s].knots.Count - 2 )
{
np = shape.splines[s].knots[p].Interpolate(0.002f, shape.splines[s].knots[p + 1]);
np = np - shape.splines[s].knots[p].p;
//np = shape.splines[s].knots[p].outvec; //(0.0f, shape.splines[s].knots[p + 1]);
//Debug.Log("np " + np);
}
else
{
if ( shape.splines[s].closed )
{
np = shape.splines[s].knots[p].Interpolate(0.002f, shape.splines[s].knots[0]);
np = np - shape.splines[s].knots[p].p;
//np = shape.splines[s].knots[p].outvec; //Tangent(0.0f, shape.splines[s].knots[0]);
//Debug.Log("np " + np);
}
else
{
np = shape.splines[s].knots[p - 1].Interpolate(0.998f, shape.splines[s].knots[p]);
np = shape.splines[s].knots[p].p - np;
//np = shape.splines[s].knots[p - 1].outvec; //Tangent(0.9999f, shape.splines[s].knots[p]);
//Debug.Log("np " + np);
}
}
if ( np == Vector3.zero )
np = Vector3.forward;
np = np.normalized;
// np holds the tangent so we can align the arc
Quaternion fwd = Quaternion.LookRotation(np);
Vector3 rg = Vector3.Cross(np, Vector3.up);
//Vector3 up = Vector3.Cross(np, rg);
Handles.color = twistcol;
float twist = shape.splines[s].knots[p].twist;
Handles.DrawSolidArc(shape.splines[s].knots[p].p, np, rg, twist, shape.KnotSize * 0.1f);
Vector3 tang = new Vector3(0.0f, 0.0f, shape.splines[s].knots[p].twist);
Quaternion inrot = fwd * Quaternion.Euler(tang);
//Quaternion rot = Handles.RotationHandle(inrot, shape.splines[s].knots[p].p);
Handles.color = Color.white;
Quaternion rot = Handles.Disc(inrot, shape.splines[s].knots[p].p, np, shape.KnotSize * 0.1f, false, 0.0f);
if ( rot != inrot )
{
tang = rot.eulerAngles;
float diff = (tang.z - shape.splines[s].knots[p].twist);
if ( Mathf.Abs(diff) > 0.0001f )
{
while ( diff > 180.0f )
diff -= 360.0f;
while ( diff < -180.0f )
diff += 360.0f;
shape.splines[s].knots[p].twist += diff;
recalc = true;
}
}
}
// Midpoint add knot code
if ( s == shape.selcurve )
{
if ( p < shape.splines[s].knots.Count - 1 )
{
Handles.color = Color.white;
Vector3 mp = shape.splines[s].knots[p].InterpolateCS(0.5f, shape.splines[s].knots[p + 1]);
Vector3 mp1 = Handles.FreeMoveHandle(mp, Quaternion.identity, shape.KnotSize * 0.01f, Vector3.zero, Handles.CircleCap);
if ( mp1 != mp )
{
if ( !addingknot )
{
addingknot = true;
addpos = mp;
knum = p;
snum = s;
}
}
}
}
}
}
// Draw nearest point (use for adding knot)
Vector3 wcp = CursorPos;
Vector3 newCursorPos = PosHandles(shape, wcp, Quaternion.identity);
if ( newCursorPos != wcp )
{
Vector3 cd = newCursorPos - wcp;
CursorPos += cd;
float calpha = 0.0f;
CursorPos = shape.FindNearestPoint(CursorPos, 5, ref CursorKnot, ref CursorTangent, ref calpha);
shape.CursorPercent = calpha * 100.0f;
}
Handles.Label(CursorPos, "Cursor " + shape.CursorPercent.ToString("0.00") + "% - " + CursorPos);
// Move whole spline handle
if ( shape.showorigin )
{
Handles.Label(bounds.min, "Origin");
Vector3 spos = Handles.PositionHandle(bounds.min, Quaternion.identity);
if ( spos != bounds.min )
{
if ( shape.usesnap )
{
if ( shape.snap.x != 0.0f )
spos.x = (int)(spos.x / shape.snap.x) * shape.snap.x;
if ( shape.snap.y != 0.0f )
spos.y = (int)(spos.y / shape.snap.y) * shape.snap.y;
if ( shape.snap.z != 0.0f )
spos.z = (int)(spos.z / shape.snap.z) * shape.snap.z;
}
// Move the spline
shape.MoveSpline(spos - bounds.min, shape.selcurve, false);
recalc = true;
}
}
if ( recalc )
{
shape.CalcLength(); //10);
if ( shape.updateondrag || (!shape.updateondrag && mouseup) )
{
shape.BuildMesh();
//MegaLoftLayerSimple[] layers = (MegaLoftLayerSimple[])FindObjectsOfType(typeof(MegaLoftLayerSimple));
//for ( int i = 0; i < layers.Length; i++ )
//{
//layers[i].Notify(shape.splines[shape.selcurve], 0);
//}
EditorUtility.SetDirty(shape);
}
}
Handles.matrix = Matrix4x4.identity;
//undoManager.CheckDirty(target);
// This is wrong gui not changing here
if ( GUI.changed )
{
MegaUndo.CreateSnapshot();
MegaUndo.RegisterSnapshot();
}
MegaUndo.ClearSnapshotTarget();
}
Vector3 PosHandlesSnap(MegaShape shape, Vector3 pos, Quaternion q)
{
switch ( shape.handleType )
{
case MegaHandleType.Position:
pos = Handles.PositionHandle(pos, q);
break;
case MegaHandleType.Free:
pos = Handles.FreeMoveHandle(pos, q, shape.KnotSize * 0.01f, Vector3.zero, Handles.CircleCap);
break;
}
if ( shape.usesnap )
{
if ( shape.snap.x != 0.0f )
pos.x = (int)(pos.x / shape.snap.x) * shape.snap.x;
if ( shape.snap.y != 0.0f )
pos.y = (int)(pos.y / shape.snap.y) * shape.snap.y;
if ( shape.snap.z != 0.0f )
pos.z = (int)(pos.z / shape.snap.z) * shape.snap.z;
}
return pos;
}
Vector3 PosHandles(MegaShape shape, Vector3 pos, Quaternion q)
{
switch ( shape.handleType )
{
case MegaHandleType.Position:
pos = Handles.PositionHandle(pos, q);
break;
case MegaHandleType.Free:
pos = Handles.FreeMoveHandle(pos, q, shape.KnotSize * 0.01f, Vector3.zero, Handles.CircleCap);
break;
}
return pos;
}
#if UNITY_5_1 || UNITY_5_2 || UNITY_5_3 || UNITY_5_4 || UNITY_5_5 || UNITY_6
[DrawGizmo(GizmoType.NotInSelectionHierarchy | GizmoType.Pickable | GizmoType.InSelectionHierarchy)]
#else
[DrawGizmo(GizmoType.NotInSelectionHierarchy | GizmoType.Pickable | GizmoType.InSelectionHierarchy)]
#endif
static void RenderGizmo(MegaShape shape, GizmoType gizmoType)
{
if ( (gizmoType & GizmoType.Active) != 0 && Selection.activeObject == shape.gameObject )
{
if ( shape.splines == null || shape.splines.Count == 0 )
return;
DrawGizmos(shape, new Color(1.0f, 1.0f, 1.0f, 1.0f));
if ( shape.splines[shape.selcurve].knots.Count > 1 )
{
Color col = Color.yellow;
col.a = 0.5f;
Gizmos.color = col; //Color.yellow;
CursorPos = shape.InterpCurve3D(shape.selcurve, shape.CursorPercent * 0.01f, true);
Gizmos.DrawSphere(shape.transform.TransformPoint(CursorPos), shape.KnotSize * 0.01f);
Handles.color = Color.white;
if ( shape.handleType == MegaHandleType.Free && editmode )
{
int s = shape.selcurve;
{
for ( int p = 0; p < shape.splines[s].knots.Count; p++ )
{
if ( shape.drawKnots ) //&& s == shape.selcurve )
{
Gizmos.color = Color.green;
Gizmos.DrawSphere(shape.transform.TransformPoint(shape.splines[s].knots[p].p), shape.KnotSize * 0.01f);
}
if ( shape.drawHandles )
{
Gizmos.color = Color.red;
Gizmos.DrawSphere(shape.transform.TransformPoint(shape.splines[s].knots[p].invec), shape.KnotSize * 0.01f);
Gizmos.DrawSphere(shape.transform.TransformPoint(shape.splines[s].knots[p].outvec), shape.KnotSize * 0.01f);
}
}
}
}
}
}
else
DrawGizmos(shape, new Color(1.0f, 1.0f, 1.0f, 0.25f));
if ( Camera.current )
{
Vector3 vis = Camera.current.WorldToScreenPoint(shape.transform.position);
if ( vis.z > 0.0f )
{
Gizmos.DrawIcon(shape.transform.position, "MegaSpherify icon.png", false);
Handles.Label(shape.transform.position, " " + shape.name);
}
}
}
// Dont want this in here, want in editor
// If we go over a knot then should draw to the knot
static void DrawGizmos(MegaShape shape, Color modcol1)
{
if ( ((1 << shape.gameObject.layer) & Camera.current.cullingMask) == 0 )
return;
if ( !shape.drawspline )
return;
Matrix4x4 tm = shape.transform.localToWorldMatrix;
for ( int s = 0; s < shape.splines.Count; s++ )
{
if ( shape.splines[s].knots.Count > 1 )
{
float ldist = shape.stepdist * 0.1f;
if ( ldist < 0.01f )
ldist = 0.01f;
Color modcol = modcol1;
if ( s != shape.selcurve && modcol1.a == 1.0f )
modcol.a *= 0.5f;
if ( shape.splines[s].length / ldist > 500.0f )
ldist = shape.splines[s].length / 500.0f;
float ds = shape.splines[s].length / (shape.splines[s].length / ldist);
if ( ds > shape.splines[s].length )
ds = shape.splines[s].length;
int c = 0;
int k = -1;
int lk = -1;
Vector3 first = shape.splines[s].Interpolate(0.0f, shape.normalizedInterp, ref lk);
for ( float dist = ds; dist < shape.splines[s].length; dist += ds )
{
float alpha = dist / shape.splines[s].length;
Vector3 pos = shape.splines[s].Interpolate(alpha, shape.normalizedInterp, ref k);
if ( (c & 1) == 1 )
Gizmos.color = shape.col1 * modcol;
else
Gizmos.color = shape.col2 * modcol;
if ( k != lk )
{
for ( lk = lk + 1; lk <= k; lk++ )
{
Gizmos.DrawLine(tm.MultiplyPoint(first), tm.MultiplyPoint(shape.splines[s].knots[lk].p));
first = shape.splines[s].knots[lk].p;
}
}
lk = k;
Gizmos.DrawLine(tm.MultiplyPoint(first), tm.MultiplyPoint(pos));
c++;
first = pos;
}
if ( (c & 1) == 1 )
Gizmos.color = shape.col1 * modcol;
else
Gizmos.color = shape.col2 * modcol;
Vector3 lastpos;
if ( shape.splines[s].closed )
lastpos = shape.splines[s].Interpolate(0.0f, shape.normalizedInterp, ref k);
else
lastpos = shape.splines[s].Interpolate(1.0f, shape.normalizedInterp, ref k);
Gizmos.DrawLine(tm.MultiplyPoint(first), tm.MultiplyPoint(lastpos));
}
}
}
void LoadSVG(float scale)
{
MegaShape ms = (MegaShape)target;
string filename = EditorUtility.OpenFilePanel("SVG File", lastpath, "svg");
if ( filename == null || filename.Length < 1 )
return;
lastpath = filename;
bool opt = true;
if ( ms.splines != null && ms.splines.Count > 0 )
opt = EditorUtility.DisplayDialog("Spline Import Option", "Splines already present, do you want to 'Add' or 'Replace' splines with this file?", "Add", "Replace");
int startspline = 0;
if ( opt )
startspline = ms.splines.Count;
StreamReader streamReader = new StreamReader(filename);
string text = streamReader.ReadToEnd();
streamReader.Close();
MegaShapeSVG svg = new MegaShapeSVG();
svg.importData(text, ms, scale, opt, startspline); //.splines[0]);
ms.imported = true;
}
void LoadSXL(float scale)
{
MegaShape ms = (MegaShape)target;
string filename = EditorUtility.OpenFilePanel("SXL File", lastpath, "sxl");
if ( filename == null || filename.Length < 1 )
return;
lastpath = filename;
bool opt = true;
if ( ms.splines != null && ms.splines.Count > 0 )
opt = EditorUtility.DisplayDialog("Spline Import Option", "Splines already present, do you want to 'Add' or 'Replace' splines with this file?", "Add", "Replace");
int startspline = 0;
if ( opt )
startspline = ms.splines.Count;
StreamReader streamReader = new StreamReader(filename);
string text = streamReader.ReadToEnd();
streamReader.Close();
MegaShapeSXL sxl = new MegaShapeSXL();
sxl.importData(text, ms, scale, opt, startspline); //.splines[0]);
ms.imported = true;
}
void LoadKML(float scale)
{
MegaShape ms = (MegaShape)target;
string filename = EditorUtility.OpenFilePanel("KML File", lastpath, "kml");
if ( filename == null || filename.Length < 1 )
return;
lastpath = filename;
//bool opt = true;
//if ( ms.splines != null && ms.splines.Count > 0 )
// opt = EditorUtility.DisplayDialog("Spline Import Option", "Splines already present, do you want to 'Add' or 'Replace' splines with this file?", "Add", "Replace");
//int startspline = 0;
//if ( opt )
// startspline = ms.splines.Count;
MegaKML kml = new MegaKML();
kml.KMLDecode(filename);
Vector3[] points = kml.GetPoints(ImportScale);
ms.BuildSpline(ms.selcurve, points, true);
}
void LoadShape(float scale)
{
MegaShape ms = (MegaShape)target;
string filename = EditorUtility.OpenFilePanel("Shape File", lastpath, "spl");
if ( filename == null || filename.Length < 1 )
return;
lastpath = filename;
// Clear what we have
bool opt = true;
if ( ms.splines != null && ms.splines.Count > 0 )
opt = EditorUtility.DisplayDialog("Spline Import Option", "Splines already present, do you want to 'Add' or 'Replace' splines with this file?", "Add", "Replace");
int startspline = 0;
if ( opt )
startspline = ms.splines.Count;
else
ms.splines.Clear();
ParseFile(filename, ShapeCallback);
ms.Scale(scale, startspline);
ms.MaxTime = 0.0f;
for ( int s = 0; s < ms.splines.Count; s++ )
{
if ( ms.splines[s].animations != null )
{
for ( int a = 0; a < ms.splines[s].animations.Count; a++ )
{
MegaControl con = ms.splines[s].animations[a].con;
if ( con != null )
{
float t = con.Times[con.Times.Length - 1];
if ( t > ms.MaxTime )
ms.MaxTime = t;
}
}
}
}
ms.imported = true;
}
public void ShapeCallback(string classname, BinaryReader br)
{
switch ( classname )
{
case "Shape": LoadShape(br); break;
}
}
public void LoadShape(BinaryReader br)
{
MegaParse.Parse(br, ParseShape);
}
public void ParseFile(string assetpath, ParseClassCallbackType cb)
{
FileStream fs = new FileStream(assetpath, FileMode.Open, FileAccess.Read, System.IO.FileShare.Read);
BinaryReader br = new BinaryReader(fs);
bool processing = true;
while ( processing )
{
string classname = MegaParse.ReadString(br);
if ( classname == "Done" )
break;
int chunkoff = br.ReadInt32();
long fpos = fs.Position;
cb(classname, br);
fs.Position = fpos + chunkoff;
}
br.Close();
}
static public Vector3 ReadP3(BinaryReader br)
{
Vector3 p = Vector3.zero;
p.x = br.ReadSingle();
p.y = br.ReadSingle();
p.z = br.ReadSingle();
return p;
}
bool SplineParse(BinaryReader br, string cid)
{
MegaShape ms = (MegaShape)target;
MegaSpline ps = ms.splines[ms.splines.Count - 1];
switch ( cid )
{
case "Transform":
Vector3 pos = ReadP3(br);
Vector3 rot = ReadP3(br);
Vector3 scl = ReadP3(br);
rot.y = -rot.y;
ms.transform.position = pos;
ms.transform.rotation = Quaternion.Euler(rot * Mathf.Rad2Deg);
ms.transform.localScale = scl;
break;
case "Flags":
int count = br.ReadInt32();
ps.closed = (br.ReadInt32() == 1);
count = br.ReadInt32();
ps.knots = new List<MegaKnot>(count);
ps.length = 0.0f;
break;
case "Knots":
for ( int i = 0; i < ps.knots.Capacity; i++ )
{
MegaKnot pk = new MegaKnot();
pk.p = ReadP3(br);
pk.invec = ReadP3(br);
pk.outvec = ReadP3(br);
pk.seglength = br.ReadSingle();
ps.length += pk.seglength;
pk.length = ps.length;
ps.knots.Add(pk);
}
break;
}
return true;
}
bool AnimParse(BinaryReader br, string cid)
{
MegaShape ms = (MegaShape)target;
switch ( cid )
{
case "V":
int v = br.ReadInt32();
ma = new MegaKnotAnim();
int s = ms.GetSpline(v, ref ma); //.s, ref ma.p, ref ma.t);
if ( ms.splines[s].animations == null )
ms.splines[s].animations = new List<MegaKnotAnim>();
ms.splines[s].animations.Add(ma);
break;
case "Anim":
ma.con = MegaParseBezVector3Control.LoadBezVector3KeyControl(br);
break;
}
return true;
}
bool ParseShape(BinaryReader br, string cid)
{
MegaShape ms = (MegaShape)target;
switch ( cid )
{
case "Num":
int count = br.ReadInt32();
ms.splines = new List<MegaSpline>(count);
break;
case "Spline":
MegaSpline spl = new MegaSpline();
ms.splines.Add(spl);
MegaParse.Parse(br, SplineParse);
break;
case "Anim":
MegaParse.Parse(br, AnimParse);
break;
}
return true;
}
[MenuItem("GameObject/Create MegaShape Prefab")]
static void DoCreateSimplePrefabNew()
{
if ( Selection.activeGameObject != null )
{
if ( !Directory.Exists("Assets/MegaPrefabs") )
{
AssetDatabase.CreateFolder("Assets", "MegaPrefabs");
//string newFolderPath = AssetDatabase.GUIDToAssetPath(guid);
//Debug.Log("folder path " + newFolderPath);
}
GameObject obj = Selection.activeGameObject;
GameObject prefab = PrefabUtility.CreatePrefab("Assets/MegaPrefabs/" + Selection.activeGameObject.name + ".prefab", Selection.activeGameObject);
MeshFilter mf = obj.GetComponent<MeshFilter>();
if ( mf )
{
MeshFilter newmf = prefab.GetComponent<MeshFilter>();
Mesh mesh = CloneMesh(mf.sharedMesh);
mesh.name = obj.name + " copy";
AssetDatabase.AddObjectToAsset(mesh, prefab);
//AssetDatabase.CreateAsset(mesh, "Assets/MegaPrefabs/" + Selection.activeGameObject.name + ".asset");
newmf.sharedMesh = mesh;
MeshCollider mc = prefab.GetComponent<MeshCollider>();
if ( mc )
{
mc.sharedMesh = null;
mc.sharedMesh = mesh;
}
}
//MegaShapeLoft oldloft = obj.GetComponent<MegaShapeLoft>();
//MegaShapeLoft loft = prefab.GetComponent<MegaShapeLoft>();
//if ( loft )
//{
//for ( int i = 0; i < loft.Layers.Length; i++ )
//loft.Layers[i].CopyLayer(oldloft.Layers[i]);
//}
//PrefabUtility.DisconnectPrefabInstance(prefab);
}
}
static Mesh CloneMesh(Mesh mesh)
{
Mesh clonemesh = new Mesh();
clonemesh.vertices = mesh.vertices;
#if UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5
clonemesh.uv2 = mesh.uv2;
#else
clonemesh.uv1 = mesh.uv1;
clonemesh.uv2 = mesh.uv2;
#endif
clonemesh.uv = mesh.uv;
clonemesh.normals = mesh.normals;
clonemesh.tangents = mesh.tangents;
clonemesh.colors = mesh.colors;
clonemesh.subMeshCount = mesh.subMeshCount;
for ( int s = 0; s < mesh.subMeshCount; s++ )
clonemesh.SetTriangles(mesh.GetTriangles(s), s);
clonemesh.boneWeights = mesh.boneWeights;
clonemesh.bindposes = mesh.bindposes;
clonemesh.name = mesh.name + "_copy";
clonemesh.RecalculateBounds();
return clonemesh;
}
// Animation keyframe stuff
// Need system to grab state of curve
void AnimationKeyFrames(MegaShape shape)
{
MegaSpline spline = shape.splines[shape.selcurve];
shape.showanimations = EditorGUILayout.Foldout(shape.showanimations, "Animations");
if ( shape.showanimations )
{
shape.keytime = EditorGUILayout.FloatField("Key Time", shape.keytime);
if ( shape.keytime < 0.0f )
shape.keytime = 0.0f;
spline.splineanim.Enabled = EditorGUILayout.BeginToggleGroup("Enabled", spline.splineanim.Enabled);
EditorGUILayout.BeginHorizontal();
//if ( spline.splineanim == null )
//{
//}
//else
{
//if ( GUILayout.Button("Create") )
//{
//spline.splineanim = new MegaSplineAnim();
//spline.splineanim.Init(spline);
//}
if ( GUILayout.Button("Add Key") )
{
AddKeyFrame(shape, shape.keytime);
}
if ( GUILayout.Button("Clear") )
{
ClearAnim(shape);
}
//if ( GUILayout.Button("Delete") )
//{
// spline.splineanim = null;
//}
}
EditorGUILayout.EndHorizontal();
//if ( spline.splineanim == null )
// return;
// Need to show each keyframe
if ( spline.splineanim != null )
{
//EditorGUILayout.LabelField("Frames " + spline.splineanim.knots[0].)
int nk = spline.splineanim.NumKeys();
float mt = 0.0f;
for ( int i = 0; i < nk; i++ )
{
EditorGUILayout.BeginHorizontal();
mt = spline.splineanim.GetKeyTime(i);
EditorGUILayout.LabelField("" + i, GUILayout.MaxWidth(20)); //" + " Time: " + mt);
float t = EditorGUILayout.FloatField("", mt, GUILayout.MaxWidth(100));
if ( t != mt )
spline.splineanim.SetKeyTime(spline, i, t);
if ( GUILayout.Button("Delete", GUILayout.MaxWidth(50)) )
spline.splineanim.RemoveKey(i);
if ( GUILayout.Button("Update", GUILayout.MaxWidth(50)) )
spline.splineanim.UpdateKey(spline, i);
if ( GUILayout.Button("Get", GUILayout.MaxWidth(50)) )
{
spline.splineanim.GetKey(spline, i);
EditorUtility.SetDirty(target);
}
EditorGUILayout.EndHorizontal();
}
shape.MaxTime = mt;
float at = EditorGUILayout.Slider("T", shape.testtime, 0.0f, mt);
if ( at != shape.testtime )
{
shape.testtime = at;
if ( !shape.animate )
{
for ( int s = 0; s < shape.splines.Count; s++ )
{
if ( shape.splines[s].splineanim != null && shape.splines[s].splineanim.Enabled )
{
shape.splines[s].splineanim.GetState1(shape.splines[s], at);
shape.splines[s].CalcLength(); //(10); // could use less here
}
}
}
}
}
EditorGUILayout.EndToggleGroup();
}
}
void ClearAnim(MegaShape shape)
{
MegaSpline spline = shape.splines[shape.selcurve];
if ( spline.splineanim != null )
{
spline.splineanim.Init(spline);
}
}
void AddKeyFrame(MegaShape shape, float t)
{
MegaSpline spline = shape.splines[shape.selcurve];
//if ( spline.splineanim == null )
//{
//Debug.Log("1");
//MegaSplineAnim sa = new MegaSplineAnim();
//sa.Init(spline);
//spline.splineanim = sa;
//}
//else
//{
spline.splineanim.AddState(spline, t);
//}
}
void Export(MegaShape shape)
{
string filename = EditorUtility.SaveFilePanel("Export Shape to SVG", "", shape.name, ".svg");
if ( filename.Length > 0 )
{
string data = MegaShapeSVG.Export(shape, (int)xaxis, (int)yaxis, strokewidth, strokecol);
System.IO.File.WriteAllText(filename, data);
}
}
}
| |
#region Licence
/****************************************************************************
Copyright 1999-2015 Vincent J. Jacquet. All rights reserved.
Permission is granted to anyone to use this software for any purpose on
any computer system, and to alter it and redistribute it, subject
to the following restrictions:
1. The author is not responsible for the consequences of use of this
software, no matter how awful, even if they arise from flaws in it.
2. The origin of this software must not be misrepresented, either by
explicit claim or by omission. Since few users ever read sources,
credits must appear in the documentation.
3. Altered versions must be plainly marked as such, and must not be
misrepresented as being the original software. Since few users
ever read sources, credits must appear in the documentation.
4. This notice may not be removed or altered.
****************************************************************************/
#endregion
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Resources;
using System.Windows.Forms;
namespace WmcSoft.Windows.Forms.Design
{
/// <summary>
///
/// </summary>
public class Border3DSideEditor : UITypeEditor
{
private class Border3DSideUI : Control
{
public Border3DSideUI(Border3DSideEditor editor) {
this.editor = editor;
this.InitializeComponent();
this.tabOrder = new Border3DSideEditor.Border3DSideUI.SpringControl[5] { this.left, this.top, this.right, this.bottom, this.middle };
}
public void End() {
this.edSvc = null;
this.value = null;
}
public virtual Border3DSide GetSelectedBorder3DSide() {
Border3DSide sides = Border3DSide.All;
if (!this.left.GetSolid()) {
sides &= ~Border3DSide.Left;
}
if (!this.top.GetSolid()) {
sides &= ~Border3DSide.Top;
}
if (!this.bottom.GetSolid()) {
sides &= ~Border3DSide.Bottom;
}
if (!this.right.GetSolid()) {
sides &= ~Border3DSide.Right;
}
if (!this.middle.GetSolid()) {
sides &= ~Border3DSide.Middle;
}
//if (((int)sides) == 0) {
// sides = Border3DSide.All;
// this.left.SetSolid(true);
// this.top.SetSolid(true);
// this.bottom.SetSolid(true);
// this.right.SetSolid(true);
// this.middle.SetSolid(true);
//}
return sides;
}
void InitializeComponent() {
int width = 2 * SystemInformation.Border3DSize.Width;
int height = 2 * SystemInformation.Border3DSize.Height;
this.left = new Border3DSideEditor.Border3DSideUI.SpringControl(this);
this.right = new Border3DSideEditor.Border3DSideUI.SpringControl(this);
this.top = new Border3DSideEditor.Border3DSideUI.SpringControl(this);
this.bottom = new Border3DSideEditor.Border3DSideUI.SpringControl(this);
this.middle = new Border3DSideEditor.Border3DSideUI.SpringControl(this);
base.SetBounds(0, 0, 90, 90);
//
// middle
//
this.middle.Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Top;
this.middle.Location = new Point(30, 30);
this.middle.Size = new Size(30, 30);
this.middle.TabIndex = 4;
this.middle.TabStop = true;
//
// right
//
this.right.Anchor = AnchorStyles.Right;
this.right.Location = new Point(80 - width, 10 + height);
this.right.Size = new Size(10, 70 - 2 * height);
this.right.TabIndex = 2;
this.right.TabStop = true;
//
// left
//
this.left.Anchor = AnchorStyles.Left;
this.left.Location = new Point(width, 10 + height);
this.left.Size = new Size(10, 70 - 2 * height);
this.left.TabIndex = 0;
this.left.TabStop = true;
//
// top
//
this.top.Anchor = AnchorStyles.Top;
this.top.Location = new Point(10 + width, height);
this.top.Size = new Size(70 - 2 * width, 10);
this.top.TabIndex = 1;
this.top.TabStop = true;
//
// bottom
//
this.bottom.Anchor = AnchorStyles.Bottom;
this.bottom.Location = new Point(10 + width, 80 - height);
this.bottom.Size = new Size(70 - 2 * width, 10);
this.bottom.TabIndex = 3;
this.bottom.TabStop = true;
this.BackColor = SystemColors.Window;
this.ForeColor = SystemColors.WindowText;
base.TabStop = false;
//base.Controls.Add(this.container);
base.Controls.AddRange(new Control[5] { this.top, this.left, this.bottom, this.right, this.middle });
ResourceManager rm = new ResourceManager(typeof(Border3DSideEditor));
this.middle.AccessibleName = rm.GetString("Border3DSide.Middle.AccessibleName");
this.right.AccessibleName = rm.GetString("Border3DSide.Right.AccessibleName");
this.left.AccessibleName = rm.GetString("Border3DSide.Left.AccessibleName");
this.top.AccessibleName = rm.GetString("Border3DSide.Top.AccessibleName");
this.bottom.AccessibleName = rm.GetString("Border3DSide.Bottom.AccessibleName");
rm.ReleaseAllResources();
}
protected override void OnPaint(PaintEventArgs e) {
Rectangle rectangle = base.ClientRectangle;
ControlPaint.DrawBorder3D(e.Graphics, rectangle, Border3DStyle.Sunken);
}
protected override void OnGotFocus(EventArgs e) {
base.OnGotFocus(e);
this.top.Focus();
}
private void SetValue() {
this.value = this.GetSelectedBorder3DSide();
}
public void Start(System.Windows.Forms.Design.IWindowsFormsEditorService edSvc, object value) {
this.edSvc = edSvc;
this.value = value;
if (value is Border3DSide) {
this.left.SetSolid((((Border3DSide)value) & Border3DSide.Left) == Border3DSide.Left);
this.top.SetSolid((((Border3DSide)value) & Border3DSide.Top) == Border3DSide.Top);
this.bottom.SetSolid((((Border3DSide)value) & Border3DSide.Bottom) == Border3DSide.Bottom);
this.right.SetSolid((((Border3DSide)value) & Border3DSide.Right) == Border3DSide.Right);
this.middle.SetSolid((((Border3DSide)value) & Border3DSide.Middle) == Border3DSide.Middle);
this.oldBorders = (Border3DSide)value;
} else {
this.oldBorders = Border3DSide.All;
}
}
private void Teardown(bool save) {
if (!save) {
this.value = this.oldBorders;
}
this.edSvc.CloseDropDown();
}
public object Value {
get { return this.value; }
}
private SpringControl bottom;
//private ContainerPlaceholder container;
private Border3DSideEditor editor;
private System.Windows.Forms.Design.IWindowsFormsEditorService edSvc;
private SpringControl left;
private Border3DSide oldBorders;
private SpringControl right;
private SpringControl top;
private SpringControl middle;
private SpringControl[] tabOrder;
private object value;
// Nested Types
private class SpringControl : Control
{
// Methods
public SpringControl(Border3DSideEditor.Border3DSideUI picker) {
if (picker == null) {
throw new ArgumentNullException("picker");
}
this.picker = picker;
base.TabStop = true;
}
protected override AccessibleObject CreateAccessibilityInstance() {
return new Border3DSideEditor.Border3DSideUI.SpringControl.SpringControlAccessibleObject(this);
}
public virtual bool GetSolid() {
return this.solid;
}
protected override void OnGotFocus(EventArgs e) {
if (!this.focused) {
this.focused = true;
base.Invalidate();
}
base.OnGotFocus(e);
}
protected override void OnLostFocus(EventArgs e) {
if (this.focused) {
this.focused = false;
base.Invalidate();
}
base.OnLostFocus(e);
}
protected override void OnMouseDown(MouseEventArgs e) {
this.SetSolid(!this.solid);
base.Focus();
}
protected override void OnPaint(PaintEventArgs e) {
Rectangle rectangle = base.ClientRectangle;
if (this.solid) {
e.Graphics.FillRectangle(SystemBrushes.ControlDark, rectangle);
e.Graphics.DrawRectangle(SystemPens.WindowFrame, rectangle.X, rectangle.Y, (int)(rectangle.Width - 1), (int)(rectangle.Height - 1));
} else {
ControlPaint.DrawFocusRectangle(e.Graphics, rectangle);
}
if (this.focused) {
rectangle.Inflate(-2, -2);
ControlPaint.DrawFocusRectangle(e.Graphics, rectangle);
}
}
protected override bool ProcessDialogChar(char charCode) {
if (charCode == ' ') {
this.SetSolid(!this.solid);
return true;
}
return base.ProcessDialogChar(charCode);
}
protected override bool ProcessDialogKey(Keys keyData) {
if (((keyData & Keys.KeyCode) == Keys.Return) && ((keyData & (Keys.Alt | Keys.Control)) == Keys.None)) {
this.picker.Teardown(true);
return true;
}
if (((keyData & Keys.KeyCode) == Keys.Escape) && ((keyData & (Keys.Alt | Keys.Control)) == Keys.None)) {
this.picker.Teardown(false);
return true;
}
if (((keyData & Keys.KeyCode) != Keys.Tab) || ((keyData & (Keys.Alt | Keys.Control)) != Keys.None)) {
return base.ProcessDialogKey(keyData);
}
for (int i = 0; i < this.picker.tabOrder.Length; ++i) {
if (this.picker.tabOrder[i] == this) {
i += (((keyData & Keys.Shift) == Keys.None) ? 1 : -1);
i = (i < 0) ? (i + this.picker.tabOrder.Length) : (i % this.picker.tabOrder.Length);
this.picker.tabOrder[i].Focus();
break;
}
}
return true;
}
public virtual void SetSolid(bool value) {
if (this.solid != value) {
this.solid = value;
this.picker.SetValue();
base.Invalidate();
}
}
// Fields
internal bool focused;
internal bool solid;
private Border3DSideEditor.Border3DSideUI picker;
// Nested Types
private class SpringControlAccessibleObject : Control.ControlAccessibleObject
{
// Methods
public SpringControlAccessibleObject(Border3DSideEditor.Border3DSideUI.SpringControl owner)
: base(owner) {
}
// Properties
public override AccessibleStates State {
get {
AccessibleStates states = base.State;
if (((Border3DSideEditor.Border3DSideUI.SpringControl)base.Owner).GetSolid()) {
states |= AccessibleStates.Selected;
}
return states;
}
}
}
}
}
/// <summary>
///
/// </summary>
public Border3DSideEditor() {
}
/// <summary>
///
/// </summary>
/// <param name="context"></param>
/// <param name="provider"></param>
/// <param name="value"></param>
/// <returns></returns>
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) {
if (provider != null) {
var service = (System.Windows.Forms.Design.IWindowsFormsEditorService)provider.GetService(typeof(System.Windows.Forms.Design.IWindowsFormsEditorService));
if (service == null) {
return value;
}
using (var ui = new Border3DSideEditor.Border3DSideUI(this)) {
ui.Start(service, value);
service.DropDownControl(ui);
value = ui.Value;
ui.End();
}
}
return value;
}
/// <summary>
///
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override System.Drawing.Design.UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) {
return UITypeEditorEditStyle.DropDown;
}
}
}
| |
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Apis.Http;
using Google.Apis.Requests;
using Google.Apis.Services;
using Moq;
using Moq.Language.Flow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Google.PowerShell.Tests.Common
{
/// <summary>
/// A set of extention methods for to help when mocking google api services.
/// </summary>
public static class GoogleApiMockExtensions
{
/// <summary>
/// Takes a mock for either a <see cref="BaseClientService"/> or a resource and creates a mock of a child
/// resource.
/// </summary>
/// <typeparam name="T">The mocked type to get a mocked child resource from.</typeparam>
/// <typeparam name="TResource">A resource type in the mocked type.</typeparam>
/// <param name="mock">The mock to setup the resource as a child of.</param>
/// <param name="resourceExpression">The express that gets the resource.</param>
public static Mock<TResource> Resource<T, TResource>(
this Mock<T> mock,
Expression<Func<T, TResource>> resourceExpression)
where T : class
where TResource : class
{
var resourceMock = new Mock<TResource>(Mock.Of<IClientService>());
mock.Setup(resourceExpression).Returns(resourceMock.Object);
return resourceMock;
}
/// <summary>
/// Sets up a request that will throw an exception when executed.
/// </summary>
/// <typeparam name="TResource">The type of resource creating the request.</typeparam>
/// <typeparam name="TRequest">The type of the request to make.</typeparam>
/// <typeparam name="TResponse">The type of the responce.</typeparam>
/// <param name="resourceMock">The mock of the resource that makes the request.</param>
/// <param name="requestExpression">The expression of the request. Uses Moq.It functions for wildcards.</param>
/// <param name="exception">The exception the request will throw when executed.</param>
/// <returns>The mock of the request object. Useful for verification.</returns>
public static Mock<TRequest> SetupRequestError<TResource, TRequest, TResponse>(
this Mock<TResource> resourceMock,
Expression<Func<TResource, TRequest>> requestExpression,
Exception exception)
where TRequest : ClientServiceRequest<TResponse>
where TResource : class
{
Mock<IClientService> clientServiceMock = GetClientServiceMock();
Mock<TRequest> requestMock = GetRequestMock(requestExpression, clientServiceMock.Object);
resourceMock.Setup(requestExpression).Returns(requestMock.Object);
clientServiceMock.Setup(c => c.DeserializeResponse<TResponse>(It.IsAny<HttpResponseMessage>()))
.Throws(exception);
return requestMock;
}
/// <summary>
/// Sets up a request.
/// </summary>
/// <typeparam name="TResource">The type of resource creating the request.</typeparam>
/// <typeparam name="TRequest">The type of the request to make.</typeparam>
/// <typeparam name="TResponse">The type of the responce.</typeparam>
/// <param name="resourceMock">The mock of the resource that makes the request.</param>
/// <param name="requestExpression">The expression of the request. Uses Moq.It functions for wildcards.</param>
/// <param name="response">The responce the request should receive.</param>
/// <returns>The mock of the request object. Useful for verification.</returns>
public static Mock<TRequest> SetupRequest<TResource, TRequest, TResponse>(
this Mock<TResource> resourceMock,
Expression<Func<TResource, TRequest>> requestExpression,
Task<TResponse> response)
where TRequest : ClientServiceRequest<TResponse>
where TResource : class
{
Mock<IClientService> clientServiceMock = GetClientServiceMock();
Mock<TRequest> requestMock = GetRequestMock(requestExpression, clientServiceMock.Object);
resourceMock.Setup(requestExpression).Returns(requestMock.Object);
clientServiceMock.Setup(c => c.DeserializeResponse<TResponse>(It.IsAny<HttpResponseMessage>()))
.Returns(response);
return requestMock;
}
/// <summary>
/// Sets up a request.
/// </summary>
/// <typeparam name="TResource">The type of resource creating the request.</typeparam>
/// <typeparam name="TRequest">The type of the request to make.</typeparam>
/// <typeparam name="TResponse">The type of the responce.</typeparam>
/// <param name="resourceMock">The mock of the resource that makes the request.</param>
/// <param name="requestExpression">The expression of the request. Uses Moq.It functions for wildcards.</param>
/// <param name="response">The responce the request should receive.</param>
/// <returns>The mock of the request object. Useful for verification.</returns>
public static Mock<TRequest> SetupRequest<TResource, TRequest, TResponse>(
this Mock<TResource> resourceMock,
Expression<Func<TResource, TRequest>> requestExpression,
TResponse response)
where TRequest : ClientServiceRequest<TResponse>
where TResource : class
{
return resourceMock.SetupRequest(requestExpression, Task.FromResult(response));
}
/// <summary>
/// Sets up a request.
/// </summary>
/// <typeparam name="TResource">The type of resource creating the request.</typeparam>
/// <typeparam name="TRequest">The type of the request to make.</typeparam>
/// <typeparam name="TResponse">The type of the responce.</typeparam>
/// <param name="resourceMock">The mock of the resource that makes the request.</param>
/// <param name="requestExpression">The expression of the request. Uses Moq.It functions for wildcards.</param>
/// <param name="response">A function returning responce the request should receive.</param>
/// <returns>The mock of the request object. Useful for verification.</returns>
public static Mock<TRequest> SetupRequest<TResource, TRequest, TResponse>(
this Mock<TResource> resourceMock,
Expression<Func<TResource, TRequest>> requestExpression,
Func<Task<TResponse>> response)
where TRequest : ClientServiceRequest<TResponse>
where TResource : class
{
Mock<IClientService> clientServiceMock = GetClientServiceMock();
Mock<TRequest> requestMock = GetRequestMock(requestExpression, clientServiceMock.Object);
resourceMock.Setup(requestExpression).Returns(requestMock.Object);
clientServiceMock.Setup(c => c.DeserializeResponse<TResponse>(It.IsAny<HttpResponseMessage>()))
.Returns(response);
return requestMock;
}
/// <summary>
/// Sets up a request on which a response can be set up. Pairs with <see cref="SetupResponse{TResponse}"/>.
/// </summary>
/// When setting up an error, using this with <see cref="SetupResponse{TResponse}"/> requires fewer explicit
/// generic parameters.
/// <code>
/// projects.SetupRequest(p => p.List()).SetupResponse<ListProjectsResponse>()
/// .Throws(new Exception("error-message"));
/// </code>
/// as opposed to
/// <code>
/// projects.SetupRequestError<ProjectsResource, ProjectsResource.ListRequest, ListProjectsResponse>(
/// p => o.Get(bucketName, objectName),
/// new Exception("error-message"));
/// </code>
/// <typeparam name="TResource">The type of resource creating the request.</typeparam>
/// <typeparam name="TRequest">The type of the request to make.</typeparam>
/// <param name="resourceMock">The mock of the resource that makes the request.</param>
/// <param name="requestExpression">The expression of the request. Uses Moq.It functions for wildcards.</param>
/// <returns>The mock of the request object. Useful for verification.</returns>
public static Mock<IClientService> SetupRequest<TResource, TRequest>(
this Mock<TResource> resourceMock,
Expression<Func<TResource, TRequest>> requestExpression)
where TRequest : class, IClientServiceRequest
where TResource : class
{
Mock<IClientService> clientServiceMock = GetClientServiceMock();
Mock<TRequest> requestMock = GetRequestMock(requestExpression, clientServiceMock.Object);
resourceMock.Setup(requestExpression).Returns(requestMock.Object);
return clientServiceMock;
}
/// <summary>
/// Gets a setup for a response to a request. Call <see cref="Moq.Language.IThrows.Throws"/> or
/// <see cref="Moq.Language.IReturns{TMock,TResult}.Returns{T}"/> on the result of this function.
/// </summary>
/// <typeparam name="TResponse">The type of response to return.</typeparam>
/// <param name="clientServiceMock">The mock of a Client Service to setup.
/// Usually comes from <see cref="SetupRequest{TResource,TRequest}"/>.</param>
public static ISetup<IClientService, Task<TResponse>> SetupResponse<TResponse>(
this Mock<IClientService> clientServiceMock)
{
return clientServiceMock.Setup(c => c.DeserializeResponse<TResponse>(It.IsAny<HttpResponseMessage>()));
}
private static Mock<TRequest> GetRequestMock<TRequest, TResource>(
Expression<Func<TResource, TRequest>> requestExpression,
IClientService clientService) where TRequest : class, IClientServiceRequest
{
var requestMethod = requestExpression.Body as MethodCallExpression;
if (requestMethod == null)
{
throw new ArgumentException(
$"{nameof(requestExpression)}.{nameof(requestExpression.Body)} " +
$"must be of type {nameof(MethodCallExpression)} " +
$"but was {requestExpression.Body.GetType()}");
}
IEnumerable<object> methodArgs =
requestMethod.Arguments.Select(a => a.Type)
.Select(Expression.Default)
.Select(e => Expression.Convert(e, typeof(object)))
.Select(e => Expression.Lambda<Func<object>>(e).Compile()());
object[] constructorArgs = new[] { clientService }.Concat(methodArgs).ToArray();
var requestMock = new Mock<TRequest>(constructorArgs)
{
CallBase = true
};
requestMock.Setup(r => r.RestPath).Returns("/");
requestMock.Object.RequestParameters.Clear();
return requestMock;
}
private static Mock<IClientService> GetClientServiceMock()
{
var clientServiceMock = new Mock<IClientService>();
var handlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
// Use MockBehavior.Strict to ensure we make no acutal http requests.
var configurableHandlerMock =
new Mock<ConfigurableMessageHandler>(MockBehavior.Strict, handlerMock.Object);
var clientMock = new Mock<ConfigurableHttpClient>(MockBehavior.Strict, configurableHandlerMock.Object);
clientMock.Setup(c => c.SendAsync(It.IsAny<HttpRequestMessage>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new HttpResponseMessage()));
clientServiceMock.Setup(c => c.BaseUri).Returns("https://mock.uri");
clientServiceMock.Setup(c => c.HttpClient).Returns(clientMock.Object);
clientServiceMock.Setup(c => c.Serializer.Format).Returns("json");
clientServiceMock.Setup(c => c.SerializeObject(It.IsAny<object>())).Returns("{}");
return clientServiceMock;
}
}
}
| |
using System;
using UnityEngine.FrameRecorder;
using UnityEngine;
namespace UnityEditor.FrameRecorder
{
public class RecorderWindow : EditorWindow
{
enum EState
{
Idle,
WaitingForPlayModeToStartRecording,
Recording
}
RecorderEditor m_Editor;
EState m_State = EState.Idle;
RecorderSelector m_recorderSelector;
string m_StartingCategory = string.Empty;
RecorderWindowSettings m_WindowSettingsAsset;
public static void ShowAndPreselectCategory(string category)
{
var window = GetWindow(typeof(RecorderWindow), false, "Recorder") as RecorderWindow;
if (RecordersInventory.recordersByCategory.ContainsKey(category))
{
window.m_StartingCategory = category;
window.m_recorderSelector = null;
}
}
public void OnEnable()
{
m_recorderSelector = null;
}
DateTime m_LastRepaint = DateTime.MinValue;
protected void Update()
{
if (m_State == EState.Recording && (DateTime.Now - m_LastRepaint).TotalMilliseconds > 50)
{
Repaint();
}
}
Vector2 m_ScrollPos;
public void OnGUI()
{
try
{
m_ScrollPos = EditorGUILayout.BeginScrollView(m_ScrollPos);
try
{
m_LastRepaint = DateTime.Now;
// Bug? work arround: on Stop play, Enable is not called.
if (m_Editor != null && m_Editor.target == null)
{
UnityHelpers.Destroy(m_Editor);
m_Editor = null;
m_recorderSelector = null;
}
if (m_recorderSelector == null)
{
if (m_WindowSettingsAsset == null)
{
var candidates = AssetDatabase.FindAssets("t:RecorderWindowSettings");
if (candidates.Length > 0)
{
var path = AssetDatabase.GUIDToAssetPath(candidates[0]);
m_WindowSettingsAsset = AssetDatabase.LoadAssetAtPath<RecorderWindowSettings>(path);
if (m_WindowSettingsAsset == null)
{
AssetDatabase.DeleteAsset(path);
}
}
if(m_WindowSettingsAsset == null)
{
m_WindowSettingsAsset = ScriptableObject.CreateInstance<RecorderWindowSettings>();
AssetDatabase.CreateAsset(m_WindowSettingsAsset, "Assets/FrameRecordingSettings.asset");
AssetDatabase.Refresh();
}
}
m_recorderSelector = new RecorderSelector(OnRecorderSelected, true);
m_recorderSelector.Init(m_WindowSettingsAsset.m_Settings, m_StartingCategory);
}
if (m_State == EState.WaitingForPlayModeToStartRecording && EditorApplication.isPlaying)
DelayedStartRecording();
using (new EditorGUI.DisabledScope(EditorApplication.isPlaying))
m_recorderSelector.OnGui();
if (m_Editor != null)
{
m_Editor.showBounds = true;
using (new EditorGUI.DisabledScope(EditorApplication.isPlaying))
{
EditorGUILayout.Separator();
m_Editor.OnInspectorGUI();
EditorGUILayout.Separator();
}
RecordButtonOnGui();
GUILayout.Space(50);
}
}
finally
{
EditorGUILayout.EndScrollView();
}
}
catch (ExitGUIException)
{
}
catch (Exception ex)
{
if (m_State == EState.Recording)
{
try
{
Debug.LogError("Aborting recording due to an exception!\n" + ex.ToString());
StopRecording();
}
catch (Exception) {}
}
else
{
EditorGUILayout.HelpBox("An exception was raised while editing the settings. This can be indicative of corrupted settings.", MessageType.Warning);
if (GUILayout.Button("Reset settings to default"))
{
ResetSettings();
}
}
Debug.LogException(ex);
}
}
void ResetSettings()
{
UnityHelpers.Destroy(m_Editor);
m_Editor = null;
m_recorderSelector = null;
var path = AssetDatabase.GetAssetPath(m_WindowSettingsAsset);
UnityHelpers.Destroy(m_WindowSettingsAsset, true);
AssetDatabase.DeleteAsset(path);
AssetDatabase.Refresh(ImportAssetOptions.Default);
m_WindowSettingsAsset = null;
}
public void OnDestroy()
{
StopRecording();
UnityHelpers.Destroy(m_Editor);
m_Editor = null;
}
void RecordButtonOnGui()
{
if (m_Editor == null || m_Editor.target == null)
return;
switch (m_State)
{
case EState.Idle:
{
using (new EditorGUI.DisabledScope(!m_Editor.isValid ))
{
if (GUILayout.Button("Start Recording"))
StartRecording();
}
break;
}
case EState.WaitingForPlayModeToStartRecording:
{
using (new EditorGUI.DisabledScope(true))
GUILayout.Button("Stop Recording"); // passive
break;
}
case EState.Recording:
{
var recorderGO = FrameRecorderGOControler.FindRecorder((RecorderSettings)m_Editor.target);
if (recorderGO == null)
{
GUILayout.Button("Start Recording"); // just to keep the ui system happy.
m_State = EState.Idle;
}
else
{
if (GUILayout.Button("Stop Recording"))
StopRecording();
UpdateRecordingProgress(recorderGO);
}
break;
}
default:
throw new ArgumentOutOfRangeException();
}
}
void UpdateRecordingProgress( GameObject go)
{
var rect = EditorGUILayout.BeginHorizontal( );
rect.height = 20;
var recComp = go.GetComponent<RecorderComponent>();
if (recComp == null || recComp.session == null)
return;
var session = recComp.session;
var settings = recComp.session.m_Recorder.settings;
switch (settings.m_DurationMode)
{
case DurationMode.Manual:
{
var label = string.Format("{0} Frames recorded", session.m_Recorder.recordedFramesCount);
EditorGUI.ProgressBar(rect, 0, label );
break;
}
case DurationMode.SingleFrame:
case DurationMode.FrameInterval:
{
var label = (session.frameIndex < settings.m_StartFrame) ?
string.Format("Skipping first {0} frames...", settings.m_StartFrame-1) :
string.Format("{0} Frames recorded", session.m_Recorder.recordedFramesCount);
EditorGUI.ProgressBar(rect, (session.frameIndex +1) / (float)(settings.m_EndFrame +1), label );
break;
}
case DurationMode.TimeInterval:
{
var label = (session.m_CurrentFrameStartTS < settings.m_StartTime) ?
string.Format("Skipping first {0} seconds...", settings.m_StartTime) :
string.Format("{0} Frames recorded", session.m_Recorder.recordedFramesCount);
EditorGUI.ProgressBar(rect,(float)session.m_CurrentFrameStartTS / (settings.m_EndTime == 0f ? 0.0001f : settings.m_EndTime), label );
break;
}
}
EditorGUILayout.EndHorizontal();
}
void StartRecording()
{
m_State = EState.WaitingForPlayModeToStartRecording;
EditorApplication.isPlaying = true;
return;
}
void DelayedStartRecording()
{
StartRecording(true);
}
void StartRecording(bool autoExitPlayMode)
{
var settings = (RecorderSettings)m_Editor.target;
var go = FrameRecorderGOControler.HookupRecorder(!settings.m_Verbose);
var session = new RecordingSession()
{
m_Recorder = RecordersInventory.GenerateNewRecorder(m_recorderSelector.selectedRecorder, settings),
m_RecorderGO = go,
};
var component = go.AddComponent<RecorderComponent>();
component.session = session;
component.autoExitPlayMode = autoExitPlayMode;
if (session.SessionCreated() && session.BeginRecording())
m_State = EState.Recording;
else
{
m_State = EState.Idle;
StopRecording();
}
}
void StopRecording()
{
if (m_Editor != null)
{
var settings = (RecorderSettings)m_Editor.target;
if (settings != null)
{
var recorderGO = FrameRecorderGOControler.FindRecorder(settings);
if (recorderGO != null)
{
UnityHelpers.Destroy(recorderGO);
}
}
}
}
public void OnRecorderSelected()
{
if (m_Editor != null)
{
UnityHelpers.Destroy(m_Editor);
m_Editor = null;
}
if (m_recorderSelector.selectedRecorder == null)
return;
if (m_WindowSettingsAsset.m_Settings != null && RecordersInventory.GetRecorderInfo(m_recorderSelector.selectedRecorder).settings != m_WindowSettingsAsset.m_Settings.GetType())
{
UnityHelpers.Destroy(m_WindowSettingsAsset.m_Settings, true);
m_WindowSettingsAsset.m_Settings = null;
}
if( m_WindowSettingsAsset.m_Settings == null )
m_WindowSettingsAsset.m_Settings = RecordersInventory.GenerateNewSettingsAsset(m_WindowSettingsAsset, m_recorderSelector.selectedRecorder );
m_Editor = Editor.CreateEditor( m_WindowSettingsAsset.m_Settings ) as RecorderEditor;
AssetDatabase.Refresh();
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace BinxEd
{
/// <summary>
/// MainForm is the main View for the application.
/// </summary>
public class MainForm : System.Windows.Forms.Form
{
private Controller controller_;
private ContextMenu tv1Menu;
private TreeNode targetNode_;
private int RightPaneWidth_;
// private bool defineMode_;
private System.Windows.Forms.ToolBar toolBar1;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.SaveFileDialog saveFileDialog1;
private System.Windows.Forms.StatusBar statusBar1;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem menuItemFile;
private System.Windows.Forms.MenuItem menuItemNew;
private System.Windows.Forms.MenuItem menuItemOpen;
private System.Windows.Forms.MenuItem menuItemSave;
private System.Windows.Forms.MenuItem menuItemSaveAs;
private System.Windows.Forms.MenuItem menuItem6;
private System.Windows.Forms.MenuItem menuItemExit;
private System.Windows.Forms.MenuItem menuItemEdit;
private System.Windows.Forms.MenuItem menuItemAddAfter;
private System.Windows.Forms.MenuItem menuItemAddChild;
private System.Windows.Forms.MenuItem menuItemDefine;
private System.Windows.Forms.MenuItem menuItemDefineStruct;
private System.Windows.Forms.MenuItem menuItemDefineUnion;
private System.Windows.Forms.MenuItem menuItemDefineArray;
private System.Windows.Forms.MenuItem menuItemUtility;
private System.Windows.Forms.MenuItem menuItemValidate;
private System.Windows.Forms.MenuItem menuItemHelp;
private System.Windows.Forms.MenuItem menuItemDocument;
private System.Windows.Forms.MenuItem menuItemSchema;
private System.Windows.Forms.MenuItem menuItemSave0;
private System.Windows.Forms.MenuItem menuItemAboutMe;
private System.Windows.Forms.ToolBarButton toolBarButtonNew;
private System.Windows.Forms.ToolBarButton toolBarButtonOpen;
private System.Windows.Forms.ToolBarButton toolBarButtonSave;
private System.Windows.Forms.ImageList imageList1;
private System.Windows.Forms.TreeView treeView1;
private System.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.MenuItem menuItemFile3;
private System.Windows.Forms.MenuItem menuItemDelete;
private System.Windows.Forms.MenuItem menuItemFile7;
private System.Windows.Forms.MenuItem menuItemBigEndian;
private System.Windows.Forms.ToolBarButton toolBarButtonDelete;
private System.Windows.Forms.MenuItem menuItemBrowse;
private PropertyView listView1;
private System.Windows.Forms.ImageList imageListNodeIcons;
private System.Windows.Forms.MenuItem menuItemAddBefore;
private System.Windows.Forms.MenuItem menuItemPrimitiveBefore;
private System.Windows.Forms.MenuItem menuItemDefinedBefore;
private System.Windows.Forms.MenuItem menuItemStructBefore;
private System.Windows.Forms.MenuItem menuItemUnionBefore;
private System.Windows.Forms.MenuItem menuItemArrayBefore;
private System.Windows.Forms.MenuItem menuItemCaseBefore;
private System.Windows.Forms.MenuItem menuItemPrimitiveAfter;
private System.Windows.Forms.MenuItem menuItemDefinedAfter;
private System.Windows.Forms.MenuItem menuItemStructAfter;
private System.Windows.Forms.MenuItem menuItemUnionAfter;
private System.Windows.Forms.MenuItem menuItemArrayAfter;
private System.Windows.Forms.MenuItem menuItemCaseAfter;
private System.Windows.Forms.MenuItem menuItemPrimitiveChild;
private System.Windows.Forms.MenuItem menuItemDefinedChild;
private System.Windows.Forms.MenuItem menuItemStructChild;
private System.Windows.Forms.MenuItem menuItemUnionChild;
private System.Windows.Forms.MenuItem menuItemArrayChild;
private System.Windows.Forms.MenuItem menuItemCaseChild;
private System.Windows.Forms.MenuItem menuItemDimChild;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuItemFontPlus;
private System.Windows.Forms.MenuItem menuItemFontMinus;
private System.Windows.Forms.ToolBarButton toolBarButtonSeparator2;
private System.Windows.Forms.ToolBarButton toolBarButtonFontPlus;
private System.Windows.Forms.ToolBarButton toolBarButtonFontMinus;
private System.Windows.Forms.MenuItem menuItem2;
private System.Windows.Forms.MenuItem menuItemImport;
private System.Windows.Forms.ToolBarButton toolBarButtonBrowse;
private System.Windows.Forms.ToolBarButton toolBarButtonValidate;
private System.Windows.Forms.ToolBarButton toolBarButtonSeparator3;
private System.Windows.Forms.ToolBarButton toolBarButtonImport;
private System.Windows.Forms.ToolBarButton toolBarButtonSeparator1;
private System.ComponentModel.IContainer components;
public MainForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
controller_ = new Controller(this);
RightPaneWidth_ = this.Width - splitter1.SplitPosition;
}
/// <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()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MainForm));
this.toolBar1 = new System.Windows.Forms.ToolBar();
this.toolBarButtonNew = new System.Windows.Forms.ToolBarButton();
this.toolBarButtonOpen = new System.Windows.Forms.ToolBarButton();
this.toolBarButtonSave = new System.Windows.Forms.ToolBarButton();
this.toolBarButtonSeparator1 = new System.Windows.Forms.ToolBarButton();
this.toolBarButtonDelete = new System.Windows.Forms.ToolBarButton();
this.toolBarButtonSeparator2 = new System.Windows.Forms.ToolBarButton();
this.toolBarButtonFontPlus = new System.Windows.Forms.ToolBarButton();
this.toolBarButtonFontMinus = new System.Windows.Forms.ToolBarButton();
this.toolBarButtonSeparator3 = new System.Windows.Forms.ToolBarButton();
this.toolBarButtonBrowse = new System.Windows.Forms.ToolBarButton();
this.toolBarButtonValidate = new System.Windows.Forms.ToolBarButton();
this.toolBarButtonImport = new System.Windows.Forms.ToolBarButton();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
this.statusBar1 = new System.Windows.Forms.StatusBar();
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.menuItemFile = new System.Windows.Forms.MenuItem();
this.menuItemNew = new System.Windows.Forms.MenuItem();
this.menuItemOpen = new System.Windows.Forms.MenuItem();
this.menuItemSave = new System.Windows.Forms.MenuItem();
this.menuItemSaveAs = new System.Windows.Forms.MenuItem();
this.menuItem6 = new System.Windows.Forms.MenuItem();
this.menuItemExit = new System.Windows.Forms.MenuItem();
this.menuItemEdit = new System.Windows.Forms.MenuItem();
this.menuItemAddBefore = new System.Windows.Forms.MenuItem();
this.menuItemPrimitiveBefore = new System.Windows.Forms.MenuItem();
this.menuItemDefinedBefore = new System.Windows.Forms.MenuItem();
this.menuItemStructBefore = new System.Windows.Forms.MenuItem();
this.menuItemUnionBefore = new System.Windows.Forms.MenuItem();
this.menuItemArrayBefore = new System.Windows.Forms.MenuItem();
this.menuItemCaseBefore = new System.Windows.Forms.MenuItem();
this.menuItemAddAfter = new System.Windows.Forms.MenuItem();
this.menuItemPrimitiveAfter = new System.Windows.Forms.MenuItem();
this.menuItemDefinedAfter = new System.Windows.Forms.MenuItem();
this.menuItemStructAfter = new System.Windows.Forms.MenuItem();
this.menuItemUnionAfter = new System.Windows.Forms.MenuItem();
this.menuItemArrayAfter = new System.Windows.Forms.MenuItem();
this.menuItemCaseAfter = new System.Windows.Forms.MenuItem();
this.menuItemAddChild = new System.Windows.Forms.MenuItem();
this.menuItemPrimitiveChild = new System.Windows.Forms.MenuItem();
this.menuItemDefinedChild = new System.Windows.Forms.MenuItem();
this.menuItemStructChild = new System.Windows.Forms.MenuItem();
this.menuItemUnionChild = new System.Windows.Forms.MenuItem();
this.menuItemArrayChild = new System.Windows.Forms.MenuItem();
this.menuItemCaseChild = new System.Windows.Forms.MenuItem();
this.menuItemDimChild = new System.Windows.Forms.MenuItem();
this.menuItemFile3 = new System.Windows.Forms.MenuItem();
this.menuItemDelete = new System.Windows.Forms.MenuItem();
this.menuItemFile7 = new System.Windows.Forms.MenuItem();
this.menuItemBigEndian = new System.Windows.Forms.MenuItem();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuItemFontPlus = new System.Windows.Forms.MenuItem();
this.menuItemFontMinus = new System.Windows.Forms.MenuItem();
this.menuItemDefine = new System.Windows.Forms.MenuItem();
this.menuItemDefineStruct = new System.Windows.Forms.MenuItem();
this.menuItemDefineUnion = new System.Windows.Forms.MenuItem();
this.menuItemDefineArray = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.menuItemImport = new System.Windows.Forms.MenuItem();
this.menuItemUtility = new System.Windows.Forms.MenuItem();
this.menuItemBrowse = new System.Windows.Forms.MenuItem();
this.menuItemValidate = new System.Windows.Forms.MenuItem();
this.menuItemHelp = new System.Windows.Forms.MenuItem();
this.menuItemDocument = new System.Windows.Forms.MenuItem();
this.menuItemSchema = new System.Windows.Forms.MenuItem();
this.menuItemSave0 = new System.Windows.Forms.MenuItem();
this.menuItemAboutMe = new System.Windows.Forms.MenuItem();
this.treeView1 = new System.Windows.Forms.TreeView();
this.imageListNodeIcons = new System.Windows.Forms.ImageList(this.components);
this.splitter1 = new System.Windows.Forms.Splitter();
this.listView1 = new BinxEd.PropertyView();
this.SuspendLayout();
//
// toolBar1
//
this.toolBar1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
this.toolBarButtonNew,
this.toolBarButtonOpen,
this.toolBarButtonSave,
this.toolBarButtonSeparator1,
this.toolBarButtonDelete,
this.toolBarButtonSeparator2,
this.toolBarButtonFontPlus,
this.toolBarButtonFontMinus,
this.toolBarButtonSeparator3,
this.toolBarButtonBrowse,
this.toolBarButtonValidate,
this.toolBarButtonImport});
this.toolBar1.DropDownArrows = true;
this.toolBar1.ImageList = this.imageList1;
this.toolBar1.Location = new System.Drawing.Point(0, 0);
this.toolBar1.Name = "toolBar1";
this.toolBar1.ShowToolTips = true;
this.toolBar1.Size = new System.Drawing.Size(752, 29);
this.toolBar1.TabIndex = 0;
this.toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick);
//
// toolBarButtonNew
//
this.toolBarButtonNew.ImageIndex = 0;
this.toolBarButtonNew.Tag = "NEW";
this.toolBarButtonNew.ToolTipText = "Create new BinX document";
//
// toolBarButtonOpen
//
this.toolBarButtonOpen.ImageIndex = 1;
this.toolBarButtonOpen.Tag = "OPEN";
this.toolBarButtonOpen.ToolTipText = "Open a BinX document";
//
// toolBarButtonSave
//
this.toolBarButtonSave.ImageIndex = 2;
this.toolBarButtonSave.Tag = "SAVE";
this.toolBarButtonSave.ToolTipText = "Save BinX document";
//
// toolBarButtonSeparator1
//
this.toolBarButtonSeparator1.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// toolBarButtonDelete
//
this.toolBarButtonDelete.Enabled = false;
this.toolBarButtonDelete.ImageIndex = 6;
this.toolBarButtonDelete.Tag = "DELETE";
this.toolBarButtonDelete.ToolTipText = "Delete the selected node";
//
// toolBarButtonSeparator2
//
this.toolBarButtonSeparator2.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// toolBarButtonFontPlus
//
this.toolBarButtonFontPlus.ImageIndex = 7;
this.toolBarButtonFontPlus.Tag = "FONT+";
this.toolBarButtonFontPlus.ToolTipText = "Increase Font size in TreeView";
//
// toolBarButtonFontMinus
//
this.toolBarButtonFontMinus.ImageIndex = 8;
this.toolBarButtonFontMinus.Tag = "FONT-";
this.toolBarButtonFontMinus.ToolTipText = "Decrease Font size in TreeView";
//
// toolBarButtonSeparator3
//
this.toolBarButtonSeparator3.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// toolBarButtonBrowse
//
this.toolBarButtonBrowse.ImageIndex = 3;
this.toolBarButtonBrowse.Tag = "BROWSE";
this.toolBarButtonBrowse.ToolTipText = "View BinX document in Browser";
//
// toolBarButtonValidate
//
this.toolBarButtonValidate.ImageIndex = 4;
this.toolBarButtonValidate.Tag = "VALIDATE";
this.toolBarButtonValidate.ToolTipText = "Validate a BinX document";
//
// toolBarButtonImport
//
this.toolBarButtonImport.ImageIndex = 5;
this.toolBarButtonImport.Tag = "IMPORT";
this.toolBarButtonImport.ToolTipText = "Import type definitions from another BinX document";
//
// imageList1
//
this.imageList1.ImageSize = new System.Drawing.Size(16, 16);
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
//
// openFileDialog1
//
this.openFileDialog1.DefaultExt = "xml";
this.openFileDialog1.Filter = "BinX document|*.xml";
//
// saveFileDialog1
//
this.saveFileDialog1.DefaultExt = "xml";
this.saveFileDialog1.Filter = "BinX document|*.xml";
//
// statusBar1
//
this.statusBar1.Location = new System.Drawing.Point(0, 565);
this.statusBar1.Name = "statusBar1";
this.statusBar1.Size = new System.Drawing.Size(752, 16);
this.statusBar1.TabIndex = 1;
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemFile,
this.menuItemEdit,
this.menuItemDefine,
this.menuItemUtility,
this.menuItemHelp});
//
// menuItemFile
//
this.menuItemFile.Index = 0;
this.menuItemFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemNew,
this.menuItemOpen,
this.menuItemSave,
this.menuItemSaveAs,
this.menuItem6,
this.menuItemExit});
this.menuItemFile.Text = "&File";
//
// menuItemNew
//
this.menuItemNew.Index = 0;
this.menuItemNew.Text = "&New";
this.menuItemNew.Click += new System.EventHandler(this.menuItemNew_Click);
//
// menuItemOpen
//
this.menuItemOpen.Index = 1;
this.menuItemOpen.Text = "&Open";
this.menuItemOpen.Click += new System.EventHandler(this.menuItemOpen_Click);
//
// menuItemSave
//
this.menuItemSave.Index = 2;
this.menuItemSave.Text = "&Save";
this.menuItemSave.Click += new System.EventHandler(this.menuItemSave_Click);
//
// menuItemSaveAs
//
this.menuItemSaveAs.Index = 3;
this.menuItemSaveAs.Text = "Save &As";
this.menuItemSaveAs.Click += new System.EventHandler(this.menuItemSaveAs_Click);
//
// menuItem6
//
this.menuItem6.Index = 4;
this.menuItem6.Text = "-";
//
// menuItemExit
//
this.menuItemExit.Index = 5;
this.menuItemExit.Text = "E&xit";
this.menuItemExit.Click += new System.EventHandler(this.menuItemExit_Click);
//
// menuItemEdit
//
this.menuItemEdit.Index = 1;
this.menuItemEdit.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemAddBefore,
this.menuItemAddAfter,
this.menuItemAddChild,
this.menuItemFile3,
this.menuItemDelete,
this.menuItemFile7,
this.menuItemBigEndian,
this.menuItem1,
this.menuItemFontPlus,
this.menuItemFontMinus});
this.menuItemEdit.Text = "&Edit";
//
// menuItemAddBefore
//
this.menuItemAddBefore.Enabled = false;
this.menuItemAddBefore.Index = 0;
this.menuItemAddBefore.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemPrimitiveBefore,
this.menuItemDefinedBefore,
this.menuItemStructBefore,
this.menuItemUnionBefore,
this.menuItemArrayBefore,
this.menuItemCaseBefore});
this.menuItemAddBefore.Text = "Add Before";
//
// menuItemPrimitiveBefore
//
this.menuItemPrimitiveBefore.Index = 0;
this.menuItemPrimitiveBefore.Text = "Primitive";
this.menuItemPrimitiveBefore.Click += new System.EventHandler(this.menuItemPrimitiveBefore_Click);
//
// menuItemDefinedBefore
//
this.menuItemDefinedBefore.Index = 1;
this.menuItemDefinedBefore.Text = "Defined";
this.menuItemDefinedBefore.Click += new System.EventHandler(this.menuItemDefinedBefore_Click);
//
// menuItemStructBefore
//
this.menuItemStructBefore.Index = 2;
this.menuItemStructBefore.Text = "Struct";
this.menuItemStructBefore.Click += new System.EventHandler(this.menuItemStructBefore_Click);
//
// menuItemUnionBefore
//
this.menuItemUnionBefore.Index = 3;
this.menuItemUnionBefore.Text = "Union";
this.menuItemUnionBefore.Click += new System.EventHandler(this.menuItemUnionBefore_Click);
//
// menuItemArrayBefore
//
this.menuItemArrayBefore.Index = 4;
this.menuItemArrayBefore.Text = "Array";
this.menuItemArrayBefore.Click += new System.EventHandler(this.menuItemArrayBefore_Click);
//
// menuItemCaseBefore
//
this.menuItemCaseBefore.Index = 5;
this.menuItemCaseBefore.Text = "Case";
this.menuItemCaseBefore.Click += new System.EventHandler(this.menuItemCaseBefore_Click);
//
// menuItemAddAfter
//
this.menuItemAddAfter.Enabled = false;
this.menuItemAddAfter.Index = 1;
this.menuItemAddAfter.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemPrimitiveAfter,
this.menuItemDefinedAfter,
this.menuItemStructAfter,
this.menuItemUnionAfter,
this.menuItemArrayAfter,
this.menuItemCaseAfter});
this.menuItemAddAfter.Text = "Add After";
//
// menuItemPrimitiveAfter
//
this.menuItemPrimitiveAfter.Index = 0;
this.menuItemPrimitiveAfter.Text = "Primitive";
this.menuItemPrimitiveAfter.Click += new System.EventHandler(this.menuItemPrimitiveAfter_Click);
//
// menuItemDefinedAfter
//
this.menuItemDefinedAfter.Index = 1;
this.menuItemDefinedAfter.Text = "Defined";
this.menuItemDefinedAfter.Click += new System.EventHandler(this.menuItemDefinedAfter_Click);
//
// menuItemStructAfter
//
this.menuItemStructAfter.Index = 2;
this.menuItemStructAfter.Text = "Struct";
this.menuItemStructAfter.Click += new System.EventHandler(this.menuItemStructAfter_Click);
//
// menuItemUnionAfter
//
this.menuItemUnionAfter.Index = 3;
this.menuItemUnionAfter.Text = "Union";
this.menuItemUnionAfter.Click += new System.EventHandler(this.menuItemUnionAfter_Click);
//
// menuItemArrayAfter
//
this.menuItemArrayAfter.Index = 4;
this.menuItemArrayAfter.Text = "Array";
this.menuItemArrayAfter.Click += new System.EventHandler(this.menuItemArrayAfter_Click);
//
// menuItemCaseAfter
//
this.menuItemCaseAfter.Index = 5;
this.menuItemCaseAfter.Text = "Case";
this.menuItemCaseAfter.Click += new System.EventHandler(this.menuItemCaseAfter_Click);
//
// menuItemAddChild
//
this.menuItemAddChild.Enabled = false;
this.menuItemAddChild.Index = 2;
this.menuItemAddChild.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemPrimitiveChild,
this.menuItemDefinedChild,
this.menuItemStructChild,
this.menuItemUnionChild,
this.menuItemArrayChild,
this.menuItemCaseChild,
this.menuItemDimChild});
this.menuItemAddChild.Text = "Add Child";
//
// menuItemPrimitiveChild
//
this.menuItemPrimitiveChild.Index = 0;
this.menuItemPrimitiveChild.Text = "Primitive";
this.menuItemPrimitiveChild.Click += new System.EventHandler(this.menuItemPrimitiveChild_Click);
//
// menuItemDefinedChild
//
this.menuItemDefinedChild.Index = 1;
this.menuItemDefinedChild.Text = "Defined";
this.menuItemDefinedChild.Click += new System.EventHandler(this.menuItemDefinedChild_Click);
//
// menuItemStructChild
//
this.menuItemStructChild.Index = 2;
this.menuItemStructChild.Text = "Struct";
this.menuItemStructChild.Click += new System.EventHandler(this.menuItemStructChild_Click);
//
// menuItemUnionChild
//
this.menuItemUnionChild.Index = 3;
this.menuItemUnionChild.Text = "Union";
this.menuItemUnionChild.Click += new System.EventHandler(this.menuItemUnionChild_Click);
//
// menuItemArrayChild
//
this.menuItemArrayChild.Index = 4;
this.menuItemArrayChild.Text = "Array";
this.menuItemArrayChild.Click += new System.EventHandler(this.menuItemArrayChild_Click);
//
// menuItemCaseChild
//
this.menuItemCaseChild.Index = 5;
this.menuItemCaseChild.Text = "Case";
this.menuItemCaseChild.Click += new System.EventHandler(this.menuItemCaseChild_Click);
//
// menuItemDimChild
//
this.menuItemDimChild.Index = 6;
this.menuItemDimChild.Text = "Dim";
this.menuItemDimChild.Click += new System.EventHandler(this.menuItemDimChild_Click);
//
// menuItemFile3
//
this.menuItemFile3.Index = 3;
this.menuItemFile3.Text = "-";
//
// menuItemDelete
//
this.menuItemDelete.Enabled = false;
this.menuItemDelete.Index = 4;
this.menuItemDelete.Text = "Delete";
this.menuItemDelete.Click += new System.EventHandler(this.menuItemDelete_Click);
//
// menuItemFile7
//
this.menuItemFile7.Index = 5;
this.menuItemFile7.Text = "-";
//
// menuItemBigEndian
//
this.menuItemBigEndian.Index = 6;
this.menuItemBigEndian.RadioCheck = true;
this.menuItemBigEndian.Text = "Big-Endian";
this.menuItemBigEndian.Click += new System.EventHandler(this.menuItemBigEndian_Click);
//
// menuItem1
//
this.menuItem1.Index = 7;
this.menuItem1.Text = "-";
//
// menuItemFontPlus
//
this.menuItemFontPlus.Index = 8;
this.menuItemFontPlus.Text = "Font +";
this.menuItemFontPlus.Click += new System.EventHandler(this.menuItemFontPlus_Click);
//
// menuItemFontMinus
//
this.menuItemFontMinus.Index = 9;
this.menuItemFontMinus.Text = "Font -";
this.menuItemFontMinus.Click += new System.EventHandler(this.menuItemFontMinus_Click);
//
// menuItemDefine
//
this.menuItemDefine.Index = 2;
this.menuItemDefine.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemDefineStruct,
this.menuItemDefineUnion,
this.menuItemDefineArray,
this.menuItem2,
this.menuItemImport});
this.menuItemDefine.Text = "&Define";
//
// menuItemDefineStruct
//
this.menuItemDefineStruct.Index = 0;
this.menuItemDefineStruct.Text = "struct";
this.menuItemDefineStruct.Click += new System.EventHandler(this.menuItemDefineStruct_Click);
//
// menuItemDefineUnion
//
this.menuItemDefineUnion.Index = 1;
this.menuItemDefineUnion.Text = "union";
this.menuItemDefineUnion.Click += new System.EventHandler(this.menuItemDefineUnion_Click);
//
// menuItemDefineArray
//
this.menuItemDefineArray.Index = 2;
this.menuItemDefineArray.Text = "array";
this.menuItemDefineArray.Click += new System.EventHandler(this.menuItemDefineArray_Click);
//
// menuItem2
//
this.menuItem2.Index = 3;
this.menuItem2.Text = "-";
//
// menuItemImport
//
this.menuItemImport.Index = 4;
this.menuItemImport.Text = "Import";
this.menuItemImport.Click += new System.EventHandler(this.menuItemImport_Click);
//
// menuItemUtility
//
this.menuItemUtility.Index = 3;
this.menuItemUtility.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemBrowse,
this.menuItemValidate});
this.menuItemUtility.Text = "&Utility";
//
// menuItemBrowse
//
this.menuItemBrowse.Index = 0;
this.menuItemBrowse.Text = "View in Browser";
this.menuItemBrowse.Click += new System.EventHandler(this.menuItemBrowse_Click);
//
// menuItemValidate
//
this.menuItemValidate.Index = 1;
this.menuItemValidate.Text = "&Validate a Document";
this.menuItemValidate.Click += new System.EventHandler(this.menuItemValidate_Click);
//
// menuItemHelp
//
this.menuItemHelp.Index = 4;
this.menuItemHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemDocument,
this.menuItemSchema,
this.menuItemSave0,
this.menuItemAboutMe});
this.menuItemHelp.Text = "&Help";
//
// menuItemDocument
//
this.menuItemDocument.Index = 0;
this.menuItemDocument.Text = "Documentation";
this.menuItemDocument.Click += new System.EventHandler(this.menuItemDocument_Click);
//
// menuItemSchema
//
this.menuItemSchema.Index = 1;
this.menuItemSchema.Text = "BinX Schema";
this.menuItemSchema.Click += new System.EventHandler(this.menuItemSchema_Click);
//
// menuItemSave0
//
this.menuItemSave0.Index = 2;
this.menuItemSave0.Text = "-";
//
// menuItemAboutMe
//
this.menuItemAboutMe.Index = 3;
this.menuItemAboutMe.Text = "About me";
this.menuItemAboutMe.Click += new System.EventHandler(this.menuItemAboutMe_Click);
//
// treeView1
//
this.treeView1.Dock = System.Windows.Forms.DockStyle.Left;
this.treeView1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.treeView1.ImageIndex = 1;
this.treeView1.ImageList = this.imageListNodeIcons;
this.treeView1.Location = new System.Drawing.Point(0, 29);
this.treeView1.Name = "treeView1";
this.treeView1.Nodes.AddRange(new System.Windows.Forms.TreeNode[] {
new System.Windows.Forms.TreeNode("BinX Document")});
this.treeView1.SelectedImageIndex = 1;
this.treeView1.ShowRootLines = false;
this.treeView1.Size = new System.Drawing.Size(552, 536);
this.treeView1.TabIndex = 6;
this.treeView1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.treeView1_MouseDown);
this.treeView1.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect);
//
// imageListNodeIcons
//
this.imageListNodeIcons.ImageSize = new System.Drawing.Size(16, 16);
this.imageListNodeIcons.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageListNodeIcons.ImageStream")));
this.imageListNodeIcons.TransparentColor = System.Drawing.Color.Transparent;
//
// splitter1
//
this.splitter1.Location = new System.Drawing.Point(552, 29);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(4, 536);
this.splitter1.TabIndex = 5;
this.splitter1.TabStop = false;
this.splitter1.SplitterMoved += new System.Windows.Forms.SplitterEventHandler(this.splitter1_SplitterMoved);
//
// listView1
//
this.listView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.listView1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.listView1.FullRowSelect = true;
this.listView1.GridLines = true;
this.listView1.LabelWrap = false;
this.listView1.Location = new System.Drawing.Point(556, 29);
this.listView1.MultiSelect = false;
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(196, 536);
this.listView1.TabIndex = 4;
this.listView1.View = System.Windows.Forms.View.Details;
this.listView1.Resize += new System.EventHandler(this.listView1_Resize);
this.listView1.PropertyUpdateHandler += new BinxEd.PropertyView.PropertyUpdateEvent(this.listView1_PropertyUpdateHandler);
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(752, 581);
this.Controls.Add(this.listView1);
this.Controls.Add(this.splitter1);
this.Controls.Add(this.treeView1);
this.Controls.Add(this.statusBar1);
this.Controls.Add(this.toolBar1);
this.Menu = this.mainMenu1;
this.Name = "MainForm";
this.Text = "BinX Editor 1.0";
this.Resize += new System.EventHandler(this.MainForm_Resize);
this.Closing += new System.ComponentModel.CancelEventHandler(this.MainForm_Closing);
this.Load += new System.EventHandler(this.MainForm_Load);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new MainForm());
}
private void MainForm_Load(object sender, System.EventArgs e)
{
//add context menu for treeviews
tv1Menu = new ContextMenu();
controller_.initializeTree(treeView1.TopNode);
}
/// <summary>
/// File->Exit menu.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItemExit_Click(object sender, System.EventArgs e)
{
this.Close();
}
/// <summary>
/// Main window closing event handler
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (controller_.isDocumentModified())
{
DialogResult r = MessageBox.Show(this,"Save file before exit?","Warning", MessageBoxButtons.YesNo);
if (r == DialogResult.Yes)
{
if (saveFileDialog1.ShowDialog(this)==DialogResult.OK)
{
controller_.saveDocument(saveFileDialog1.FileName, false);
}
}
}
}
/// <summary>
/// File->New menu
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItemNew_Click(object sender, System.EventArgs e)
{
if (controller_.isDocumentModified())
{
DialogResult r = MessageBox.Show(this, "Save file before open another one?", "Warning", MessageBoxButtons.YesNo);
if (r == DialogResult.Yes)
{
if (saveFileDialog1.ShowDialog(this)==DialogResult.OK)
{
controller_.saveDocument(saveFileDialog1.FileName, false);
}
}
}
controller_.clearData();
controller_.initializeTree(treeView1.TopNode);
this.Text = "BinX Editor 1.0";
}
/// <summary>
/// File->Open menu.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItemOpen_Click(object sender, System.EventArgs e)
{
if (controller_.isDocumentModified())
{
DialogResult r = MessageBox.Show(this, "Save file before open another one?", "Warning", MessageBoxButtons.YesNo);
if (r == DialogResult.Yes)
{
if (saveFileDialog1.ShowDialog(this)==DialogResult.OK)
{
controller_.saveDocument(saveFileDialog1.FileName, false);
}
}
}
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
Cursor.Current = Cursors.WaitCursor;
controller_.loadDocument(openFileDialog1.FileName);
controller_.populateDataTree(treeView1.TopNode);
menuItemBigEndian.Checked = controller_.isBigEndian();
Cursor.Current = Cursors.Default;
this.Text = "BinX Editor 1.0 - " + openFileDialog1.FileName;
}
}
/// <summary>
/// File->Save menu.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItemSave_Click(object sender, System.EventArgs e)
{
if (controller_.requireFileName())
{
menuItemSaveAs_Click(sender, e);
}
else
{
controller_.saveDocument();
}
}
/// <summary>
/// File->Save As menu.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItemSaveAs_Click(object sender, System.EventArgs e)
{
if (saveFileDialog1.ShowDialog(this)==DialogResult.OK)
{
controller_.saveDocument(saveFileDialog1.FileName, true);
this.Text = "BinX Editor 1.0 - " + saveFileDialog1.FileName;
((DataNode)treeView1.TopNode.LastNode).updateText();
}
}
/// <summary>
/// Toolbar button click event handler
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
{
if (e.Button.Tag.Equals("NEW"))
{
menuItemNew_Click(sender, e);
}
else if (e.Button.Tag.Equals("OPEN"))
{
menuItemOpen_Click(sender, e);
}
else if (e.Button.Tag.Equals("SAVE"))
{
menuItemSave_Click(sender, e);
}
else if (e.Button.Tag.Equals("DELETE"))
{
menuItemDelete_Click(sender, e);
}
else if (e.Button.Tag.Equals("FONT+"))
{
menuItemFontPlus_Click(sender, e);
}
else if (e.Button.Tag.Equals("FONT-"))
{
menuItemFontMinus_Click(sender, e);
}
else if (e.Button.Tag.Equals("BROWSE"))
{
menuItemBrowse_Click(sender, e);
}
else if (e.Button.Tag.Equals("VALIDATE"))
{
menuItemValidate_Click(sender, e);
}
else if (e.Button.Tag.Equals("IMPORT"))
{
menuItemImport_Click(sender, e);
}
}
/// <summary>
/// Mouse down event on treeview1 for assigning correct context menu
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void treeView1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
this.treeView1.ContextMenu = null;
targetNode_ = treeView1.GetNodeAt(e.X, e.Y);
if (targetNode_ != null && targetNode_ != treeView1.TopNode)
{
DataNode dn = (DataNode)targetNode_;
ArrayList siblings = dn.validSiblingTypes();
ArrayList children = dn.validChildTypes();
tv1Menu.MenuItems.Clear();
if (siblings != null && siblings.Count > 0 && !isArrayElement(dn) && !isCaseBody(dn))
{
MenuItem mnu = this.menuItemAddBefore.CloneMenu();
showMenuItemsToAdd(mnu, ref siblings);
tv1Menu.MenuItems.Add(mnu);
MenuItem mnu2 = this.menuItemAddAfter.CloneMenu();
showMenuItemsToAdd(mnu2, ref siblings);
tv1Menu.MenuItems.Add(mnu2);
}
if (children != null && children.Count > 0)
{
MenuItem mnu = this.menuItemAddChild.CloneMenu();
showMenuItemsToAdd(mnu, ref children);
tv1Menu.MenuItems.Add(mnu);
}
if (dn.canDelete())
{
MenuItem mnu = this.menuItemDelete.CloneMenu();
mnu.Enabled = true;
tv1Menu.MenuItems.Add(mnu);
}
if (tv1Menu.MenuItems.Count > 0)
{
this.treeView1.ContextMenu = tv1Menu;
}
}
}
//left-click will incur a treeView1_AfterSelect event which is handled elsewhere
}
/// <summary>
/// Define->struct menu
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItemDefineStruct_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)treeView1.TopNode.Nodes[0];
controller_.addStructTypeNode(node, node.Nodes.Count, true);
}
/// <summary>
/// Define->Union menu
/// </summary>
/// TODO: Add case else support and < void-0 > case body
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItemDefineUnion_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)treeView1.TopNode.Nodes[0];
controller_.addUnionTypeNode(node, node.Nodes.Count, true);
}
/// <summary>
/// Define->Array menu
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItemDefineArray_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)treeView1.TopNode.Nodes[0];
controller_.addArrayTypeNode(node, node.Nodes.Count, true);
}
/// <summary>
/// Locate the current active node. If right-clicked, targetNode_ is the interested node, otherwise, the SelectedNode.
/// targetNode_ must be cleared after use.
/// </summary>
/// <returns></returns>
private TreeNode GetActiveNode()
{
TreeNode thisNode = (targetNode_ != null)?targetNode_:treeView1.SelectedNode;
targetNode_ = null;
return thisNode;
}
/// <summary>
/// Edit->Delete menu
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItemDelete_Click(object sender, System.EventArgs e)
{
TreeNode tn = GetActiveNode();
if (tn != null)
{
controller_.deleteNode((DataNode)tn);
}
}
/// <summary>
/// Edit->Big-Endian menu as a check button.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItemBigEndian_Click(object sender, System.EventArgs e)
{
menuItemBigEndian.Checked = !menuItemBigEndian.Checked;
controller_.setBigEndian( menuItemBigEndian.Checked );
treeView1.TopNode.Nodes[1].Text = controller_.getDatasetNodeText();
}
/// <summary>
/// Help->About menu
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItemAboutMe_Click(object sender, System.EventArgs e)
{
FormAbout fa = new FormAbout();
fa.ShowDialog();
}
/// <summary>
/// Make a valid path.
/// </summary>
/// <returns></returns>
private string GetApplicationPath()
{
string sPath = Application.StartupPath;
if (sPath.EndsWith("Debug"))
{
sPath = sPath.Substring(0, sPath.Length-6);
}
else if (sPath.EndsWith("Release"))
{
sPath = sPath.Substring(0, sPath.Length - 8);
}
if (sPath.EndsWith("bin"))
{
sPath = sPath.Substring(0, sPath.Length-4);
}
return sPath;
}
/// <summary>
/// Help->Documentation menu
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItemDocument_Click(object sender, System.EventArgs e)
{
System.Diagnostics.Process.Start("IExplore.exe", GetApplicationPath() + "\\help.htm");
}
/// <summary>
/// Help->BinX schema menu
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItemSchema_Click(object sender, System.EventArgs e)
{
System.Diagnostics.Process.Start("IExplore.exe", GetApplicationPath() + "\\binx.xsd");
}
/// <summary>
/// Utility->Validate menu
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItemValidate_Click(object sender, System.EventArgs e)
{
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
Cursor.Current = Cursors.WaitCursor;
Validator.Validate(GetApplicationPath()+"\\binx.xsd", openFileDialog1.FileName);
Cursor.Current = Cursors.Default;
}
}
/// <summary>
/// Utility->View in browser
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItemBrowse_Click(object sender, System.EventArgs e)
{
if (controller_.isDocumentEmpty())
{
MessageBox.Show(this, "Document is empty");
return;
}
if (controller_.isDocumentModified())
{
menuItemSave_Click(sender, e); //save the document first
}
System.Diagnostics.Process.Start("IExplore.exe", controller_.getDocumentFilePath());
}
/// <summary>
/// Set related menu items visible according to strings in the array list.
/// </summary>
/// <remarks>If items contains 'any' then all data types apply, else only 'define','dim', and 'case' nodes are supported.</remarks>
/// <param name="baseMenu"></param>
/// <param name="items"></param>
private void showMenuItemsToAdd(MenuItem baseMenu, ref ArrayList items)
{
// defineMode_ = false;
baseMenu.Enabled = true;
if (items[0].Equals("any"))
{
for (int i=0; i<5; i++)
{
baseMenu.MenuItems[i].Visible = true;
}
baseMenu.MenuItems[5].Visible = false;
if (baseMenu.MenuItems.Count > 6)
baseMenu.MenuItems[6].Visible = false;
}
else if (items[0].Equals("define"))
{
// defineMode_ = true;
baseMenu.MenuItems[0].Visible = baseMenu.MenuItems[1].Visible = false;
for (int i=2; i<5; i++)
{
baseMenu.MenuItems[i].Visible = true;
}
baseMenu.MenuItems[5].Visible = false;
if (baseMenu.MenuItems.Count > 6)
baseMenu.MenuItems[6].Visible = false;
}
else if (items[0].Equals("dim"))
{
for (int i=0; i<6; i++)
baseMenu.MenuItems[i].Visible = false;
baseMenu.MenuItems[6].Visible = true;
}
else if (items[0].Equals("case"))
{
for (int i=0; i<baseMenu.MenuItems.Count; i++)
baseMenu.MenuItems[i].Visible = false;
baseMenu.MenuItems[5].Visible = true;
}
}
/// <summary>
/// Test whether the given node is an element of an array node.
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
private bool isArrayElement(DataNode node)
{
if (!node.Parent.Equals(treeView1.TopNode))
{
AbstractNode parent = ((DataNode)node.Parent).getDataNode();
if (parent.GetType().Equals(typeof(ArrayNode)))
{
return true;
}
else if (parent.GetType().Equals(typeof(DefineTypeNode)))
{
if (((DefineTypeNode)parent).getBaseType().GetType().Equals(typeof(ArrayNode)))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Test whether the given node is a case body node of a case node.
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
private bool isCaseBody(DataNode node)
{
if (!node.Parent.Equals(treeView1.TopNode))
{
AbstractNode parent = ((DataNode)node.Parent).getDataNode();
if (parent.GetType().Equals(typeof(CaseNode)))
{
return true;
}
}
return false;
}
/// <summary>
/// After a node is selected (left click on it), update the menu items.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void treeView1_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
if (e.Node.Equals(treeView1.TopNode))
{
menuItemAddBefore.Enabled = false;
menuItemAddAfter.Enabled = false;
menuItemAddChild.Enabled = false;
menuItemDelete.Enabled = toolBarButtonDelete.Enabled = false;
listView1.Items.Clear();
}
else
{
DataNode dn = (DataNode)e.Node;
menuItemDelete.Enabled = toolBarButtonDelete.Enabled = dn.canDelete();
ArrayList siblings = dn.validSiblingTypes();
if (siblings != null && siblings.Count > 0 && !isArrayElement(dn) && !isCaseBody(dn))
{
showMenuItemsToAdd(menuItemAddBefore, ref siblings);
showMenuItemsToAdd(menuItemAddAfter, ref siblings);
}
else
{
menuItemAddBefore.Enabled = false;
menuItemAddAfter.Enabled = false;
}
ArrayList children = dn.validChildTypes();
if (children != null && children.Count > 0)
{
showMenuItemsToAdd(menuItemAddChild, ref children);
}
else
{
menuItemAddChild.Enabled = false;
}
listView1.setProperties(dn.getProperties());
}
}
private void menuItemPrimitiveBefore_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)GetActiveNode();
DataNode parent = (DataNode)node.Parent;
controller_.addPrimitiveNode(parent, parent.Nodes.IndexOf(node));
}
private void menuItemPrimitiveAfter_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)GetActiveNode();
DataNode parent = (DataNode)node.Parent;
controller_.addPrimitiveNode(parent, parent.Nodes.IndexOf(node)+1);
}
private void menuItemPrimitiveChild_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)GetActiveNode();
controller_.addPrimitiveNode(node, node.Nodes.Count);
node.Expand();
}
private void menuItemDefinedBefore_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)GetActiveNode();
DataNode parent = (DataNode)node.Parent;
controller_.addUseTypeNode(parent, parent.Nodes.IndexOf(node));
}
private void menuItemDefinedAfter_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)GetActiveNode();
DataNode parent = (DataNode)node.Parent;
controller_.addUseTypeNode(parent, parent.Nodes.IndexOf(node)+1);
}
private void menuItemDefinedChild_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)GetActiveNode();
controller_.addUseTypeNode(node, node.Nodes.Count);
node.Expand();
}
private void menuItemStructBefore_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)GetActiveNode();
DataNode parent = (DataNode)node.Parent;
controller_.addStructTypeNode(parent, parent.Nodes.IndexOf(node), parent.Equals(treeView1.TopNode.Nodes[0]));
}
private void menuItemStructAfter_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)GetActiveNode();
DataNode parent = (DataNode)node.Parent;
controller_.addStructTypeNode(parent, parent.Nodes.IndexOf(node)+1, parent.Equals(treeView1.TopNode.Nodes[0]));
}
private void menuItemStructChild_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)GetActiveNode();
controller_.addStructTypeNode(node, node.Nodes.Count, node.Equals(treeView1.TopNode.Nodes[0]));
}
private void menuItemUnionBefore_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)GetActiveNode();
DataNode parent = (DataNode)node.Parent;
controller_.addUnionTypeNode(parent, parent.Nodes.IndexOf(node), parent.Equals(treeView1.TopNode.Nodes[0]));
}
private void menuItemUnionAfter_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)GetActiveNode();
DataNode parent = (DataNode)node.Parent;
controller_.addUnionTypeNode(parent, parent.Nodes.IndexOf(node)+1, parent.Equals(treeView1.TopNode.Nodes[0]));
}
private void menuItemUnionChild_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)GetActiveNode();
controller_.addUnionTypeNode(node, node.Nodes.Count, node.Equals(treeView1.TopNode.Nodes[0]));
}
private void menuItemArrayBefore_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)GetActiveNode();
DataNode parent = (DataNode)node.Parent;
controller_.addArrayTypeNode(parent, parent.Nodes.IndexOf(node), parent.Equals(treeView1.TopNode.Nodes[0]));
}
private void menuItemArrayAfter_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)GetActiveNode();
DataNode parent = (DataNode)node.Parent;
controller_.addArrayTypeNode(parent, parent.Nodes.IndexOf(node)+1, parent.Equals(treeView1.TopNode.Nodes[0]));
}
private void menuItemArrayChild_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)GetActiveNode();
controller_.addArrayTypeNode(node, node.Nodes.Count, node.Equals(treeView1.TopNode.Nodes[0]));
}
private void menuItemCaseBefore_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)GetActiveNode();
DataNode parent = (DataNode)node.Parent;
controller_.addCaseNode(parent, parent.Nodes.IndexOf(node));
}
private void menuItemCaseAfter_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)GetActiveNode();
DataNode parent = (DataNode)node.Parent;
controller_.addCaseNode(parent, parent.Nodes.IndexOf(node)+1);
}
private void menuItemCaseChild_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)GetActiveNode();
controller_.addCaseNode(node, node.Nodes.Count);
}
private void menuItemDimChild_Click(object sender, System.EventArgs e)
{
DataNode node = (DataNode)GetActiveNode();
controller_.addDimNode(node, node.Nodes.Count);
}
/// <summary>
/// Make the tree view font larger until 18pt.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItemFontPlus_Click(object sender, System.EventArgs e)
{
if (treeView1.Font.Size < 18.0)
{
treeView1.Font = new Font(treeView1.Font.Name, treeView1.Font.Size + 1.0f);
}
}
/// <summary>
/// Make the tree view font smaller until 9pt.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItemFontMinus_Click(object sender, System.EventArgs e)
{
if (treeView1.Font.Size > 9.0)
{
treeView1.Font = new Font(treeView1.Font.FontFamily, treeView1.Font.Size - 1.0f);
}
}
/// <summary>
/// Import only the definitions from an external BinX document, and the duplicated types are ignored.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItemImport_Click(object sender, System.EventArgs e)
{
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
Cursor.Current = Cursors.WaitCursor;
controller_.importDefinitions(openFileDialog1.FileName);
treeView1.BeginUpdate();
controller_.populateDataTree(treeView1.TopNode);
treeView1.EndUpdate();
Cursor.Current = Cursors.Default;
}
}
/// <summary>
/// Catch this event to adjust the property columns after the property view size is changed.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listView1_Resize(object sender, System.EventArgs e)
{
listView1.ResizeView(listView1.Size);
}
/// <summary>
/// Called by PropertyView when update of properties occurs.
/// </summary>
/// <param name="propertyName"></param>
/// <param name="propertyValue"></param>
private void listView1_PropertyUpdateHandler(string propertyName, string propertyValue)
{
Console.WriteLine(":" + propertyName + "," + propertyValue);
DataNode node = (DataNode)treeView1.SelectedNode;
if (node != null)
{
node.setProperty(propertyName, propertyValue);
node.updateText();
if (propertyName.Equals("Array Type"))
{
((DataNode)node.LastNode).updateText();
}
}
}
/// <summary>
/// Catch this event to make sure the right-hand pane (property view) size remain the same after resizing the main window.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MainForm_Resize(object sender, System.EventArgs e)
{
splitter1.SplitPosition = this.Width - RightPaneWidth_;
}
/// <summary>
/// Catch this event to remember the new property view size after split bar is moved.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void splitter1_SplitterMoved(object sender, System.Windows.Forms.SplitterEventArgs e)
{
RightPaneWidth_ = this.Width - splitter1.SplitPosition;
}
}
}
| |
#if NON_UNITY || !NET_STANDARD_2_0
using Grpc.Core;
using MagicOnion.Server.Hubs;
using MagicOnion.Utils;
using MessagePack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using System.Threading.Tasks;
namespace MagicOnion.Client
{
#if ENABLE_SAVE_ASSEMBLY
public
#else
internal
#endif
static class StreamingHubClientAssemblyHolder
{
public const string ModuleName = "MagicOnion.Client.StreamingHubClient";
readonly static DynamicAssembly assembly;
internal static DynamicAssembly Assembly { get { return assembly; } }
static StreamingHubClientAssemblyHolder()
{
assembly = new DynamicAssembly(ModuleName);
}
#if ENABLE_SAVE_ASSEMBLY
public static AssemblyBuilder Save()
{
return assembly.Save();
}
#endif
}
#if ENABLE_SAVE_ASSEMBLY
public
#else
internal
#endif
static class StreamingHubClientBuilder<TStreamingHub, TReceiver>
{
public static readonly Type ClientType;
// static readonly Type ClientFireAndForgetType;
static readonly Type bytesMethod = typeof(Method<,>).MakeGenericType(new[] { typeof(byte[]), typeof(byte[]) });
static readonly FieldInfo throughMarshaller = typeof(MagicOnionMarshallers).GetField("ThroughMarshaller", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
static readonly ConstructorInfo notSupportedException = typeof(NotSupportedException).GetConstructor(Type.EmptyTypes);
static readonly MethodInfo callMessagePackDesrialize = typeof(MessagePackSerializer).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)
.First(x => x.Name == "Deserialize" && x.GetParameters().Length == 3 && x.GetParameters()[0].ParameterType == typeof(ReadOnlyMemory<byte>) && x.GetParameters()[1].ParameterType == typeof(MessagePackSerializerOptions));
static readonly MethodInfo callCancellationTokenNone = typeof(CancellationToken).GetProperty("None", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static).GetGetMethod();
static readonly PropertyInfo completedTask = typeof(Task).GetProperty("CompletedTask", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
static StreamingHubClientBuilder()
{
var t = typeof(TStreamingHub);
var ti = t.GetTypeInfo();
if (!ti.IsInterface) throw new Exception("Client Proxy only allows interface. Type:" + ti.Name);
var asm = StreamingHubClientAssemblyHolder.Assembly;
var methodDefinitions = SearchDefinitions(t);
var parentType = typeof(StreamingHubClientBase<,>).MakeGenericType(typeof(TStreamingHub), typeof(TReceiver));
var typeBuilder = asm.DefineType($"{DynamicClientAssemblyHolder.ModuleName}.{ti.FullName}StreamingHubClient_{Guid.NewGuid().ToString()}", TypeAttributes.Public, parentType, new Type[] { t });
VerifyMethodDefinitions(methodDefinitions);
{
// Create FireAndForgetType first as nested type.
var typeBuilderEx = typeBuilder.DefineNestedType($"FireAndForgetClient", TypeAttributes.NestedPrivate, typeof(object), new Type[] { t });
var tuple = DefineFireAndForgetConstructor(typeBuilderEx, typeBuilder);
var fireAndForgetClientCtor = tuple.Item1;
var fireAndForgetField = tuple.Item2;
DefineMethodsFireAndForget(typeBuilderEx, t, fireAndForgetField, typeBuilder, methodDefinitions);
typeBuilderEx.CreateTypeInfo(); // ok to create nested type.
var methodField = DefineStaticConstructor(typeBuilder, t);
var clientField = DefineConstructor(typeBuilder, t, typeof(TReceiver), fireAndForgetClientCtor);
DefineMethods(typeBuilder, t, typeof(TReceiver), methodField, clientField, methodDefinitions);
}
ClientType = typeBuilder.CreateTypeInfo().AsType();
}
static MethodDefinition[] SearchDefinitions(Type interfaceType)
{
return interfaceType
.GetInterfaces()
.Concat(new[] { interfaceType })
.SelectMany(x => x.GetMethods())
.Where(x =>
{
var methodInfo = x;
if (methodInfo.IsSpecialName && (methodInfo.Name.StartsWith("set_") || methodInfo.Name.StartsWith("get_"))) return false;
if (methodInfo.GetCustomAttribute<IgnoreAttribute>(false) != null) return false; // ignore
var methodName = methodInfo.Name;
if (methodName == "Equals"
|| methodName == "GetHashCode"
|| methodName == "GetType"
|| methodName == "ToString"
|| methodName == "DisposeAsync"
|| methodName == "WaitForDisconnect"
|| methodName == "FireAndForget"
)
{
return false;
}
return true;
})
.Where(x => !x.IsSpecialName)
.Select(x => new MethodDefinition
{
ServiceType = interfaceType,
MethodInfo = x,
})
.ToArray();
}
static void VerifyMethodDefinitions(MethodDefinition[] definitions)
{
var map = new Dictionary<int, MethodDefinition>(definitions.Length);
foreach (var item in definitions)
{
var methodId = item.MethodInfo.GetCustomAttribute<MethodIdAttribute>()?.MethodId ?? FNV1A32.GetHashCode(item.MethodInfo.Name);
if (map.ContainsKey(methodId))
{
throw new Exception($"TStreamingHub does not allows duplicate methodId(hash code). Please change name or use MethodIdAttribute. {map[methodId].MethodInfo.Name} and {item.MethodInfo.Name}");
}
map.Add(methodId, item);
if (!(item.MethodInfo.ReturnType.IsGenericType && item.MethodInfo.ReturnType.GetGenericTypeDefinition() == typeof(Task<>))
&& item.MethodInfo.ReturnType != typeof(Task))
{
throw new Exception($"Invalid definition, TStreamingHub's return type must only be `Task` or `Task<T>`. {item.MethodInfo.Name}.");
}
item.MethodId = methodId;
if (item.RequestType == null)
{
item.RequestType = MagicOnionMarshallers.CreateRequestType(item.MethodInfo.GetParameters());
}
}
}
static FieldInfo DefineStaticConstructor(TypeBuilder typeBuilder, Type interfaceType)
{
// static readonly Method<byte[], byte[]> method = new Method<byte[], byte[]>(MethodType.DuplexStreaming, "IFoo", "Connect", MagicOnionMarshallers.ThroughMarshaller, MagicOnionMarshallers.ThroughMarshaller);
var field = typeBuilder.DefineField("method", bytesMethod, FieldAttributes.Private | FieldAttributes.Static);
var cctor = typeBuilder.DefineConstructor(MethodAttributes.Static, CallingConventions.Standard, Type.EmptyTypes);
var il = cctor.GetILGenerator();
il.EmitLdc_I4((int)MethodType.DuplexStreaming);
il.Emit(OpCodes.Ldstr, interfaceType.Name);
il.Emit(OpCodes.Ldstr, "Connect");
il.Emit(OpCodes.Ldsfld, throughMarshaller);
il.Emit(OpCodes.Ldsfld, throughMarshaller);
il.Emit(OpCodes.Newobj, bytesMethod.GetConstructors()[0]);
il.Emit(OpCodes.Stsfld, field);
il.Emit(OpCodes.Ret);
return field;
}
static FieldInfo DefineConstructor(TypeBuilder typeBuilder, Type interfaceType, Type receiverType, ConstructorInfo fireAndForgetClientCtor)
{
// .ctor(CallInvoker callInvoker, string host, CallOptions option, MessagePackSerializerOptions resolver, IMagicOnionClientLogger logger) :base(...)
{
var argTypes = new[] { typeof(CallInvoker), typeof(string), typeof(CallOptions), typeof(MessagePackSerializerOptions), typeof(IMagicOnionClientLogger) };
var ctor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, argTypes);
var il = ctor.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Ldarg_3);
il.Emit(OpCodes.Ldarg_S, (byte)4);
il.Emit(OpCodes.Ldarg_S, (byte)5);
il.Emit(OpCodes.Call, typeBuilder.BaseType
.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).First());
// { this.fireAndForgetClient = new FireAndForgetClient(this); }
var clientField = typeBuilder.DefineField("fireAndForgetClient", fireAndForgetClientCtor.DeclaringType, FieldAttributes.Private);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Newobj, fireAndForgetClientCtor);
il.Emit(OpCodes.Stfld, clientField);
il.Emit(OpCodes.Ret);
return clientField;
}
}
static Tuple<ConstructorBuilder, FieldBuilder> DefineFireAndForgetConstructor(TypeBuilder typeBuilder, Type parentClientType)
{
// .ctor(Parent client) { this.client = client }
{
var argTypes = new[] { parentClientType };
var ctor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, argTypes);
var clientField = typeBuilder.DefineField("client", parentClientType, FieldAttributes.Private);
var il = ctor.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, typeof(object).GetConstructors().First());
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Stfld, clientField);
il.Emit(OpCodes.Ret);
return Tuple.Create(ctor, clientField);
}
}
static void DefineMethods(TypeBuilder typeBuilder, Type interfaceType, Type receiverType, FieldInfo methodField, FieldInfo clientField, MethodDefinition[] definitions)
{
var baseType = typeof(StreamingHubClientBase<,>).MakeGenericType(interfaceType, receiverType);
var serializerOptionsField = baseType.GetField("serializerOptions", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
var receiverField = baseType.GetField("receiver", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
// protected abstract Method<byte[], byte[]> DuplexStreamingAsyncMethod { get; }
{
var method = typeBuilder.DefineMethod("get_DuplexStreamingAsyncMethod", MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual,
bytesMethod,
Type.EmptyTypes);
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, methodField);
il.Emit(OpCodes.Ret);
}
{
// Task DisposeAsync();
{
var method = typeBuilder.DefineMethod("DisposeAsync", MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual,
typeof(Task), Type.EmptyTypes);
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, baseType.GetMethod("DisposeAsync", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance));
il.Emit(OpCodes.Ret);
}
// Task WaitForDisconnect();
{
var method = typeBuilder.DefineMethod("WaitForDisconnect", MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual,
typeof(Task), Type.EmptyTypes);
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, baseType.GetMethod("WaitForDisconnect", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance));
il.Emit(OpCodes.Ret);
}
// TSelf FireAndForget();
{
var method = typeBuilder.DefineMethod("FireAndForget", MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual,
interfaceType, Type.EmptyTypes);
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, clientField);
il.Emit(OpCodes.Ret);
}
}
// receiver types borrow from DynamicBroadcastBuilder
{
// protected abstract void OnResponseEvent(int methodId, object taskCompletionSource, ArraySegment<byte> data);
{
var method = typeBuilder.DefineMethod("OnResponseEvent", MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual,
null, new[] { typeof(int), typeof(object), typeof(ArraySegment<byte>) });
var il = method.GetILGenerator();
var labels = definitions
.Select(x => new { def = x, label = il.DefineLabel() })
.ToArray();
foreach (var item in labels)
{
// if( == ) goto ...
il.Emit(OpCodes.Ldarg_1);
il.EmitLdc_I4(item.def.MethodId);
il.Emit(OpCodes.Beq, item.label);
}
// else
il.Emit(OpCodes.Ret);
foreach (var item in labels)
{
// var result = LZ4MessagePackSerializer.Deserialize<T>(data, resolver);
// ((TaskCompletionSource<T>)taskCompletionSource).TrySetResult(result);
// => ((TaskCompletionSource<T>)taskCompletionSource).TrySetResult(LZ4MessagePackSerializer.Deserialize<T>(data, resolver));
Type responseType;
Type tcsType;
if (item.def.MethodInfo.ReturnType == typeof(Task))
{
// Task methods uses TaskCompletionSource<Nil>
responseType = typeof(Nil);
tcsType = typeof(TaskCompletionSource<Nil>);
}
else
{
responseType = item.def.MethodInfo.ReturnType.GetGenericArguments()[0];
tcsType = typeof(TaskCompletionSource<>).MakeGenericType(responseType);
}
il.MarkLabel(item.label);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Castclass, tcsType);
il.Emit(OpCodes.Ldarg_3);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, serializerOptionsField);
il.Emit(OpCodes.Call, callCancellationTokenNone);
il.Emit(OpCodes.Call, callMessagePackDesrialize.MakeGenericMethod(responseType));
il.Emit(OpCodes.Callvirt, tcsType.GetMethod("TrySetResult"));
il.Emit(OpCodes.Pop);
il.Emit(OpCodes.Ret);
}
}
// protected abstract void OnBroadcastEvent(int methodId, ArraySegment<byte> data);
{
var methodDefinitions = BroadcasterHelper.SearchDefinitions(receiverType);
BroadcasterHelper.VerifyMethodDefinitions(methodDefinitions);
var method = typeBuilder.DefineMethod("OnBroadcastEvent", MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual,
typeof(void), new[] { typeof(int), typeof(ArraySegment<byte>) });
var il = method.GetILGenerator();
var labels = methodDefinitions
.Select(x => new { def = x, label = il.DefineLabel() })
.ToArray();
foreach (var item in labels)
{
// if( == ) goto ...
il.Emit(OpCodes.Ldarg_1);
il.EmitLdc_I4(item.def.MethodId);
il.Emit(OpCodes.Beq, item.label);
}
// else
il.Emit(OpCodes.Ret);
foreach (var item in labels)
{
il.MarkLabel(item.label);
// var result = LZ4MessagePackSerializer.Deserialize<DynamicArgumentTuple<int, string>>(data, resolver);
// return receiver.OnReceiveMessage(result.Item1, result.Item2);
var parameters = item.def.MethodInfo.GetParameters();
if (parameters.Length == 0)
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, receiverField);
il.Emit(OpCodes.Callvirt, item.def.MethodInfo);
il.Emit(OpCodes.Ret);
}
else if (parameters.Length == 1)
{
// TODO:fix emit
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, receiverField);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, serializerOptionsField);
il.Emit(OpCodes.Call, callCancellationTokenNone);
il.Emit(OpCodes.Call, callMessagePackDesrialize.MakeGenericMethod(parameters[0].ParameterType));
il.Emit(OpCodes.Callvirt, item.def.MethodInfo);
il.Emit(OpCodes.Ret);
}
else
{
// TODO:fix emit
var deserializeType = BroadcasterHelper.dynamicArgumentTupleTypes[parameters.Length - 2]
.MakeGenericType(parameters.Select(x => x.ParameterType).ToArray());
var lc = il.DeclareLocal(deserializeType);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, serializerOptionsField);
il.Emit(OpCodes.Call, callCancellationTokenNone);
il.Emit(OpCodes.Call, callMessagePackDesrialize.MakeGenericMethod(deserializeType));
il.Emit(OpCodes.Stloc, lc);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, receiverField);
for (int i = 0; i < parameters.Length; i++)
{
il.Emit(OpCodes.Ldloc, lc);
il.Emit(OpCodes.Ldfld, deserializeType.GetField("Item" + (i + 1)));
}
il.Emit(OpCodes.Callvirt, item.def.MethodInfo);
il.Emit(OpCodes.Ret);
}
}
}
}
// Proxy Methods
for (int i = 0; i < definitions.Length; i++)
{
var def = definitions[i];
var parameters = def.MethodInfo.GetParameters().Select(x => x.ParameterType).ToArray();
var method = typeBuilder.DefineMethod(def.MethodInfo.Name, MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual,
def.MethodInfo.ReturnType,
parameters);
var il = method.GetILGenerator();
// return WriteMessageAsync<T>(methodId, message);
// return WriteMessageWithResponseAsync<TReq, TRes>(methodId, message);
// this.***
il.Emit(OpCodes.Ldarg_0);
// arg1
il.EmitLdc_I4(def.MethodId);
// create request for arg2
for (int j = 0; j < parameters.Length; j++)
{
il.Emit(OpCodes.Ldarg, j + 1);
}
Type callType = null;
if (parameters.Length == 0)
{
// use Nil.
callType = typeof(Nil);
il.Emit(OpCodes.Ldsfld, typeof(Nil).GetField("Default"));
}
else if (parameters.Length == 1)
{
// already loaded parameter.
callType = parameters[0];
}
else
{
// call new DynamicArgumentTuple<T>
callType = def.RequestType;
il.Emit(OpCodes.Newobj, callType.GetConstructors().First());
}
if (def.MethodInfo.ReturnType == typeof(Task))
{
var mInfo = baseType.GetMethod("WriteMessageWithResponseAsync", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
il.Emit(OpCodes.Callvirt, mInfo.MakeGenericMethod(callType, typeof(Nil)));
}
else
{
var mInfo = baseType.GetMethod("WriteMessageWithResponseAsync", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
il.Emit(OpCodes.Callvirt, mInfo.MakeGenericMethod(callType, def.MethodInfo.ReturnType.GetGenericArguments()[0]));
}
il.Emit(OpCodes.Ret);
}
}
static void DefineMethodsFireAndForget(TypeBuilder typeBuilder, Type interfaceType, FieldInfo clientField, Type parentNestedType, MethodDefinition[] definitions)
{
{
// Task DisposeAsync();
{
var method = typeBuilder.DefineMethod("DisposeAsync", MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual,
typeof(Task), Type.EmptyTypes);
var il = method.GetILGenerator();
il.Emit(OpCodes.Newobj, notSupportedException);
il.Emit(OpCodes.Throw);
}
// Task WaitForDisconnect();
{
var method = typeBuilder.DefineMethod("WaitForDisconnect", MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual,
typeof(Task), Type.EmptyTypes);
var il = method.GetILGenerator();
il.Emit(OpCodes.Newobj, notSupportedException);
il.Emit(OpCodes.Throw);
}
// TSelf FireAndForget();
{
var method = typeBuilder.DefineMethod("FireAndForget", MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual,
interfaceType, Type.EmptyTypes);
var il = method.GetILGenerator();
il.Emit(OpCodes.Newobj, notSupportedException);
il.Emit(OpCodes.Throw);
}
}
// Proxy Methods
for (int i = 0; i < definitions.Length; i++)
{
var def = definitions[i];
var parameters = def.MethodInfo.GetParameters().Select(x => x.ParameterType).ToArray();
var method = typeBuilder.DefineMethod(def.MethodInfo.Name, MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual,
def.MethodInfo.ReturnType,
parameters);
var il = method.GetILGenerator();
// return client.WriteMessage***<T>(methodId, message);
// this.client.***
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, clientField);
// arg1
il.EmitLdc_I4(def.MethodId);
// create request for arg2
for (int j = 0; j < parameters.Length; j++)
{
il.Emit(OpCodes.Ldarg, j + 1);
}
Type callType = null;
if (parameters.Length == 0)
{
// use Nil.
callType = typeof(Nil);
il.Emit(OpCodes.Ldsfld, typeof(Nil).GetField("Default"));
}
else if (parameters.Length == 1)
{
// already loaded parameter.
callType = parameters[0];
}
else
{
// call new DynamicArgumentTuple<T>
callType = def.RequestType;
il.Emit(OpCodes.Newobj, callType.GetConstructors().First());
}
if (def.MethodInfo.ReturnType == typeof(Task))
{
var mInfo = parentNestedType.BaseType.GetMethod("WriteMessageAsync", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
il.Emit(OpCodes.Callvirt, mInfo.MakeGenericMethod(callType));
}
else
{
var mInfo = parentNestedType.BaseType.GetMethod("WriteMessageAsyncFireAndForget", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
il.Emit(OpCodes.Callvirt, mInfo.MakeGenericMethod(callType, def.MethodInfo.ReturnType.GetGenericArguments()[0]));
}
il.Emit(OpCodes.Ret);
}
}
class MethodDefinition
{
public string Path => ServiceType.Name + "/" + MethodInfo.Name;
public Type ServiceType;
public MethodInfo MethodInfo;
public int MethodId;
public Type RequestType;
}
}
}
#endif
| |
////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Autodesk, Inc. All rights reserved
// Written by Philippe Leefsma 2012 - ADN/Developer Technical Services
//
// 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.
////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace ListViewEmbeddedControls
{
public class ListViewEx : ListView
{
#region Interop-Defines
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wPar, IntPtr lPar);
// ListView messages
private const int LVM_FIRST = 0x1000;
private const int LVM_GETCOLUMNORDERARRAY = (LVM_FIRST + 59);
// Windows Messages
private const int WM_PAINT = 0x000F;
#endregion
/// <summary>
/// Structure to hold an embedded control's info
/// </summary>
private struct EmbeddedControl
{
public Control Control;
public int Column;
public int Row;
public DockStyle Dock;
public ListViewItem Item;
}
private ArrayList _embeddedControls = new ArrayList();
public ListViewEx() {}
/// <summary>
/// Retrieve the order in which columns appear
/// </summary>
/// <returns>Current display order of column indices</returns>
protected int[] GetColumnOrder()
{
IntPtr lPar = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * Columns.Count);
IntPtr res = SendMessage(Handle, LVM_GETCOLUMNORDERARRAY, new IntPtr(Columns.Count), lPar);
if (res.ToInt32() == 0) // Something went wrong
{
Marshal.FreeHGlobal(lPar);
return null;
}
int [] order = new int[Columns.Count];
Marshal.Copy(lPar, order, 0, Columns.Count);
Marshal.FreeHGlobal(lPar);
return order;
}
/// <summary>
/// Retrieve the bounds of a ListViewSubItem
/// </summary>
/// <param name="Item">The Item containing the SubItem</param>
/// <param name="SubItem">Index of the SubItem</param>
/// <returns>Subitem's bounds</returns>
protected Rectangle GetSubItemBounds(ListViewItem Item, int SubItem)
{
Rectangle subItemRect = Rectangle.Empty;
if (Item == null)
throw new ArgumentNullException("Item");
int[] order = GetColumnOrder();
if (order == null) // No Columns
return subItemRect;
if (SubItem >= order.Length)
throw new IndexOutOfRangeException("SubItem "+SubItem+" out of range");
// Retrieve the bounds of the entire ListViewItem (all subitems)
Rectangle lviBounds = Item.GetBounds(ItemBoundsPortion.Entire);
int subItemX = lviBounds.Left;
// Calculate the X position of the SubItem.
// Because the columns can be reordered we have to use Columns[order[i]] instead of Columns[i] !
ColumnHeader col;
int i;
for (i=0; i<order.Length; i++)
{
col = this.Columns[order[i]];
if (col.Index == SubItem)
break;
subItemX += col.Width;
}
subItemRect = new Rectangle(subItemX, lviBounds.Top, this.Columns[order[i]].Width, lviBounds.Height);
return subItemRect;
}
/// <summary>
/// Add a control to the ListView
/// </summary>
/// <param name="c">Control to be added</param>
/// <param name="col">Index of column</param>
/// <param name="row">Index of row</param>
public void AddEmbeddedControl(Control c, int col, int row)
{
AddEmbeddedControl(c,col,row,DockStyle.Fill);
}
/// <summary>
/// Add a control to the ListView
/// </summary>
/// <param name="c">Control to be added</param>
/// <param name="col">Index of column</param>
/// <param name="row">Index of row</param>
/// <param name="dock">Location and resize behavior of embedded control</param>
public void AddEmbeddedControl(Control c, int col, int row, DockStyle dock)
{
if (c==null)
throw new ArgumentNullException();
if (col>=Columns.Count || row>=Items.Count)
throw new ArgumentOutOfRangeException();
EmbeddedControl ec;
ec.Control = c;
ec.Column = col;
ec.Row = row;
ec.Dock = dock;
ec.Item = Items[row];
_embeddedControls.Add(ec);
// Add a Click event handler to select the ListView row when an embedded control is clicked
c.Click += new EventHandler(_embeddedControl_Click);
this.Controls.Add(c);
}
/// <summary>
/// Remove a control from the ListView
/// </summary>
/// <param name="c">Control to be removed</param>
public void RemoveEmbeddedControl(Control c)
{
if (c == null)
throw new ArgumentNullException();
for (int i=0; i<_embeddedControls.Count; i++)
{
EmbeddedControl ec = (EmbeddedControl)_embeddedControls[i];
if (ec.Control == c)
{
c.Click -= new EventHandler(_embeddedControl_Click);
this.Controls.Remove(c);
_embeddedControls.RemoveAt(i);
return;
}
}
throw new Exception("Control not found!");
}
/// <summary>
/// Retrieve the control embedded at a given location
/// </summary>
/// <param name="col">Index of Column</param>
/// <param name="row">Index of Row</param>
/// <returns>Control found at given location or null if none assigned.</returns>
public Control GetEmbeddedControl(int col, int row)
{
foreach (EmbeddedControl ec in _embeddedControls)
if (ec.Row == row && ec.Column == col)
return ec.Control;
return null;
}
[DefaultValue(View.LargeIcon)]
public new View View
{
get
{
return base.View;
}
set
{
// Embedded controls are rendered only when we're in Details mode
foreach (EmbeddedControl ec in _embeddedControls)
ec.Control.Visible = (value == View.Details);
base.View = value;
}
}
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_PAINT:
if (View != View.Details)
break;
if (this.View == View.Details && this.Columns.Count > 0)
this.Columns[this.Columns.Count - 1].Width = -2;
// Calculate the position of all embedded controls
foreach (EmbeddedControl ec in _embeddedControls)
{
Rectangle rc = this.GetSubItemBounds(ec.Item, ec.Column);
if ((this.HeaderStyle != ColumnHeaderStyle.None) &&
(rc.Top<this.Font.Height)) // Control overlaps ColumnHeader
{
ec.Control.Visible = false;
continue;
}
else
{
ec.Control.Visible = true;
}
switch (ec.Dock)
{
case DockStyle.Fill:
break;
case DockStyle.Top:
rc.Height = ec.Control.Height;
break;
case DockStyle.Left:
rc.Width = ec.Control.Width;
break;
case DockStyle.Bottom:
rc.Offset(0, rc.Height-ec.Control.Height);
rc.Height = ec.Control.Height;
break;
case DockStyle.Right:
rc.Offset(rc.Width-ec.Control.Width, 0);
rc.Width = ec.Control.Width;
break;
case DockStyle.None:
rc.Size = ec.Control.Size;
break;
}
// Set embedded control's bounds
ec.Control.Bounds = rc;
}
break;
}
base.WndProc (ref m);
}
private void _embeddedControl_Click(object sender, EventArgs e)
{
// When a control is clicked the ListViewItem holding it is selected
foreach (EmbeddedControl ec in _embeddedControls)
{
if (ec.Control == (Control)sender)
{
this.SelectedItems.Clear();
ec.Item.Selected = true;
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.AspNet.Identity;
using Microsoft.Data.Entity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using PartsUnlimited.Areas.Admin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace PartsUnlimited.Models
{
public static class SampleData
{
private static string AdminRoleSectionName = "AdminRole";
private static string DefaultAdminNameKey = "UserName";
private static string DefaultAdminPasswordKey = "Password";
public static async Task InitializePartsUnlimitedDatabaseAsync(IServiceProvider serviceProvider, bool createUser = true)
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var db = serviceScope.ServiceProvider.GetService<PartsUnlimitedContext>();
var productsRepository = serviceScope.ServiceProvider.GetService<IProductsRepository>();
bool dbNewlyCreated = await db.Database.EnsureCreatedAsync();
//Seeding a database using migrations is not yet supported. (https://github.com/aspnet/EntityFramework/issues/629)
//Add seed data, only if the tables are empty.
bool tablesEmpty = !db.Orders.Any() && !db.Categories.Any() && !db.Stores.Any();
if (dbNewlyCreated || tablesEmpty)
{
await InsertTestData(serviceProvider);
await CreateAdminUser(serviceProvider);
}
bool documentDBEmpty = !productsRepository.Set<Product>().ToList().Any();
if (documentDBEmpty)
{
await InsertDocumentDBTestData(serviceProvider);
}
}
}
private static async Task InsertDocumentDBTestData(IServiceProvider serviceProvider)
{
var db = serviceProvider.GetService<PartsUnlimitedContext>();
var categories = db.Set<Category>().ToList();
var products = GetProducts(categories).ToList();
var productsRepository = serviceProvider.GetService<IProductsRepository>();
foreach (var product in products)
{
await productsRepository.CreateOrUpdateAsync(product);
}
}
public static async Task InsertTestData(IServiceProvider serviceProvider)
{
var categories = GetCategories().ToList();
await AddOrUpdateAsync(serviceProvider, g => g.Name, categories);
var stores = GetStores().ToList();
await AddOrUpdateAsync(serviceProvider, a => a.Name, stores);
var products = GetProducts(categories).ToList();
var rainchecks = GetRainchecks(stores, products).ToList();
await AddOrUpdateAsync(serviceProvider, a => a.RaincheckId, rainchecks);
PopulateOrderHistory(serviceProvider, products);
}
private static async Task AddOrUpdateAsync<TEntity>(
IServiceProvider serviceProvider,
Func<TEntity, object> propertyToMatch, IEnumerable<TEntity> entities)
where TEntity : class
{
// Query in a separate context so that we can attach existing entities as modified
List<TEntity> existingData;
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var db = serviceScope.ServiceProvider.GetService<PartsUnlimitedContext>();
existingData = db.Set<TEntity>().ToList();
}
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var db = serviceScope.ServiceProvider.GetService<PartsUnlimitedContext>();
foreach (var item in entities)
{
db.Entry(item).State = existingData.Any(g => propertyToMatch(g).Equals(propertyToMatch(item)))
? EntityState.Modified
: EntityState.Added;
}
await db.SaveChangesAsync();
}
}
/// <summary>
/// Returns configuration section for AdminRole.
/// </summary>
/// <param name="serviceProvider"></param>
/// <returns></returns>
private static IConfigurationSection GetAdminRoleConfiguration(IServiceProvider serviceProvider)
{
var appEnv = serviceProvider.GetService<IApplicationEnvironment>();
var builder = new ConfigurationBuilder().SetBasePath(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddEnvironmentVariables();
var configuration = builder.Build();
return configuration.GetSection(AdminRoleSectionName);
}
/// <summary>
/// Creates a store manager user who can manage the inventory.
/// </summary>
/// <param name="serviceProvider"></param>
/// <returns></returns>
private static async Task CreateAdminUser(IServiceProvider serviceProvider)
{
IConfigurationSection configuration = GetAdminRoleConfiguration(serviceProvider);
UserManager<ApplicationUser> userManager = serviceProvider.GetService<UserManager<ApplicationUser>>();
var user = await userManager.FindByNameAsync(configuration[DefaultAdminNameKey]);
if (user == null)
{
user = new ApplicationUser { UserName = configuration[DefaultAdminNameKey] };
await userManager.CreateAsync(user, configuration[DefaultAdminPasswordKey]);
await userManager.AddClaimAsync(user, new Claim(AdminConstants.ManageStore.Name, AdminConstants.ManageStore.Allowed));
}
}
/// <summary>
/// Generate an enumeration of rainchecks. The random number generator uses a seed to ensure
/// that the sequence is consistent, but provides somewhat random looking data.
/// </summary>
public static IEnumerable<Raincheck> GetRainchecks(IEnumerable<Store> stores, IList<Product> products)
{
var random = new Random(1234);
foreach (var store in stores)
{
for (var i = 0; i < random.Next(1, 5); i++)
{
yield return new Raincheck
{
StoreId = store.StoreId,
Name = $"John Smith{random.Next()}",
Quantity = random.Next(1, 10),
ProductId = products[random.Next(0, products.Count)].ProductId,
SalePrice = Math.Round(100 * random.NextDouble(), 2)
};
}
}
}
public static IEnumerable<Store> GetStores()
{
return Enumerable.Range(1, 20).Select(id => new Store { Name = $"Store{id}" });
}
public static IEnumerable<Category> GetCategories()
{
yield return new Category { Name = "Brakes", Description = "Brakes description", ImageUrl = "product_brakes_disc.jpg" };
yield return new Category { Name = "Lighting", Description = "Lighting description", ImageUrl = "product_lighting_headlight.jpg" };
yield return new Category { Name = "Wheels & Tires", Description = "Wheels & Tires description", ImageUrl = "product_wheel_rim.jpg" };
yield return new Category { Name = "Batteries", Description = "Batteries description", ImageUrl = "product_batteries_basic-battery.jpg" };
yield return new Category { Name = "Oil", Description = "Oil description", ImageUrl = "product_oil_premium-oil.jpg" };
}
public static void PopulateOrderHistory(IServiceProvider serviceProvider, IEnumerable<Product> products)
{
var random = new Random(1234);
var recomendationCombinations = new[] {
new{ Transactions = new []{1, 3, 8}, Multiplier = 60 },
new{ Transactions = new []{2, 6}, Multiplier = 10 },
new{ Transactions = new []{4, 11}, Multiplier = 20 },
new{ Transactions = new []{5, 14}, Multiplier = 10 },
new{ Transactions = new []{6, 16, 18}, Multiplier = 20 },
new{ Transactions = new []{7, 17}, Multiplier = 25 },
new{ Transactions = new []{8, 1}, Multiplier = 5 },
new{ Transactions = new []{10, 17,9}, Multiplier = 15 },
new{ Transactions = new []{11, 5}, Multiplier = 15 },
new{ Transactions = new []{12, 8}, Multiplier = 5 },
new{ Transactions = new []{13, 15}, Multiplier = 50 },
new{ Transactions = new []{14, 15}, Multiplier = 30 },
new{ Transactions = new []{16, 18}, Multiplier = 80 }
};
IConfigurationSection configuration = GetAdminRoleConfiguration(serviceProvider);
string userName = configuration[DefaultAdminNameKey];
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var db = serviceScope.ServiceProvider.GetService<PartsUnlimitedContext>();
var orders = new List<Order>();
foreach (var combination in recomendationCombinations)
{
for (int i = 0; i < combination.Multiplier; i++)
{
var order = new Order
{
Username = userName,
OrderDate = DateTime.Now,
Name = $"John Smith{random.Next()}",
Address = "15010 NE 36th St",
City = "Redmond",
State = "WA",
PostalCode = "98052",
Country = "United States",
Phone = "425-703-6214",
Email = userName
};
db.Orders.Add(order);
decimal total = 0;
foreach (var id in combination.Transactions)
{
var product = products.Single(x => x.RecommendationId == id);
var orderDetail = GetOrderDetail(product, order);
db.OrderDetails.Add(orderDetail);
total += orderDetail.UnitPrice;
}
order.Total = total;
}
}
db.SaveChanges();
}
}
public static OrderDetail GetOrderDetail(Product product, Order order)
{
var random = new Random();
int quantity;
switch (product.Category.Name)
{
case "Brakes":
case "Wheels & Tires":
{
quantity = random.Next(1, 5);
break;
}
default:
{
quantity = random.Next(1, 3);
break;
}
}
return new OrderDetail
{
ProductId = product.ProductId,
UnitPrice = product.Price,
OrderId = order.OrderId,
Quantity = quantity,
};
}
public static IEnumerable<Product> GetProducts(IEnumerable<Category> categories)
{
var categoriesMap = categories.ToDictionary(c => c.Name, c => c);
yield return new Product
{
SkuNumber = "LIG-0001",
Title = "Halogen Headlights (2 Pack)",
Category = categoriesMap["Lighting"],
CategoryId = categoriesMap["Lighting"].CategoryId,
Price = 38.99M,
SalePrice = 38.99M,
ProductArtUrl = "product_lighting_headlight.jpg",
ProductDetails = "{ \"Light Source\" : \"Halogen\", \"Assembly Required\": \"Yes\", \"Color\" : \"Clear\", \"Interior\" : \"Chrome\", \"Beam\": \"low and high\", \"Wiring harness included\" : \"Yes\", \"Bulbs Included\" : \"No\", \"Includes Parking Signal\" : \"Yes\"}",
Description = "Our Halogen Headlights are made to fit majority of vehicles with our universal fitting mold. Product requires some assembly.",
Inventory = 10,
LeadTime = 0,
RecommendationId = 1,
ProductId = 1
};
yield return new Product
{
SkuNumber = "LIG-0002",
Title = "Bugeye Headlights (2 Pack)",
Category = categoriesMap["Lighting"],
CategoryId = categoriesMap["Lighting"].CategoryId,
Price = 48.99M,
SalePrice = 48.99M,
ProductArtUrl = "product_lighting_bugeye-headlight.jpg",
ProductDetails = "{ \"Light Source\" : \"Halogen\", \"Assembly Required\": \"Yes\", \"Color\" : \"Clear\", \"Interior\" : \"Chrome\", \"Beam\": \"low and high\", \"Wiring harness included\" : \"No\", \"Bulbs Included\" : \"Yes\", \"Includes Parking Signal\" : \"Yes\"}",
Description = "Our Bugeye Headlights use Halogen light bulbs are made to fit into a standard bugeye slot. Product requires some assembly and includes light bulbs.",
Inventory = 7,
LeadTime = 0,
RecommendationId = 2,
ProductId = 2
};
yield return new Product
{
SkuNumber = "LIG-0003",
Title = "Turn Signal Light Bulb",
Category = categoriesMap["Lighting"],
CategoryId = categoriesMap["Lighting"].CategoryId,
Price = 6.49M,
SalePrice = 6.49M,
ProductArtUrl = "product_lighting_lightbulb.jpg",
ProductDetails = "{ \"Color\" : \"Clear\", \"Fit\" : \"Universal\", \"Wattage\" : \"30 Watts\", \"Includes Socket\" : \"Yes\"}",
Description = " Clear bulb that with a universal fitting for all headlights/taillights. Simple Installation, low wattage and a clear light for optimal visibility and efficiency.",
Inventory = 18,
LeadTime = 0,
RecommendationId = 3,
ProductId = 3
};
yield return new Product
{
SkuNumber = "WHE-0001",
Title = "Matte Finish Rim",
Category = categoriesMap["Wheels & Tires"],
CategoryId = categoriesMap["Wheels & Tires"].CategoryId,
Price = 75.99M,
SalePrice = 75.99M,
ProductArtUrl = "product_wheel_rim.jpg",
ProductDetails = "{ \"Material\" : \"Aluminum alloy\", \"Design\" : \"Spoke\", \"Spokes\" : \"9\", \"Number of Lugs\" : \"4\", \"Wheel Diameter\" : \"17 in.\", \"Color\" : \"Black\", \"Finish\" : \"Matte\" } ",
Description = "A Parts Unlimited favorite, the Matte Finish Rim is affordable low profile style. Fits all low profile tires.",
Inventory = 4,
LeadTime = 0,
RecommendationId = 4,
ProductId = 4
};
yield return new Product
{
SkuNumber = "WHE-0002",
Title = "Blue Performance Alloy Rim",
Category = categoriesMap["Wheels & Tires"],
CategoryId = categoriesMap["Wheels & Tires"].CategoryId,
Price = 88.99M,
SalePrice = 88.99M,
ProductArtUrl = "product_wheel_rim-blue.jpg",
ProductDetails = "{ \"Material\" : \"Aluminum alloy\", \"Design\" : \"Spoke\", \"Spokes\" : \"5\", \"Number of Lugs\" : \"4\", \"Wheel Diameter\" : \"18 in.\", \"Color\" : \"Blue\", \"Finish\" : \"Glossy\" } ",
Description = "Stand out from the crowd with a set of aftermarket blue rims to make you vehicle turn heads and at a price that will do the same.",
Inventory = 8,
LeadTime = 0,
RecommendationId = 5,
ProductId = 5
};
yield return new Product
{
SkuNumber = "WHE-0003",
Title = "High Performance Rim",
Category = categoriesMap["Wheels & Tires"],
CategoryId = categoriesMap["Wheels & Tires"].CategoryId,
Price = 99.99M,
SalePrice = 99.49M,
ProductArtUrl = "product_wheel_rim-red.jpg",
ProductDetails = "{ \"Material\" : \"Aluminum alloy\", \"Design\" : \"Spoke\", \"Spokes\" : \"12\", \"Number of Lugs\" : \"5\", \"Wheel Diameter\" : \"18 in.\", \"Color\" : \"Red\", \"Finish\" : \"Matte\" } ",
Description = "Light Weight Rims with a twin cross spoke design for stability and reliable performance.",
Inventory = 3,
LeadTime = 0,
RecommendationId = 6,
ProductId = 6
};
yield return new Product
{
SkuNumber = "WHE-0004",
Title = "Wheel Tire Combo",
Category = categoriesMap["Wheels & Tires"],
CategoryId = categoriesMap["Wheels & Tires"].CategoryId,
Price = 72.49M,
SalePrice = 72.49M,
ProductArtUrl = "product_wheel_tyre-wheel-combo.jpg",
ProductDetails = "{ \"Material\" : \"Steel\", \"Design\" : \"Spoke\", \"Spokes\" : \"8\", \"Number of Lugs\" : \"4\", \"Wheel Diameter\" : \"19 in.\", \"Color\" : \"Gray\", \"Finish\" : \"Standard\", \"Pre-Assembled\" : \"Yes\" } ",
Description = "For the endurance driver, take advantage of our best wearing tire yet. Composite rubber and a heavy duty steel rim.",
Inventory = 0,
LeadTime = 4,
RecommendationId = 7,
ProductId = 7
};
yield return new Product
{
SkuNumber = "WHE-0005",
Title = "Chrome Rim Tire Combo",
Category = categoriesMap["Wheels & Tires"],
CategoryId = categoriesMap["Wheels & Tires"].CategoryId,
Price = 129.99M,
SalePrice = 129.99M,
ProductArtUrl = "product_wheel_tyre-rim-chrome-combo.jpg",
ProductDetails = "{ \"Material\" : \"Aluminum alloy\", \"Design\" : \"Spoke\", \"Spokes\" : \"10\", \"Number of Lugs\" : \"5\", \"Wheel Diameter\" : \"17 in.\", \"Color\" : \"Silver\", \"Finish\" : \"Chrome\", \"Pre-Assembled\" : \"Yes\" } ",
Description = "Save time and money with our ever popular wheel and tire combo. Pre-assembled and ready to go.",
Inventory = 1,
LeadTime = 0,
RecommendationId = 8,
ProductId = 8
};
yield return new Product
{
SkuNumber = "WHE-0006",
Title = "Wheel Tire Combo (4 Pack)",
Category = categoriesMap["Wheels & Tires"],
CategoryId = categoriesMap["Wheels & Tires"].CategoryId,
Price = 219.99M,
SalePrice = 219.99M,
ProductArtUrl = "product_wheel_tyre-wheel-combo-pack.jpg",
ProductDetails = "{ \"Material\" : \"Steel\", \"Design\" : \"Spoke\", \"Spokes\" : \"8\", \"Number of Lugs\" : \"5\", \"Wheel Diameter\" : \"19 in.\", \"Color\" : \"Gray\", \"Finish\" : \"Standard\", \"Pre-Assembled\" : \"Yes\" } ",
Description = "Having trouble in the wet? Then try our special patent tire on a heavy duty steel rim. These wheels perform excellent in all conditions but were designed specifically for wet weather.",
Inventory = 3,
LeadTime = 0,
RecommendationId = 9,
ProductId = 9
};
yield return new Product
{
SkuNumber = "BRA-0001",
Title = "Disk and Pad Combo",
Category = categoriesMap["Wheels & Tires"],
CategoryId = categoriesMap["Wheels & Tires"].CategoryId,
Price = 25.99M,
SalePrice = 25.99M,
ProductArtUrl = "product_brakes_disk-pad-combo.jpg",
ProductDetails = "{ \"Disk Design\" : \"Cross Drill Slotted\", \" Pad Material\" : \"Ceramic\", \"Construction\" : \"Vented Rotor\", \"Diameter\" : \"10.3 in.\", \"Finish\" : \"Silver Zinc Plated\", \"Hat Finish\" : \"Silver Zinc Plated\", \"Material\" : \"Cast Iron\" }",
Description = "Our brake disks and pads perform the best togeather. Better stopping distances without locking up, reduced rust and dusk.",
Inventory = 0,
LeadTime = 6,
RecommendationId = 10,
ProductId = 10
};
yield return new Product
{
SkuNumber = "BRA-0002",
Title = "Brake Rotor",
Category = categoriesMap["Brakes"],
CategoryId = categoriesMap["Brakes"].CategoryId,
Price = 18.99M,
SalePrice = 18.99M,
ProductArtUrl = "product_brakes_disc.jpg",
ProductDetails = "{ \"Disk Design\" : \"Cross Drill Slotted\", \"Construction\" : \"Vented Rotor\", \"Diameter\" : \"10.3 in.\", \"Finish\" : \"Silver Zinc Plated\", \"Hat Finish\" : \"Black E-coating\", \"Material\" : \"Cast Iron\" }",
Description = "Our Brake Rotor Performs well in wet coditions with a smooth responsive feel. Machined to a high tolerance to ensure all of our Brake Rotors are safe and reliable.",
Inventory = 4,
LeadTime = 0,
RecommendationId = 11,
ProductId = 11
};
yield return new Product
{
SkuNumber = "BRA-0003",
Title = "Brake Disk and Calipers",
Category = categoriesMap["Brakes"],
CategoryId = categoriesMap["Brakes"].CategoryId,
Price = 43.99M,
SalePrice = 43.99M,
ProductArtUrl = "product_brakes_disc-calipers-red.jpg",
ProductDetails = "{\"Disk Design\" : \"Cross Drill Slotted\", \" Pad Material\" : \"Carbon Ceramic\", \"Construction\" : \"Vented Rotor\", \"Diameter\" : \"11.3 in.\", \"Bolt Pattern\": \"6 x 5.31 in.\", \"Finish\" : \"Silver Zinc Plated\", \"Material\" : \"Carbon Alloy\", \"Includes Brake Pads\" : \"Yes\" }",
Description = "Upgrading your brakes can increase stopping power, reduce dust and noise. Our Disk Calipers exceed factory specification for the best performance.",
Inventory = 2,
LeadTime = 0,
RecommendationId = 12,
ProductId = 12
};
yield return new Product
{
SkuNumber = "BAT-0001",
Title = "12-Volt Calcium Battery",
Category = categoriesMap["Batteries"],
CategoryId = categoriesMap["Batteries"].CategoryId,
Price = 129.99M,
SalePrice = 129.99M,
ProductArtUrl = "product_batteries_basic-battery.jpg",
ProductDetails = "{ \"Type\": \"Calcium\", \"Volts\" : \"12\", \"Weight\" : \"22.9 lbs\", \"Size\" : \"7.7x5x8.6\", \"Cold Cranking Amps\" : \"510\" }",
Description = "Calcium is the most common battery type. It is durable and has a long shelf and service life. They also provide high cold cranking amps.",
Inventory = 9,
LeadTime = 0,
RecommendationId = 13,
ProductId = 13
};
yield return new Product
{
SkuNumber = "BAT-0002",
Title = "Spiral Coil Battery",
Category = categoriesMap["Batteries"],
CategoryId = categoriesMap["Batteries"].CategoryId,
Price = 154.99M,
SalePrice = 154.99M,
ProductArtUrl = "product_batteries_premium-battery.jpg",
ProductDetails = "{ \"Type\": \"Spiral Coil\", \"Volts\" : \"12\", \"Weight\" : \"20.3 lbs\", \"Size\" : \"7.4x5.1x8.5\", \"Cold Cranking Amps\" : \"460\" }",
Description = "Spiral Coil batteries are the preferred option for high performance Vehicles where extra toque is need for starting. They are more resistant to heat and higher charge rates than conventional batteries.",
Inventory = 3,
LeadTime = 0,
RecommendationId = 14,
ProductId = 14
};
yield return new Product
{
SkuNumber = "BAT-0003",
Title = "Jumper Leads",
Category = categoriesMap["Batteries"],
CategoryId = categoriesMap["Batteries"].CategoryId,
Price = 16.99M,
SalePrice = 16.99M,
ProductArtUrl = "product_batteries_jumper-leads.jpg",
ProductDetails = "{ \"length\" : \"6ft.\", \"Connection Type\" : \"Alligator Clips\", \"Fit\" : \"Universal\", \"Max Amp's\" : \"750\" }",
Description = "Battery Jumper Leads have a built in surge protector and a includes a plastic carry case to keep them safe from corrosion.",
Inventory = 6,
LeadTime = 0,
RecommendationId = 15,
ProductId = 15
};
yield return new Product
{
SkuNumber = "OIL-0001",
Title = "Filter Set",
Category = categoriesMap["Oil"],
CategoryId = categoriesMap["Oil"].CategoryId,
Price = 28.99M,
SalePrice = 28.99M,
ProductArtUrl = "product_oil_filters.jpg",
ProductDetails = "{ \"Filter Type\" : \"Canister and Cartridge\", \"Thread Size\" : \"0.75-16 in.\", \"Anti-Drainback Valve\" : \"Yes\"}",
Description = "Ensure that your vehicle's engine has a longer life with our new filter set. Trapping more dirt to ensure old freely circulates through your engine.",
Inventory = 3,
LeadTime = 0,
RecommendationId = 16,
ProductId = 16
};
yield return new Product
{
SkuNumber = "OIL-0002",
Title = "Oil and Filter Combo",
Category = categoriesMap["Oil"],
CategoryId = categoriesMap["Oil"].CategoryId,
Price = 34.49M,
SalePrice = 34.49M,
ProductArtUrl = "product_oil_oil-filter-combo.jpg",
ProductDetails = "{ \"Filter Type\" : \"Canister\", \"Thread Size\" : \"0.75-16 in.\", \"Anti-Drainback Valve\" : \"Yes\", \"Size\" : \"1.1 gal.\", \"Synthetic\" : \"No\" }",
Description = "This Oil and Oil Filter combo is suitable for all types of passenger and light commercial vehicles. Providing affordable performance through excellent lubrication and breakdown resistance.",
Inventory = 5,
LeadTime = 0,
RecommendationId = 17,
ProductId = 17
};
yield return new Product
{
SkuNumber = "OIL-0003",
Title = "Synthetic Engine Oil",
Category = categoriesMap["Oil"],
CategoryId = categoriesMap["Oil"].CategoryId,
Price = 36.49M,
SalePrice = 36.49M,
ProductArtUrl = "product_oil_premium-oil.jpg",
ProductDetails = "{ \"Size\" : \"1.1 Gal.\" , \"Synthetic \" : \"Yes\"}",
Description = "This Oil is designed to reduce sludge deposits and metal friction throughout your cars engine. Provides performance no matter the condition or temperature.",
Inventory = 11,
LeadTime = 0,
RecommendationId = 18,
ProductId = 18
};
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Positioning.dll
// Description: A library for managing GPS connections.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from http://geoframework.codeplex.com/ version 2.0
//
// The Initial Developer of this original code is Jon Pearson. Submitted Oct. 21, 2010 by Ben Tombs (tidyup)
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// -------------------------------------------------------------------------------------------------------
// | Developer | Date | Comments
// |--------------------------|------------|--------------------------------------------------------------
// | Tidyup (Ben Tombs) | 10/21/2010 | Original copy submitted from modified GeoFrameworks 2.0
// | Shade1974 (Ted Dunsford) | 10/21/2010 | Added file headers reviewed formatting with resharper.
// ********************************************************************************************************
using System;
using System.Globalization;
#if !PocketPC || DesignTime
using System.ComponentModel;
#endif
namespace DotSpatial.Positioning
{
#if !PocketPC || DesignTime
/// <summary>
/// Represents a two-dimensional rectangular area.
/// </summary>
/// <remarks>Instances of this class are guaranteed to be thread-safe because the class is
/// immutable (it's properties can only be set via constructors).</remarks>
[TypeConverter("DotSpatial.Positioning.Design.GeographicSizeConverter, DotSpatial.Positioning.Design, Culture=neutral, Version=1.0.0.0, PublicKeyToken=b4b0b185210c9dae")]
#endif
public struct GeographicSize : IFormattable, IEquatable<GeographicSize>
{
/// <summary>
///
/// </summary>
private readonly Distance _width;
/// <summary>
///
/// </summary>
private readonly Distance _height;
#region Fields
/// <summary>
/// Represents a size with no value.
/// </summary>
public static readonly GeographicSize Empty = new GeographicSize(Distance.Empty, Distance.Empty);
/// <summary>
/// Represents a size with no value.
/// </summary>
public static readonly GeographicSize Minimum = new GeographicSize(Distance.Minimum, Distance.Minimum);
/// <summary>
/// Represents the largest possible size on Earth's surface.
/// </summary>
public static readonly GeographicSize Maximum = new GeographicSize(Distance.Maximum, Distance.Maximum);
/// <summary>
/// Represents an invalid geographic size.
/// </summary>
public static readonly GeographicSize Invalid = new GeographicSize(Distance.Invalid, Distance.Invalid);
#endregion Fields
#region Constructors
/// <summary>
/// Creates a new instance.
/// </summary>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
public GeographicSize(Distance width, Distance height)
{
_width = width;
_height = height;
}
/// <summary>
/// Creates a new instance from the specified string.
/// </summary>
/// <param name="value">The value.</param>
public GeographicSize(string value)
: this(value, CultureInfo.CurrentCulture)
{ }
/// <summary>
/// Creates a new instance from the specified string in the specified culture.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="culture">The culture.</param>
/// <remarks>This method will attempt to split the specified string into two values, then parse each value
/// as an Distance object. The string must contain two numbers separated by a comma (or other character depending
/// on the culture).</remarks>
public GeographicSize(string value, CultureInfo culture)
{
// Split out the values
string[] values = value.Split(culture.TextInfo.ListSeparator.ToCharArray());
// There should only be two of them
switch (values.Length)
{
case 2:
_width = Distance.Parse(values[0], culture);
_height = Distance.Parse(values[1], culture);
break;
default:
throw new ArgumentException("A GeographicSize could not be created from a string because the string was not in an identifiable format. The format should be \"(w, h)\" where \"w\" represents a width in degrees, and \"h\" represents a height in degrees. The values should be separated by a comma (or other character depending on the current culture).");
}
}
#endregion Constructors
#region Public Properties
/// <summary>
/// Returns the ratio of the size's width to its height.
/// </summary>
public float AspectRatio
{
get
{
return Convert.ToSingle(_width.ToMeters().Value / _height.ToMeters().Value);
}
}
/// <summary>
/// Returns the left-to-right size.
/// </summary>
public Distance Width
{
get
{
return _width;
}
}
/// <summary>
/// Returns the top-to-bottom size.
/// </summary>
public Distance Height
{
get
{
return _height;
}
}
/// <summary>
/// Indicates if the size has zero values.
/// </summary>
public bool IsEmpty
{
get
{
return (_width.IsEmpty && _height.IsEmpty);
}
}
/// <summary>
/// Returns whether the current instance has invalid values.
/// </summary>
public bool IsInvalid
{
get
{
return _width.IsInvalid && _height.IsInvalid;
}
}
#endregion Public Properties
#region Public Methods
/// <summary>
/// Toes the aspect ratio.
/// </summary>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <returns></returns>
public GeographicSize ToAspectRatio(Distance width, Distance height)
{
// Calculate the aspect ratio
return ToAspectRatio(Convert.ToSingle(width.Divide(height).Value));
}
/// <summary>
/// Toes the aspect ratio.
/// </summary>
/// <param name="aspectRatio">The aspect ratio.</param>
/// <returns></returns>
public GeographicSize ToAspectRatio(float aspectRatio)
{
float currentAspect = AspectRatio;
// Do the values already match?
if (currentAspect == aspectRatio)
return this;
// Convert to meters first
Distance widthMeters = _width.ToMeters();
Distance heightMeters = _height.ToMeters();
// Is the new ratio higher or lower?
if (aspectRatio > currentAspect)
{
// Inflate the GeographicRectDistance to the new height minus the current height
return new GeographicSize(
widthMeters.Add(heightMeters.Multiply(aspectRatio).Subtract(widthMeters)),
heightMeters);
}
// Inflate the GeographicRectDistance to the new height minus the current height
return new GeographicSize(
widthMeters,
heightMeters.Add(widthMeters.Divide(aspectRatio).Subtract(heightMeters)));
}
/// <summary>
/// Adds the specified size to the current instance.
/// </summary>
/// <param name="size">The size.</param>
/// <returns></returns>
public GeographicSize Add(GeographicSize size)
{
return new GeographicSize(_width.Add(size.Width), _height.Add(size.Height));
}
/// <summary>
/// Subtracts the specified size from the current instance.
/// </summary>
/// <param name="size">The size.</param>
/// <returns></returns>
public GeographicSize Subtract(GeographicSize size)
{
return new GeographicSize(_width.Subtract(size.Width), _height.Subtract(size.Height));
}
/// <summary>
/// Multiplies the width and height by the specified size.
/// </summary>
/// <param name="size">A <strong>GeographicSize</strong> specifying how to much to multiply the width and height.</param>
/// <returns>A <strong>GeographicSize</strong> representing the product of the current instance with the specified size.</returns>
public GeographicSize Multiply(GeographicSize size)
{
return new GeographicSize(_width.Multiply(size.Width), _height.Multiply(size.Height));
}
/// <summary>
/// Divides the width and height by the specified size.
/// </summary>
/// <param name="size">The size.</param>
/// <returns></returns>
public GeographicSize Divide(GeographicSize size)
{
return new GeographicSize(_width.Divide(size.Width), _height.Divide(size.Height));
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <param name="format">The format.</param>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public string ToString(string format)
{
return ToString(format, CultureInfo.CurrentCulture);
}
#endregion Public Methods
#region Overrides
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">Another object to compare to.</param>
/// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
if (obj is GeographicSize)
return Equals((GeographicSize)obj);
return false;
}
/// <summary>
/// Returns a unique code based on the object's value.
/// </summary>
/// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
public override int GetHashCode()
{
return _width.GetHashCode() ^ _height.GetHashCode();
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public override string ToString()
{
return ToString("G", CultureInfo.CurrentCulture);
}
#endregion Overrides
#region Static Methods
/// <summary>
/// Returns a GeographicSize whose value matches the specified string.
/// </summary>
/// <param name="value">A <strong>String</strong> describing a width, followed by a height.</param>
/// <returns>A <strong>GeographicSize</strong> whose Width and Height properties match the specified string.</returns>
public static GeographicSize Parse(string value)
{
return Parse(value, CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns a GeographicSize whose value matches the specified string.
/// </summary>
/// <param name="value">A <strong>String</strong> describing a width, followed by a height.</param>
/// <param name="culture">A <strong>CultureInfo</strong> object describing how to parse the specified string.</param>
/// <returns>A <strong>GeographicSize</strong> whose Width and Height properties match the specified string.</returns>
public static GeographicSize Parse(string value, CultureInfo culture)
{
return new GeographicSize(value, culture);
}
#endregion Static Methods
#region Conversions
/// <summary>
/// Performs an explicit conversion from <see cref="System.String"/> to <see cref="DotSpatial.Positioning.GeographicSize"/>.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator GeographicSize(string value)
{
return new GeographicSize(value, CultureInfo.CurrentCulture);
}
/// <summary>
/// Performs an explicit conversion from <see cref="DotSpatial.Positioning.GeographicSize"/> to <see cref="System.String"/>.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator string(GeographicSize value)
{
return value.ToString();
}
#endregion Conversions
#region IEquatable<GeographicSize> Members
/// <summary>
/// Compares the value of the current instance to the specified GeographicSize.
/// </summary>
/// <param name="value">A <strong>GeographicSize</strong> object to compare against.</param>
/// <returns>A <strong>Boolean</strong>, <strong>True</strong> if the values of both objects are precisely the same.</returns>
public bool Equals(GeographicSize value)
{
return Width.Equals(value.Width)
&& Height.Equals(value.Height);
}
/// <summary>
/// Compares the value of the current instance to the specified GeographicSize, to the specified number of decimals.
/// </summary>
/// <param name="value">A <strong>GeographicSize</strong> object to compare against.</param>
/// <param name="decimals">An <strong>Integer</strong> describing how many decimals the values are rounded to before comparison.</param>
/// <returns>A <strong>Boolean</strong>, <strong>True</strong> if the values of both objects are the same out to the number of decimals specified.</returns>
public bool Equals(GeographicSize value, int decimals)
{
return _width.Equals(value.Width, decimals)
&& _height.Equals(value.Height, decimals);
}
#endregion IEquatable<GeographicSize> Members
#region IFormattable Members
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <param name="format">The format to use.-or- A null reference (Nothing in Visual Basic) to use the default format defined for the type of the <see cref="T:System.IFormattable"/> implementation.</param>
/// <param name="formatProvider">The provider to use to format the value.-or- A null reference (Nothing in Visual Basic) to obtain the numeric format information from the current locale setting of the operating system.</param>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public string ToString(string format, IFormatProvider formatProvider)
{
CultureInfo culture = (CultureInfo)formatProvider ?? CultureInfo.CurrentCulture;
if (string.IsNullOrEmpty(format))
format = "G";
return _width.ToString(format, culture)
+ culture.TextInfo.ListSeparator + " "
+ _height.ToString(format, culture);
}
#endregion IFormattable Members
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Baseline;
using Marten.Linq;
using Marten.Schema;
using Marten.Services;
using Marten.Storage;
namespace Marten.Patching
{
public class PatchExpression<T> : IPatchExpression<T>
{
private readonly IWhereFragment _fragment;
private readonly ITenant _tenant;
private readonly UnitOfWork _unitOfWork;
private readonly ISerializer _serializer;
public readonly IDictionary<string, object> Patch = new Dictionary<string, object>();
public PatchExpression(IWhereFragment fragment, ITenant tenant, UnitOfWork unitOfWork, ISerializer serializer)
{
_fragment = fragment;
_tenant = tenant;
_unitOfWork = unitOfWork;
_serializer = serializer;
}
public void Set<TValue>(string name, TValue value)
{
set(name, value);
}
public void Set<TParent, TValue>(string name, Expression<Func<T, TParent>> expression, TValue value)
{
set(toPath(expression) + $".{name}", value);
}
public void Set<TValue>(Expression<Func<T, TValue>> expression, TValue value)
{
set(toPath(expression), value);
}
private void set<TValue>(string path, TValue value)
{
Patch.Add("type", "set");
Patch.Add("value", value);
Patch.Add("path", path);
apply();
}
public void Duplicate<TElement>(Expression<Func<T, TElement>> expression, params Expression<Func<T, TElement>>[] destinations)
{
if (destinations.Length == 0)
throw new ArgumentException("At least one destination must be given");
Patch.Add("type", "duplicate");
Patch.Add("path", toPath(expression));
Patch.Add("targets", destinations.Select(toPath).ToArray());
apply();
}
public void Increment(Expression<Func<T, int>> expression, int increment = 1)
{
Patch.Add("type", "increment");
Patch.Add("increment", increment);
Patch.Add("path", toPath(expression));
apply();
}
public void Increment(Expression<Func<T, long>> expression, long increment = 1)
{
Patch.Add("type", "increment");
Patch.Add("increment", increment);
Patch.Add("path", toPath(expression));
apply();
}
public void Increment(Expression<Func<T, double>> expression, double increment = 1)
{
Patch.Add("type", "increment_float");
Patch.Add("increment", increment);
Patch.Add("path", toPath(expression));
apply();
}
public void Increment(Expression<Func<T, float>> expression, float increment = 1)
{
Patch.Add("type", "increment_float");
Patch.Add("increment", increment);
Patch.Add("path", toPath(expression));
apply();
}
public void Append<TElement>(Expression<Func<T, IEnumerable<TElement>>> expression, TElement element)
{
Patch.Add("type", "append");
Patch.Add("value", element);
Patch.Add("path", toPath(expression));
apply();
}
public void AppendIfNotExists<TElement>(Expression<Func<T, IEnumerable<TElement>>> expression, TElement element)
{
Patch.Add("type", "append_if_not_exists");
Patch.Add("value", element);
Patch.Add("path", toPath(expression));
apply();
}
public void Insert<TElement>(Expression<Func<T, IEnumerable<TElement>>> expression, TElement element,
int index = 0)
{
Patch.Add("type", "insert");
Patch.Add("value", element);
Patch.Add("path", toPath(expression));
Patch.Add("index", index);
apply();
}
public void InsertIfNotExists<TElement>(Expression<Func<T, IEnumerable<TElement>>> expression, TElement element,
int index = 0)
{
Patch.Add("type", "insert_if_not_exists");
Patch.Add("value", element);
Patch.Add("path", toPath(expression));
Patch.Add("index", index);
apply();
}
public void Remove<TElement>(Expression<Func<T, IEnumerable<TElement>>> expression, TElement element,
RemoveAction action = RemoveAction.RemoveFirst)
{
Patch.Add("type", "remove");
Patch.Add("value", element);
Patch.Add("path", toPath(expression));
Patch.Add("action", (int) action);
apply();
}
public void Rename(string oldName, Expression<Func<T, object>> expression)
{
Patch.Add("type", "rename");
var newPath = toPath(expression);
var parts = newPath.Split('.');
var to = parts.Last();
parts[parts.Length - 1] = oldName;
var path = parts.Join(".");
Patch.Add("to", to);
Patch.Add("path", path);
apply();
}
public void Delete(string name)
{
delete(name);
}
public void Delete<TParent>(string name, Expression<Func<T, TParent>> expression)
{
delete(toPath(expression) + $".{name}");
}
public void Delete<TElement>(Expression<Func<T, TElement>> expression)
{
delete(toPath(expression));
}
private void delete(string path)
{
Patch.Add("type", "delete");
Patch.Add("path", path);
apply();
}
private string toPath(Expression expression)
{
var visitor = new FindMembers();
visitor.Visit(expression);
return visitor.Members.Select(x => x.Name).Join(".");
}
private void apply()
{
var transform = _tenant.TransformFor(StoreOptions.PatchDoc);
var document = _tenant.MappingFor(typeof(T)).ToQueryableDocument();
var where = document.FilterDocuments(null, _fragment);
var operation = new PatchOperation(transform, document, where, Patch, _serializer);
_unitOfWork.Patch(operation);
}
}
}
| |
/* Copyright (c) 2006-2008 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.
*/
/* Change history
* Oct 13 2008 Joe Feser joseph.feser@gmail.com
* Converted ArrayLists and other .NET 1.1 collections to use Generics
* Combined IExtensionElement and IExtensionElementFactory interfaces
*
*/
#region Using directives
// #define USE_TRACING
using System;
using System.Xml;
using System.IO;
using System.Collections.Generic;
using System.Globalization;
#endregion
//////////////////////////////////////////////////////////////////////
// <summary>Contains AtomFeedParser.</summary>
//////////////////////////////////////////////////////////////////////
namespace Google.GData.Client
{
//////////////////////////////////////////////////////////////////////
/// <summary>AtomFeedParser.
/// </summary>
//////////////////////////////////////////////////////////////////////
public class AtomFeedParser : BaseFeedParser
{
/// <summary>holds the nametable used for parsing, based on XMLNameTable</summary>
private AtomParserNameTable nameTable;
private VersionInformation versionInfo = new VersionInformation();
//////////////////////////////////////////////////////////////////////
/// <summary>standard empty constructor</summary>
//////////////////////////////////////////////////////////////////////
public AtomFeedParser() : base()
{
Tracing.TraceCall("constructing AtomFeedParser");
this.nameTable = new AtomParserNameTable();
this.nameTable.InitAtomParserNameTable();
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>standard empty constructor</summary>
//////////////////////////////////////////////////////////////////////
public AtomFeedParser(IVersionAware v) : base()
{
Tracing.TraceCall("constructing AtomFeedParser");
this.nameTable = new AtomParserNameTable();
this.nameTable.InitAtomParserNameTable();
this.versionInfo = new VersionInformation(v);
}
/////////////////////////////////////////////////////////////////////////////
/// <summary>
/// nametable for the xmlparser that the atomfeedparser uses
/// </summary>
public AtomParserNameTable Nametable
{
get { return this.nameTable; }
}
//////////////////////////////////////////////////////////////////////
/// <summary>starts the parsing process</summary>
/// <param name="streamInput">input stream to parse </param>
/// <param name="feed">the basefeed object that should be set</param>
//////////////////////////////////////////////////////////////////////
public override void Parse(Stream streamInput, AtomFeed feed)
{
Tracing.TraceCall("feedparser starts parsing");
try
{
XmlReader reader = new XmlTextReader(streamInput, this.nameTable.Nametable);
MoveToStartElement(reader);
ParseFeed(reader, feed);
}
catch (Exception e)
{
throw new ClientFeedException("Parsing failed", e);
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>tries to parse a category collection document</summary>
/// <param name="reader"> xmlReader positioned at the start element</param>
/// <param name="owner">the base object that the collection belongs to</param>
/// <returns></returns>
//////////////////////////////////////////////////////////////////////
public AtomCategoryCollection ParseCategories(XmlReader reader, AtomBase owner)
{
Tracing.Assert(reader != null, "reader should not be null");
if (reader == null)
{
throw new ArgumentNullException("reader");
}
AtomCategoryCollection ret = new AtomCategoryCollection();
MoveToStartElement(reader);
Tracing.TraceCall("entering Categories Parser");
object localname = reader.LocalName;
Tracing.TraceInfo("localname is: " + reader.LocalName);
if (IsCurrentNameSpace(reader, BaseNameTable.AppPublishingNamespace(owner)) &&
localname.Equals(this.nameTable.Categories))
{
Tracing.TraceInfo("Found categories document");
int depth = -1;
while (NextChildElement(reader, ref depth))
{
localname = reader.LocalName;
if (IsCurrentNameSpace(reader, BaseNameTable.NSAtom))
{
if (localname.Equals(this.nameTable.Category))
{
AtomCategory category = ParseCategory(reader, owner);
ret.Add(category);
}
}
}
}
else
{
Tracing.TraceInfo("ParseCategories called and nothing was parsed" + localname);
throw new ClientFeedException("An invalid Atom Document was passed to the parser. This was not an app:categories document: " + localname);
}
return ret;
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>reads in the feed properties, updates the feed object, then starts
/// working on the entries...</summary>
/// <param name="reader"> xmlReader positioned at the Feed element</param>
/// <param name="feed">the basefeed object that should be set</param>
/// <returns> notifies user using event mechanism</returns>
//////////////////////////////////////////////////////////////////////
protected void ParseFeed(XmlReader reader, AtomFeed feed)
{
Tracing.Assert(reader != null, "reader should not be null");
if (reader == null)
{
throw new ArgumentNullException("reader");
}
Tracing.Assert(feed != null, "feed should not be null");
if (feed == null)
{
throw new ArgumentNullException("feed");
}
Tracing.TraceCall("entering AtomFeed Parser");
object localname = reader.LocalName;
Tracing.TraceInfo("localname is: " + reader.LocalName);
if (localname.Equals(this.nameTable.Feed))
{
Tracing.TraceInfo("Found standard feed document");
// found the feed......
// now parse the source base of this element
ParseSource(reader, feed);
// feed parsing complete, send notfication
this.OnNewAtomEntry(feed);
}
else if (localname.Equals(this.nameTable.Entry))
{
Tracing.TraceInfo("Found entry document");
ParseEntry(reader);
}
else
{
Tracing.TraceInfo("ParseFeed called and nothing was parsed" + localname.ToString());
// throw new ClientFeedException("An invalid Atom Document was passed to the parser. Neither Feed nor Entry started the document");
}
OnParsingDone();
feed.MarkElementDirty(false);
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>parses xml to fill a precreated AtomSource object (might be a feed)</summary>
/// <param name="reader">correctly positioned reader</param>
/// <param name="source">created source object to be filled</param>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
protected void ParseSource(XmlReader reader, AtomSource source)
{
Tracing.Assert(reader != null, "reader should not be null");
if (reader == null)
{
throw new ArgumentNullException("reader");
}
Tracing.Assert(source != null, "source should not be null");
if (source == null)
{
throw new ArgumentNullException("source");
}
Tracing.TraceCall();
//
// atomSource =
// element atom:source {
// atomCommonAttributes,
// (atomAuthor?
// & atomCategory*
// & atomContributor*
// & atomGenerator?
// & atomIcon?
// & atomId?
// & atomLink*
// & atomLogo?
// & atomRights?
// & atomSubtitle?
// & atomTitle?
// & atomUpdated?
// & extensionElement*)
// this will also parse the gData extension elements.
// }
int depth = -1;
ParseBasicAttributes(reader, source);
while (NextChildElement(reader, ref depth))
{
object localname = reader.LocalName;
AtomFeed feed = source as AtomFeed;
if (IsCurrentNameSpace(reader, BaseNameTable.NSAtom))
{
if (localname.Equals(this.nameTable.Title))
{
source.Title = ParseTextConstruct(reader, source);
}
else if (localname.Equals(this.nameTable.Updated))
{
source.Updated = DateTime.Parse(Utilities.DecodedValue(reader.ReadString()), CultureInfo.InvariantCulture);
}
else if (localname.Equals(this.nameTable.Link))
{
source.Links.Add(ParseLink(reader, source));
}
else if (localname.Equals(this.nameTable.Id))
{
source.Id = source.CreateAtomSubElement(reader, this) as AtomId;
ParseBaseLink(reader, source.Id);
}
else if (localname.Equals(this.nameTable.Icon))
{
source.Icon = source.CreateAtomSubElement(reader, this) as AtomIcon;
ParseBaseLink(reader, source.Icon);
}
else if (localname.Equals(this.nameTable.Logo))
{
source.Logo = source.CreateAtomSubElement(reader, this) as AtomLogo;
ParseBaseLink(reader, source.Logo);
}
else if (localname.Equals(this.nameTable.Author))
{
source.Authors.Add(ParsePerson(reader, source));
}
else if (localname.Equals(this.nameTable.Contributor))
{
source.Contributors.Add(ParsePerson(reader, source));
}
else if (localname.Equals(this.nameTable.Subtitle))
{
source.Subtitle = ParseTextConstruct(reader, source);
}
else if (localname.Equals(this.nameTable.Rights))
{
source.Rights = ParseTextConstruct(reader, source);
}
else if (localname.Equals(this.nameTable.Generator))
{
source.Generator = ParseGenerator(reader, source);
}
else if (localname.Equals(this.nameTable.Category))
{
// need to make this another colleciton
source.Categories.Add(ParseCategory(reader, source));
}
else if (feed != null && localname.Equals(this.nameTable.Entry))
{
ParseEntry(reader);
}
// this will either move the reader to the end of an element
// if at the end, to the start of a new one.
reader.Read();
}
else if (feed != null && IsCurrentNameSpace(reader, BaseNameTable.gBatchNamespace))
{
// parse the google batch extensions if they are there
ParseBatch(reader, feed);
}
else if (feed != null && IsCurrentNameSpace(reader, BaseNameTable.OpenSearchNamespace(this.versionInfo)))
{
if (localname.Equals(this.nameTable.TotalResults))
{
feed.TotalResults = int.Parse(Utilities.DecodedValue(reader.ReadString()), CultureInfo.InvariantCulture);
}
else if (localname.Equals(this.nameTable.StartIndex))
{
feed.StartIndex = int.Parse(Utilities.DecodedValue(reader.ReadString()), CultureInfo.InvariantCulture);
}
else if (localname.Equals(this.nameTable.ItemsPerPage))
{
feed.ItemsPerPage = int.Parse(Utilities.DecodedValue(reader.ReadString()), CultureInfo.InvariantCulture);
}
}
else
{
// default extension parsing.
ParseExtensionElements(reader, source);
}
}
return;
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>checks to see if the passed in namespace is the current one</summary>
/// <param name="reader">correctly positioned xmlreader</param>
/// <param name="namespaceToCompare">the namespace to test for</param>
/// <returns> true if this is the one</returns>
//////////////////////////////////////////////////////////////////////
static protected bool IsCurrentNameSpace(XmlReader reader, string namespaceToCompare)
{
Tracing.Assert(reader != null, "reader should not be null");
if (reader == null)
{
throw new ArgumentNullException("reader");
}
string curNamespace = reader.NamespaceURI;
if (curNamespace.Length == 0)
{
curNamespace = reader.LookupNamespace(String.Empty);
}
return curNamespace == namespaceToCompare;
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Parses the base attributes and puts the rest in extensions.
/// This needs to happen AFTER known attributes are parsed.</summary>
/// <param name="reader">correctly positioned xmlreader</param>
/// <param name="baseObject">the base object to set the property on</param>
/// <returns> true if an unknown attribute was found</returns>
//////////////////////////////////////////////////////////////////////
protected bool ParseBaseAttributes(XmlReader reader, AtomBase baseObject)
{
Tracing.Assert(reader != null, "reader should not be null");
if (reader == null)
{
throw new ArgumentNullException("reader");
}
Tracing.Assert(baseObject != null, "baseObject should not be null");
if (baseObject == null)
{
throw new ArgumentNullException("baseObject");
}
bool fRet = false;
fRet = true;
object localName = reader.LocalName;
Tracing.TraceCall();
if (IsCurrentNameSpace(reader, BaseNameTable.NSXml))
{
if (localName.Equals(this.nameTable.Base))
{
baseObject.Base = new AtomUri(reader.Value);
fRet = false;
}
else if (localName.Equals(this.nameTable.Language))
{
baseObject.Language = Utilities.DecodedValue(reader.Value);
fRet = false;
}
} else if (IsCurrentNameSpace(reader, BaseNameTable.gNamespace))
{
ISupportsEtag se = baseObject as ISupportsEtag;
if (se != null)
{
if (localName.Equals(this.nameTable.ETag))
{
se.Etag = reader.Value;
fRet = false;
}
}
}
if (fRet==true)
{
Tracing.TraceInfo("Found an unknown attribute");
this.OnNewExtensionElement(reader, baseObject);
}
return fRet;
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>parses extension elements, needs to happen when known attributes are done</summary>
/// <param name="reader">correctly positioned xmlreader</param>
/// <param name="baseObject">the base object to set the property on</param>
//////////////////////////////////////////////////////////////////////
protected void ParseExtensionElements(XmlReader reader, AtomBase baseObject)
{
Tracing.TraceCall();
if (reader == null)
{
throw new System.ArgumentNullException("reader", "No XmlReader supplied");
}
if (baseObject == null)
{
throw new System.ArgumentNullException("baseObject", "No baseObject supplied");
}
if (IsCurrentNameSpace(reader, BaseNameTable.NSAtom))
{
Tracing.TraceInfo("Found an unknown ATOM element = this might be a bug, either in the code or the document");
Tracing.TraceInfo("element: " + reader.LocalName + " position: " + reader.NodeType.ToString());
// maybe we should throw here, but I rather not - makes parsing more flexible
}
else
{
// everything NOT in Atom, call it
Tracing.TraceInfo("Found an unknown element");
this.OnNewExtensionElement(reader, baseObject);
// position back to the element
reader.MoveToElement();
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>nifty loop to check for base attributes for an object</summary>
/// <param name="reader">correctly positioned xmlreader</param>
/// <param name="baseObject">the base object to set the property on</param>
//////////////////////////////////////////////////////////////////////
protected void ParseBasicAttributes(XmlReader reader, AtomBase baseObject)
{
Tracing.TraceCall();
Tracing.Assert(reader != null, "reader should not be null");
if (reader == null)
{
throw new ArgumentNullException("reader");
}
Tracing.Assert(baseObject != null, "baseObject should not be null");
if (baseObject == null)
{
throw new ArgumentNullException("baseObject");
}
if (reader.NodeType == XmlNodeType.Element && reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
ParseBaseAttributes(reader, baseObject);
}
// position back to the element
reader.MoveToElement();
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>parses a baselink object, like AtomId, AtomLogo, or AtomIcon</summary>
/// <param name="reader"> correctly positioned xmlreader</param>
/// <param name="baseLink">the base object to set the property on</param>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
protected void ParseBaseLink(XmlReader reader, AtomBaseLink baseLink)
{
Tracing.TraceCall();
Tracing.Assert(reader != null, "reader should not be null");
if (reader == null)
{
throw new ArgumentNullException("reader");
}
Tracing.Assert(baseLink != null, "baseLink should not be null");
if (baseLink == null)
{
throw new ArgumentNullException("baseLink");
}
ParseBasicAttributes(reader, baseLink);
if (reader.NodeType == XmlNodeType.Element)
{
// read the element content
baseLink.Uri = new AtomUri(Utilities.DecodedValue(reader.ReadString()));
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>parses an author/person object</summary>
/// <param name="reader"> an XmlReader positioned at the start of the author</param>
/// <param name="owner">the object containing the person</param>
/// <returns> the created author object</returns>
//////////////////////////////////////////////////////////////////////
protected AtomPerson ParsePerson(XmlReader reader, AtomBase owner)
{
Tracing.Assert(reader != null, "reader should not be null");
if (reader == null)
{
throw new ArgumentNullException("reader");
}
Tracing.Assert(owner != null, "owner should not be null");
if (owner == null)
{
throw new ArgumentNullException("owner");
}
Tracing.TraceCall();
object localname = null;
AtomPerson author = owner.CreateAtomSubElement(reader, this) as AtomPerson;
ParseBasicAttributes(reader, author);
int lvl = -1;
while (NextChildElement(reader, ref lvl))
{
localname = reader.LocalName;
if (localname.Equals(this.nameTable.Name))
{
// author.Name = Utilities.DecodeString(Utilities.DecodedValue(reader.ReadString()));
author.Name = Utilities.DecodedValue(reader.ReadString());
reader.Read();
}
else if (localname.Equals(this.nameTable.Uri))
{
author.Uri = new AtomUri(Utilities.DecodedValue(reader.ReadString()));
reader.Read();
}
else if (localname.Equals(this.nameTable.Email))
{
author.Email = Utilities.DecodedValue(reader.ReadString());
reader.Read();
}
else
{
// default extension parsing.
ParseExtensionElements(reader, author);
}
}
return author;
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>parses an xml stream to create an AtomCategory object</summary>
/// <param name="reader">correctly positioned xmlreader</param>
/// <param name="owner">the object containing the person</param>
/// <returns> the created AtomCategory object</returns>
//////////////////////////////////////////////////////////////////////
protected AtomCategory ParseCategory(XmlReader reader, AtomBase owner)
{
Tracing.TraceCall();
Tracing.Assert(reader != null, "reader should not be null");
if (reader == null)
{
throw new ArgumentNullException("reader");
}
if (owner == null)
{
throw new ArgumentNullException("owner");
}
AtomCategory category = owner.CreateAtomSubElement(reader, this) as AtomCategory;
if (category != null)
{
bool noChildren = reader.IsEmptyElement;
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
object localname = reader.LocalName;
if (localname.Equals(this.nameTable.Term))
{
category.Term = Utilities.DecodedValue(reader.Value);
}
else if (localname.Equals(this.nameTable.Scheme))
{
category.Scheme = new AtomUri(reader.Value);
}
else if (localname.Equals(this.nameTable.Label))
{
category.Label = Utilities.DecodedValue(reader.Value);
}
else
{
ParseBaseAttributes(reader, category);
}
}
}
if (noChildren == false)
{
reader.MoveToElement();
int lvl = -1;
while (NextChildElement(reader, ref lvl))
{
ParseExtensionElements(reader, category);
}
}
}
return category;
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>creates an atomlink object</summary>
/// <param name="reader">correctly positioned xmlreader</param>
/// <param name="owner">the object containing the person</param>
/// <returns> the created AtomLink object</returns>
//////////////////////////////////////////////////////////////////////
protected AtomLink ParseLink(XmlReader reader, AtomBase owner)
{
Tracing.Assert(reader != null, "reader should not be null");
if (reader == null)
{
throw new ArgumentNullException("reader");
}
if (owner == null)
{
throw new ArgumentNullException("owner");
}
bool noChildren = reader.IsEmptyElement;
Tracing.TraceCall();
AtomLink link = owner.CreateAtomSubElement(reader, this) as AtomLink;
object localname = null;
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
localname = reader.LocalName;
if (localname.Equals(this.nameTable.HRef))
{
link.HRef = new AtomUri(reader.Value);
}
else if (localname.Equals(this.nameTable.Rel))
{
link.Rel = Utilities.DecodedValue(reader.Value);
}
else if (localname.Equals(this.nameTable.Type))
{
link.Type = Utilities.DecodedValue(reader.Value);
}
else if (localname.Equals(this.nameTable.HRefLang))
{
link.HRefLang = Utilities.DecodedValue(reader.Value);
}
else if (localname.Equals(this.nameTable.Title))
{
link.Title = Utilities.DecodedValue(reader.Value);
}
else if (localname.Equals(this.nameTable.Length))
{
link.Length = int.Parse(Utilities.DecodedValue(reader.Value), CultureInfo.InvariantCulture);
}
else
{
ParseBaseAttributes(reader, link);
}
}
}
if (noChildren == false)
{
reader.MoveToElement();
int lvl = -1;
while (NextChildElement(reader, ref lvl))
{
ParseExtensionElements(reader, link);
}
}
return link;
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>reads one of the feed entries at a time</summary>
/// <param name="reader"> XmlReader positioned at the entry element</param>
/// <returns> notifies user using event mechanism</returns>
//////////////////////////////////////////////////////////////////////
public void ParseEntry(XmlReader reader)
{
Tracing.Assert(reader != null, "reader should not be null");
if (reader == null)
{
throw new ArgumentNullException("reader");
}
object localname = reader.LocalName;
Tracing.TraceCall("Parsing atom entry");
if (localname.Equals(this.nameTable.Entry)==false)
{
throw new ClientFeedException("trying to parse an atom entry, but reader is not at the right spot");
}
AtomEntry entry = OnCreateNewEntry();
ParseBasicAttributes(reader, entry);
// remember the depth of entry
int depth = -1;
while (NextChildElement(reader, ref depth))
{
localname = reader.LocalName;
if (IsCurrentNameSpace(reader, BaseNameTable.NSAtom))
{
if (localname.Equals(this.nameTable.Id))
{
entry.Id = entry.CreateAtomSubElement(reader, this) as AtomId;
ParseBaseLink(reader, entry.Id);
}
else if (localname.Equals(this.nameTable.Link))
{
entry.Links.Add(ParseLink(reader, entry));
}
else if (localname.Equals(this.nameTable.Updated))
{
entry.Updated = DateTime.Parse(Utilities.DecodedValue(reader.ReadString()), CultureInfo.InvariantCulture);
}
else if (localname.Equals(this.nameTable.Published))
{
entry.Published = DateTime.Parse(Utilities.DecodedValue(reader.ReadString()), CultureInfo.InvariantCulture);
}
else if (localname.Equals(this.nameTable.Author))
{
entry.Authors.Add(ParsePerson(reader, entry));
}
else if (localname.Equals(this.nameTable.Contributor))
{
entry.Contributors.Add(ParsePerson(reader, entry));
}
else if (localname.Equals(this.nameTable.Rights))
{
entry.Rights = ParseTextConstruct(reader, entry);
}
else if (localname.Equals(this.nameTable.Category))
{
AtomCategory category = ParseCategory(reader, entry);
entry.Categories.Add(category);
}
else if (localname.Equals(this.nameTable.Summary))
{
entry.Summary = ParseTextConstruct(reader, entry);
}
else if (localname.Equals(this.nameTable.Content))
{
entry.Content = ParseContent(reader, entry);
}
else if (localname.Equals(this.nameTable.Source))
{
entry.Source = entry.CreateAtomSubElement(reader, this) as AtomSource;
ParseSource(reader, entry.Source);
}
else if (localname.Equals(this.nameTable.Title))
{
entry.Title = ParseTextConstruct(reader, entry);
}
// all parse methods should leave the reader at the end of their element
reader.Read();
}
else if (IsCurrentNameSpace(reader, BaseNameTable.gBatchNamespace))
{
// parse the google batch extensions if they are there
ParseBatch(reader, entry);
}
else
{
// default extension parsing
ParseExtensionElements(reader, entry);
}
}
OnNewAtomEntry(entry);
return;
}
/// <summary>
/// parses the current position in the xml reader and fills
/// the provided GDataEntryBatch property on the entry object
/// </summary>
/// <param name="reader">the xmlreader positioned at a batch element</param>
/// <param name="entry">the atomentry object to fill in</param>
protected void ParseBatch(XmlReader reader, AtomEntry entry)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
if (entry == null)
{
throw new ArgumentNullException("entry");
}
if (IsCurrentNameSpace(reader, BaseNameTable.gBatchNamespace))
{
object elementName = reader.LocalName;
if (entry.BatchData == null)
{
entry.BatchData = new GDataBatchEntryData();
}
GDataBatchEntryData batch = entry.BatchData;
if (elementName.Equals(this.nameTable.BatchId))
{
batch.Id = Utilities.DecodedValue(reader.ReadString());
}
else if (elementName.Equals(this.nameTable.BatchOperation))
{
batch.Type = ParseOperationType(reader);
}
else if (elementName.Equals(this.nameTable.BatchStatus))
{
batch.Status = GDataBatchStatus.ParseBatchStatus(reader, this);
}
else if (elementName.Equals(this.nameTable.BatchInterrupt))
{
batch.Interrupt = GDataBatchInterrupt.ParseBatchInterrupt(reader, this);
}
else
{
Tracing.TraceInfo("got an unknown batch element: " + elementName.ToString());
// default extension parsing
ParseExtensionElements(reader, entry);
}
}
}
/// <summary>
/// reads the current positioned reader and creates a operationtype enum
/// </summary>
/// <param name="reader">XmlReader positioned at the start of the status element</param>
/// <returns>GDataBatchOperationType</returns>
protected GDataBatchOperationType ParseOperationType(XmlReader reader)
{
Tracing.Assert(reader != null, "reader should not be null");
if (reader == null)
{
throw new ArgumentNullException("reader");
}
GDataBatchOperationType type = GDataBatchOperationType.Default;
object localname = reader.LocalName;
if (localname.Equals(this.nameTable.BatchOperation))
{
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
localname = reader.LocalName;
if (localname.Equals(this.nameTable.Type))
{
type = (GDataBatchOperationType)Enum.Parse(
typeof(GDataBatchOperationType), Utilities.DecodedValue(reader.Value), true);
}
}
}
}
return type;
}
/// <summary>
/// parses the current position in the xml reader and fills
/// the provided GDataFeedBatch property on the feed object
/// </summary>
/// <param name="reader">the xmlreader positioned at a batch element</param>
/// <param name="feed">the atomfeed object to fill in</param>
protected void ParseBatch(XmlReader reader, AtomFeed feed)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
if (feed == null)
{
throw new ArgumentNullException("feed");
}
if (IsCurrentNameSpace(reader, BaseNameTable.gBatchNamespace))
{
object elementName = reader.LocalName;
if (feed.BatchData == null)
{
feed.BatchData = new GDataBatchFeedData();
}
GDataBatchFeedData batch = feed.BatchData;
if (elementName.Equals(this.nameTable.BatchOperation))
{
batch.Type = (GDataBatchOperationType)Enum.Parse(typeof(GDataBatchOperationType),
reader.GetAttribute(BaseNameTable.XmlAttributeType), true);
}
else
{
Tracing.TraceInfo("got an unknown batch element: " + elementName.ToString());
reader.Skip();
}
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>parses an AtomTextConstruct</summary>
/// <param name="reader">the xmlreader correctly positioned at the construct </param>
/// <param name="owner">the container element</param>
/// <returns>the new text construct </returns>
//////////////////////////////////////////////////////////////////////
protected AtomTextConstruct ParseTextConstruct(XmlReader reader, AtomBase owner)
{
Tracing.Assert(reader != null, "reader should not be null");
if (reader == null)
{
throw new ArgumentNullException("reader");
}
if (owner == null)
{
throw new System.ArgumentNullException("owner");
}
Tracing.TraceCall("Parsing atomTextConstruct");
AtomTextConstruct construct = owner.CreateAtomSubElement(reader, this) as AtomTextConstruct;
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
object attributeName = reader.LocalName;
if (attributeName.Equals(this.nameTable.Type))
{
construct.Type = (AtomTextConstructType)Enum.Parse(
typeof(AtomTextConstructType), Utilities.DecodedValue(reader.Value), true);
}
else
{
ParseBaseAttributes(reader, construct);
}
}
}
reader.MoveToElement();
switch (construct.Type)
{
case AtomTextConstructType.html:
case AtomTextConstructType.text:
construct.Text = Utilities.DecodedValue(reader.ReadString());
break;
case AtomTextConstructType.xhtml:
default:
construct.Text = reader.ReadInnerXml();
break;
}
}
return construct;
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>parses an AtomGenerator</summary>
/// <param name="reader">the xmlreader correctly positioned at the generator </param>
/// <param name="owner">the container element</param>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
protected AtomGenerator ParseGenerator(XmlReader reader, AtomBase owner)
{
// atomGenerator = element atom:generator {
// atomCommonAttributes,
// attribute url { atomUri }?,
// attribute version { text }?,
// text
// }
Tracing.Assert(reader != null, "reader should not be null");
if (reader == null)
{
throw new ArgumentNullException("reader");
}
if (owner == null)
{
throw new ArgumentNullException("owner");
}
Tracing.TraceCall();
AtomGenerator generator = owner.CreateAtomSubElement(reader, this) as AtomGenerator;
if (generator != null)
{
generator.Text = Utilities.DecodedValue(reader.ReadString());
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
object attributeName = reader.LocalName;
if (attributeName.Equals(this.nameTable.Uri))
{
generator.Uri = new AtomUri(reader.Value);
}
else if (attributeName.Equals(this.nameTable.Version))
{
generator.Version = Utilities.DecodedValue(reader.Value);
}
else
{
ParseBaseAttributes(reader, generator);
}
}
}
}
return generator;
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>creates an AtomContent object by parsing an xml stream</summary>
/// <param name="reader">a XMLReader positioned correctly </param>
/// <param name="owner">the container element</param>
/// <returns> null or an AtomContent object</returns>
//////////////////////////////////////////////////////////////////////
protected AtomContent ParseContent(XmlReader reader, AtomBase owner)
{
Tracing.Assert(reader != null, "reader should not be null");
if (reader == null)
{
throw new ArgumentNullException("reader");
}
if (owner == null)
{
throw new ArgumentNullException("owner");
}
AtomContent content = owner.CreateAtomSubElement(reader, this) as AtomContent;
Tracing.TraceCall();
if (content != null)
{
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
object localname = reader.LocalName;
if (localname.Equals(this.nameTable.Type))
{
content.Type = Utilities.DecodedValue(reader.Value);
}
else if (localname.Equals(this.nameTable.Src))
{
content.Src = new AtomUri(reader.Value);
}
else
{
ParseBaseAttributes(reader, content);
}
}
}
if (MoveToStartElement(reader) == true)
{
if (content.Type.Equals("text") ||
content.Type.Equals("html") ||
content.Type.StartsWith("text/"))
{
// if it's text it get's just the string treatment. No
// subelements are allowed here
content.Content = Utilities.DecodedValue(reader.ReadString());
}
else if (content.Type.Equals("xhtml") ||
content.Type.Contains("/xml") ||
content.Type.Contains("+xml"))
{
// do not get childlists if the element is empty. That would skip to the next element
if (reader.IsEmptyElement == false)
{
// everything else will be nodes in the extension element list
// different media type. Create extension elements
int lvl = -1;
while (NextChildElement(reader, ref lvl))
{
ParseExtensionElements(reader, content);
}
}
}
else
{
// everything else SHOULD be base 64 encoded, so one big string
// i know the if statement could be combined with the text handling
// but i consider it clearer to make a 3 cases statement than combine them
content.Content = Utilities.DecodedValue(reader.ReadString());
}
}
}
return content;
}
/////////////////////////////////////////////////////////////////////////////
}
/////////////////////////////////////////////////////////////////////////////
}
/////////////////////////////////////////////////////////////////////////////
| |
//
// System.Reflection.Assembly Test Cases
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
// Philippe Lavoie (philippe.lavoie@cactus.ca)
// Sebastien Pouliot (sebastien@ximian.com)
//
// (c) 2003 Ximian, Inc. (http://www.ximian.com)
// Copyright (C) 2004-2005 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.Configuration.Assemblies;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Serialization;
using System.Security;
namespace MonoTests.System.Reflection
{
[TestFixture]
public class AssemblyTest
{
[Test]
public void CreateInstance()
{
Type type = typeof (AssemblyTest);
Object obj = type.Assembly.CreateInstance ("MonoTests.System.Reflection.AssemblyTest");
Assert.IsNotNull (obj, "#01");
Assert.AreEqual (GetType (), obj.GetType (), "#02");
}
[Test]
public void CreateInvalidInstance()
{
Type type = typeof (AssemblyTest);
Object obj = type.Assembly.CreateInstance("NunitTests.ThisTypeDoesNotExist");
Assert.IsNull (obj, "#03");
}
[Test]
#if NET_2_0
[Category ("NotWorking")]
[ExpectedException (typeof (ArgumentException))]
#else
[ExpectedException (typeof (TypeLoadException))]
#endif
public void TestGetType ()
{
// Bug #49114
typeof (int).Assembly.GetType ("&blabla", true, true);
}
[Test]
public void GetEntryAssembly ()
{
// note: only available in default appdomain
// http://weblogs.asp.net/asanto/archive/2003/09/08/26710.aspx
// Not sure we should emulate this behavior.
string fname = AppDomain.CurrentDomain.FriendlyName;
if (fname.EndsWith (".dll")) { // nunit-console
Assert.IsNull (Assembly.GetEntryAssembly (), "GetEntryAssembly");
#if NET_2_0
Assert.IsFalse (AppDomain.CurrentDomain.IsDefaultAppDomain (), "!default appdomain");
#endif
} else { // gnunit
Assert.IsNotNull (Assembly.GetEntryAssembly (), "GetEntryAssembly");
#if NET_2_0
Assert.IsTrue (AppDomain.CurrentDomain.IsDefaultAppDomain (), "!default appdomain");
#endif
}
}
#if NET_2_0
[Category ("NotWorking")]
#endif
[Test]
public void Corlib ()
{
Assembly corlib = typeof (int).Assembly;
Assert.IsTrue (corlib.CodeBase.EndsWith ("mscorlib.dll"), "CodeBase");
Assert.IsNull (corlib.EntryPoint, "EntryPoint");
Assert.IsTrue (corlib.EscapedCodeBase.EndsWith ("mscorlib.dll"), "EscapedCodeBase");
Assert.IsNotNull (corlib.Evidence, "Evidence");
Assert.IsTrue (corlib.Location.EndsWith ("mscorlib.dll"), "Location");
// corlib doesn't reference anything
Assert.AreEqual (0, corlib.GetReferencedAssemblies ().Length, "GetReferencedAssemblies");
#if NET_2_0
Assert.AreEqual ("mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", corlib.FullName, "FullName");
// not really "true" but it's even more trusted so...
Assert.IsTrue (corlib.GlobalAssemblyCache, "GlobalAssemblyCache");
Assert.AreEqual (0, corlib.HostContext, "HostContext");
Assert.AreEqual ("v2.0.50215", corlib.ImageRuntimeVersion, "ImageRuntimeVersion");
Assert.IsFalse (corlib.ReflectionOnly, "ReflectionOnly");
Assert.AreEqual (0x20000001, corlib.MetadataToken);
Assert.AreEqual (0x1, corlib.ManifestModule.MetadataToken);
#elif NET_1_1
Assert.IsFalse (corlib.GlobalAssemblyCache, "GlobalAssemblyCache");
Assert.AreEqual ("mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", corlib.FullName, "FullName");
Assert.AreEqual ("v1.1.4322", corlib.ImageRuntimeVersion, "ImageRuntimeVersion");
#endif
}
[Test]
public void Corlib_test ()
{
Assembly corlib_test = Assembly.GetExecutingAssembly ();
Assert.IsNull (corlib_test.EntryPoint, "EntryPoint");
Assert.IsNotNull (corlib_test.Evidence, "Evidence");
Assert.IsFalse (corlib_test.GlobalAssemblyCache, "GlobalAssemblyCache");
Assert.IsTrue (corlib_test.GetReferencedAssemblies ().Length > 0, "GetReferencedAssemblies");
#if NET_2_0
Assert.AreEqual (0, corlib_test.HostContext, "HostContext");
Assert.AreEqual ("v2.0.50215", corlib_test.ImageRuntimeVersion, "ImageRuntimeVersion");
Assert.IsNotNull (corlib_test.ManifestModule, "ManifestModule");
Assert.IsFalse (corlib_test.ReflectionOnly, "ReflectionOnly");
#elif NET_1_1
Assert.AreEqual ("v1.1.4322", corlib_test.ImageRuntimeVersion, "ImageRuntimeVersion");
#endif
}
[Test]
public void GetAssembly ()
{
Assert.IsTrue (Assembly.GetAssembly (typeof (int)).FullName.StartsWith ("mscorlib"), "GetAssembly(int)");
Assert.AreEqual (this.GetType ().Assembly.FullName, Assembly.GetAssembly (this.GetType ()).FullName, "GetAssembly(this)");
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void GetFile_Null ()
{
Assembly.GetExecutingAssembly ().GetFile (null);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void GetFile_Empty ()
{
Assembly.GetExecutingAssembly ().GetFile (String.Empty);
}
[Test]
public void GetFiles_False ()
{
Assembly corlib = typeof (int).Assembly;
FileStream[] fss = corlib.GetFiles ();
Assert.AreEqual (fss.Length, corlib.GetFiles (false).Length, "corlib.GetFiles (false)");
Assembly corlib_test = Assembly.GetExecutingAssembly ();
fss = corlib_test.GetFiles ();
Assert.AreEqual (fss.Length, corlib_test.GetFiles (false).Length, "test.GetFiles (false)");
}
[Test]
public void GetFiles_True ()
{
Assembly corlib = typeof (int).Assembly;
FileStream[] fss = corlib.GetFiles ();
Assert.IsTrue (fss.Length <= corlib.GetFiles (true).Length, "corlib.GetFiles (true)");
Assembly corlib_test = Assembly.GetExecutingAssembly ();
fss = corlib_test.GetFiles ();
Assert.IsTrue (fss.Length <= corlib_test.GetFiles (true).Length, "test.GetFiles (true)");
}
[Test]
public void LoadWithPartialName ()
{
Assembly corlib = Assembly.LoadWithPartialName ("corlib_test_default");
Assembly corlib2 = Assembly.LoadWithPartialName ("corlib_plattest");
Assert.IsTrue (corlib != null || corlib2 != null);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void GetObjectData_Null ()
{
Assembly corlib = typeof (int).Assembly;
corlib.GetObjectData (null, new StreamingContext (StreamingContextStates.All));
}
[Test]
public void GetReferencedAssemblies ()
{
Assembly corlib_test = Assembly.GetExecutingAssembly ();
AssemblyName[] names = corlib_test.GetReferencedAssemblies ();
foreach (AssemblyName an in names) {
Assert.IsNull (an.CodeBase, "CodeBase");
Assert.IsNotNull (an.CultureInfo, "CultureInfo");
Assert.IsNull (an.EscapedCodeBase, "EscapedCodeBase");
Assert.AreEqual (AssemblyNameFlags.None, an.Flags, "Flags");
Assert.IsNotNull (an.FullName, "FullName");
Assert.AreEqual (AssemblyHashAlgorithm.SHA1, an.HashAlgorithm, "HashAlgorithm");
Assert.IsNull (an.KeyPair, "KeyPair");
Assert.IsNotNull (an.Name, "Name");
Assert.IsNotNull (an.Version, "Version");
Assert.AreEqual (AssemblyVersionCompatibility.SameMachine,
an.VersionCompatibility, "VersionCompatibility");
}
}
[Test]
public void Location_Empty() {
string assemblyFileName = Path.Combine (
Path.GetTempPath (), "AssemblyLocation.dll");
try {
AssemblyName assemblyName = new AssemblyName ();
assemblyName.Name = "AssemblyLocation";
AssemblyBuilder ab = AppDomain.CurrentDomain
.DefineDynamicAssembly (assemblyName,
AssemblyBuilderAccess.Save,
Path.GetTempPath (),
AppDomain.CurrentDomain.Evidence);
ab.Save (Path.GetFileName (assemblyFileName));
using (FileStream fs = File.OpenRead(assemblyFileName)) {
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
Assembly assembly = Assembly.Load(buffer);
Assert.AreEqual(string.Empty, assembly.Location);
fs.Close();
}
} finally {
File.Delete (assemblyFileName);
}
}
#if NET_2_0
[Test]
[Category ("NotWorking")]
public void ReflectionOnlyLoad ()
{
Assembly assembly = Assembly.ReflectionOnlyLoad (typeof (AssemblyTest).Assembly.FullName);
Assert.IsNotNull (assembly);
Assert.IsTrue (assembly.ReflectionOnly);
}
[Test]
[Category ("NotWorking")]
public void ReflectionOnlyLoadFrom ()
{
string loc = typeof (AssemblyTest).Assembly.Location;
string filename = Path.GetFileName (loc);
Assembly assembly = Assembly.ReflectionOnlyLoadFrom (filename);
Assert.IsNotNull (assembly);
Assert.IsTrue (assembly.ReflectionOnly);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
[Category ("NotWorking")]
public void CreateInstanceOnRefOnly ()
{
Assembly assembly = Assembly.ReflectionOnlyLoad (typeof (AssemblyTest).Assembly.FullName);
assembly.CreateInstance ("MonoTests.System.Reflection.AssemblyTest");
}
#endif
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.Win32;
using SharpGen.Logging;
using SharpGen.Config;
namespace SharpGen.Parser
{
/// <summary>
/// GccXml front end for command line.
/// see http://www.gccxml.org/HTML/Index.html
/// </summary>
public class GccXml
{
private const string GccXmlGccOptionsFile = "gccxml_preprocess_sharpdx_options.txt";
private static readonly Regex MatchError = new Regex("error:");
/// <summary>
/// GccXml tag for FundamentalType
/// </summary>
public const string TagFundamentalType = "FundamentalType";
/// <summary>
/// GccXml tag for Enumeration
/// </summary>
public const string TagEnumeration = "Enumeration";
/// <summary>
/// GccXml tag for Struct
/// </summary>
public const string TagStruct = "Struct";
/// <summary>
/// GccXml tag for Field
/// </summary>
public const string TagField = "Field";
/// <summary>
/// GccXml tag for Union
/// </summary>
public const string TagUnion = "Union";
/// <summary>
/// GccXml tag for Typedef
/// </summary>
public const string TagTypedef = "Typedef";
/// <summary>
/// GccXml tag for Function
/// </summary>
public const string TagFunction = "Function";
/// <summary>
/// GccXml tag for PointerType
/// </summary>
public const string TagPointerType = "PointerType";
/// <summary>
/// GccXml tag for ArrayType
/// </summary>
public const string TagArrayType = "ArrayType";
/// <summary>
/// GccXml tag for ReferenceType
/// </summary>
public const string TagReferenceType = "ReferenceType";
/// <summary>
/// GccXml tag for CvQualifiedType
/// </summary>
public const string TagCvQualifiedType = "CvQualifiedType";
/// <summary>
/// GccXml tag for Namespace
/// </summary>
public const string TagNamespace = "Namespace";
/// <summary>
/// GccXml tag for Variable
/// </summary>
public const string TagVariable = "Variable";
/// <summary>
/// GccXml tag for FunctionType
/// </summary>
public const string TagFunctionType = "FunctionType";
/// <summary>
/// Gets or sets the executable path of gccxml.exe.
/// </summary>
/// <value>The executable path.</value>
public string ExecutablePath {get;set;}
/// <summary>
/// Gets or sets the include directory list.
/// </summary>
/// <value>The include directory list.</value>
public List<IncludeDirRule> IncludeDirectoryList { get; private set; }
/// <summary>
/// List of error filters regexp.
/// </summary>
private readonly List<Regex> _filterErrors;
/// <summary>
/// Initializes a new instance of the <see cref="GccXml"/> class.
/// </summary>
public GccXml()
{
IncludeDirectoryList = new List<IncludeDirRule>();
_filterErrors = new List<Regex>();
}
/// <summary>
/// Adds a filter error that will ignore a particular error from gccxml.
/// </summary>
/// <param name="file">The headerFile.</param>
/// <param name="regexpError">a regexp that filters a particular gccxml error message.</param>
public void AddFilterError(string file, string regexpError)
{
string fullRegexpError = @"[\\/]" + Regex.Escape(file) + ":.*" + regexpError;
_filterErrors.Add(new Regex(fullRegexpError));
}
/// <summary>
/// Preprocesses the specified header file.
/// </summary>
/// <param name="headerFile">The header file.</param>
/// <param name="handler">The handler.</param>
public void Preprocess(string headerFile, DataReceivedEventHandler handler)
{
Logger.RunInContext("gccxml", () =>
{
string vsVersion = GetVisualStudioVersion();
if (!File.Exists(ExecutablePath))
Logger.Fatal("gccxml.exe not found from path: [{0}]", ExecutablePath);
if (!File.Exists(headerFile))
Logger.Fatal("C++ Header file [{0}] not found", headerFile);
var currentProcess = new Process();
var startInfo = new ProcessStartInfo(ExecutablePath)
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
WorkingDirectory = Environment.CurrentDirectory
};
File.WriteAllText(GccXmlGccOptionsFile, "-dDI -E");
var arguments = ""; // "--gccxml-gcc-options " + GccXmlGccOptionsFile;
// Overrides settings for gccxml for compiling Win8 version
arguments += " --gccxml-config \"" + Path.Combine(Path.GetDirectoryName(ExecutablePath), @"..\share\gccxml-0.9\vc" + vsVersion + @"\gccxml_config") + "\"";
arguments += " -E --gccxml-gcc-options " + GccXmlGccOptionsFile;
foreach (var directory in GetIncludePaths())
arguments += " " + directory;
startInfo.Arguments = arguments + " " + headerFile;
Console.WriteLine(startInfo.Arguments);
currentProcess.StartInfo = startInfo;
currentProcess.ErrorDataReceived += ProcessErrorFromHeaderFile;
currentProcess.OutputDataReceived += handler;
currentProcess.Start();
currentProcess.BeginOutputReadLine();
currentProcess.BeginErrorReadLine();
currentProcess.WaitForExit();
currentProcess.Close();
});
}
private List<string> GetIncludePaths()
{
var paths = new List<string>();
foreach (var directory in IncludeDirectoryList)
{
var path = directory.Path;
// Is Using registry?
if (path.StartsWith("="))
{
var registryPath = directory.Path.Substring(1);
var indexOfSubPath = registryPath.IndexOf(";");
string subPath = "";
if (indexOfSubPath >= 0)
{
subPath = registryPath.Substring(indexOfSubPath + 1);
registryPath = registryPath.Substring(0, indexOfSubPath);
}
var indexOfKey = registryPath.LastIndexOf("\\");
var subKeyStr = registryPath.Substring(indexOfKey + 1);
registryPath = registryPath.Substring(0, indexOfKey);
var indexOfHive = registryPath.IndexOf("\\");
var hiveStr = registryPath.Substring(0, indexOfHive).ToUpper();
registryPath = registryPath.Substring(indexOfHive+1);
try
{
var hive = RegistryHive.LocalMachine;
switch (hiveStr)
{
case "HKEY_LOCAL_MACHINE":
hive = RegistryHive.LocalMachine;
break;
case "HKEY_CURRENT_USER":
hive = RegistryHive.CurrentUser;
break;
case "HKEY_CURRENT_CONFIG":
hive = RegistryHive.CurrentConfig;
break;
}
var rootKey = RegistryKey.OpenBaseKey(hive, RegistryView.Registry32);
var subKey = rootKey.OpenSubKey(registryPath);
if (subKey == null)
{
Logger.Error("Unable to locate key [{0}] in registry", registryPath);
continue;
}
path = Path.Combine(subKey.GetValue(subKeyStr).ToString(), subPath);
} catch (Exception ex)
{
Logger.Error("Unable to locate key [{0}] in registry", registryPath);
continue;
}
}
if (directory.IsOverride)
{
paths.Add("-iwrapper\"" + path.TrimEnd('\\') + "\"");
}
else
{
paths.Add("-I\"" + path.TrimEnd('\\') + "\"");
}
}
foreach (var path in paths)
{
Logger.Message("Path used for gccxml [{0}]", path);
}
return paths;
}
private static bool CheckVisualStudioVersion(string vsVersion)
{
var key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
var subKey = key.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\" + vsVersion + @".0\Setup\VC");
return subKey != null;
}
public static string ResolveVisualStudioVersion(params string[] versions)
{
foreach (var version in versions)
{
if (CheckVisualStudioVersion(version))
return version;
}
Logger.Exit("Visual Studio [{0}] with C++ not found. SharpDX requires this version to generate code from C++", string.Join("/", versions));
return null;
}
public static string GetVisualStudioVersion()
{
string vsVersion = ResolveVisualStudioVersion("12");
return vsVersion;
}
public static string GetWindowsFramework7Version(params string[] versions)
{
var key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
foreach (var version in versions)
{
var subKey = key.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SDKs\Windows\v" + version);
if (subKey != null)
{
// Check that the include directory actually exist
object directory = subKey.GetValue("InstallationFolder");
if (directory != null)
{
var includeDirectory = Path.Combine(directory.ToString(), "include");
if(Directory.Exists(includeDirectory))
{
// Check that we have enough files in the directory (case where the directory is there but
// completely empty)
if(Directory.EnumerateFiles(includeDirectory, "*.*", SearchOption.TopDirectoryOnly).Count() > 70)
{
return version;
}
else
{
Logger.Error("VS{0} Include directory from [{0}] is missing SDK C++ include files. Check your install",
version,
includeDirectory);
}
}
}
}
}
Logger.Exit("Missing Windows SDK [{0}]. Please, download and install the SDK from Microsoft website (Check for a full install that includes Framework headers and C++ compiler).", string.Join("/", versions));
return null;
}
/// <summary>
/// Processes the specified header headerFile.
/// </summary>
/// <param name="headerFile">The header headerFile.</param>
/// <returns></returns>
public StreamReader Process(string headerFile)
{
StreamReader result = null;
Logger.RunInContext("gccxml", () =>
{
string vsVersion = GetVisualStudioVersion();
ExecutablePath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, ExecutablePath));
if (!File.Exists(ExecutablePath)) Logger.Fatal("gccxml.exe not found from path: [{0}]", ExecutablePath);
if (!File.Exists(headerFile)) Logger.Fatal("C++ Header file [{0}] not found", headerFile);
var currentProcess = new Process();
var startInfo = new ProcessStartInfo(ExecutablePath)
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
WorkingDirectory = Environment.CurrentDirectory
};
var xmlFile = Path.ChangeExtension(headerFile, "xml");
// Delete any previously generated xml file
File.Delete(xmlFile);
var arguments = ""; // "--gccxml-gcc-options " + GccXmlGccOptionsFile;
// Overrides settings for gccxml for compiling Win8 version
arguments += " --gccxml-config \"" + Path.Combine(Path.GetDirectoryName(ExecutablePath), @"..\share\gccxml-0.9\vc" + vsVersion + @"\gccxml_config") + "\"";
arguments += " -fxml=" + xmlFile;
foreach (var directory in GetIncludePaths())
arguments += " " + directory;
startInfo.Arguments = arguments + " " + headerFile;
Console.WriteLine(startInfo.Arguments);
currentProcess.StartInfo = startInfo;
currentProcess.ErrorDataReceived += ProcessErrorFromHeaderFile;
currentProcess.OutputDataReceived += ProcessOutputFromHeaderFile;
currentProcess.Start();
currentProcess.BeginOutputReadLine();
currentProcess.BeginErrorReadLine();
currentProcess.WaitForExit();
currentProcess.Close();
if (!File.Exists(xmlFile) || Logger.HasErrors)
{
Logger.Error("Unable to generate XML file with gccxml [{0}]. Check previous errors.", xmlFile);
}
else
{
result = new StreamReader(xmlFile);
}
});
return result;
}
// E:/Code/Microsoft DirectX SDK (June 2010)//include/xaudio2fx.h:68:1: error:
private static Regex matchFileErrorRegex = new Regex(@"^(.*):(\d+):(\d+):\s+error:(.*)");
/// <summary>
/// Processes the error from header file.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.Diagnostics.DataReceivedEventArgs"/> instance containing the event data.</param>
void ProcessErrorFromHeaderFile(object sender, DataReceivedEventArgs e)
{
bool popContext = false;
try
{
if (e.Data != null)
{
var matchError = matchFileErrorRegex.Match(e.Data);
bool lineFiltered = false;
foreach (var filterError in _filterErrors)
{
if (filterError.Match(e.Data).Success)
{
lineFiltered = true;
break;
}
}
string errorText = e.Data;
if (matchError.Success)
{
Logger.PushLocation(matchError.Groups[1].Value, int.Parse(matchError.Groups[2].Value), int.Parse(matchError.Groups[3].Value));
popContext = true;
errorText = matchError.Groups[4].Value;
}
if (!lineFiltered)
{
if (MatchError.Match(e.Data).Success)
Logger.Error(errorText);
else
Logger.Warning(errorText);
}
else
{
Logger.Warning(errorText);
}
}
}
finally
{
if (popContext)
Logger.PopLocation();
}
}
/// <summary>
/// Processes the output from header file.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.Diagnostics.DataReceivedEventArgs"/> instance containing the event data.</param>
static void ProcessOutputFromHeaderFile(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
Logger.Message(e.Data);
}
}
}
| |
using AdventureWorks.UILogic.Models;
using AdventureWorks.UILogic.Repositories;
using AdventureWorks.UILogic.Services;
using Prism.Commands;
using Prism.Windows.AppModel;
using Prism.Windows.Mvvm;
using Prism.Windows.Navigation;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Threading.Tasks;
using Windows.UI.Xaml.Navigation;
namespace AdventureWorks.UILogic.ViewModels
{
public class CheckoutHubPageViewModel : ViewModelBase
{
private readonly INavigationService _navigationService;
private readonly IAccountService _accountService;
private readonly IOrderRepository _orderRepository;
private readonly IShoppingCartRepository _shoppingCartRepository;
private readonly IShippingAddressUserControlViewModel _shippingAddressViewModel;
private readonly IBillingAddressUserControlViewModel _billingAddressViewModel;
private readonly IPaymentMethodUserControlViewModel _paymentMethodViewModel;
private readonly IAlertMessageService _alertMessageService;
private readonly IResourceLoader _resourceLoader;
private bool _useSameAddressAsShipping;
private bool _isShippingAddressInvalid;
private bool _isBillingAddressInvalid;
private bool _isPaymentMethodInvalid;
public CheckoutHubPageViewModel(INavigationService navigationService,
IAccountService accountService,
IOrderRepository orderRepository,
IShoppingCartRepository shoppingCartRepository,
IShippingAddressUserControlViewModel shippingAddressViewModel,
IBillingAddressUserControlViewModel billingAddressViewModel,
IPaymentMethodUserControlViewModel paymentMethodViewModel,
IResourceLoader resourceLoader,
IAlertMessageService alertMessageService)
{
_navigationService = navigationService;
_accountService = accountService;
_orderRepository = orderRepository;
_shoppingCartRepository = shoppingCartRepository;
_shippingAddressViewModel = shippingAddressViewModel;
_billingAddressViewModel = billingAddressViewModel;
_paymentMethodViewModel = paymentMethodViewModel;
_alertMessageService = alertMessageService;
_resourceLoader = resourceLoader;
GoNextCommand = new DelegateCommand(GoNext);
}
public DelegateCommand GoNextCommand { get; private set; }
public IShippingAddressUserControlViewModel ShippingAddressViewModel
{
get { return _shippingAddressViewModel; }
}
public IBillingAddressUserControlViewModel BillingAddressViewModel
{
get { return _billingAddressViewModel; }
}
public IPaymentMethodUserControlViewModel PaymentMethodViewModel
{
get { return _paymentMethodViewModel; }
}
[RestorableState]
public bool UseSameAddressAsShipping
{
get
{
return _useSameAddressAsShipping;
}
set
{
SetProperty(ref _useSameAddressAsShipping, value);
if (_useSameAddressAsShipping)
{
// Clean the Billing Address values & errors
BillingAddressViewModel.Address = new Address { Id = Guid.NewGuid().ToString() };
}
BillingAddressViewModel.IsEnabled = !value;
}
}
[RestorableState]
public bool IsShippingAddressInvalid
{
get { return _isShippingAddressInvalid; }
private set { SetProperty(ref _isShippingAddressInvalid, value); }
}
[RestorableState]
public bool IsBillingAddressInvalid
{
get { return _isBillingAddressInvalid; }
private set { SetProperty(ref _isBillingAddressInvalid, value); }
}
[RestorableState]
public bool IsPaymentMethodInvalid
{
get { return _isPaymentMethodInvalid; }
private set { SetProperty(ref _isPaymentMethodInvalid, value); }
}
public override void OnNavigatedTo(NavigatedToEventArgs e, Dictionary<string, object> viewModelState)
{
if (viewModelState == null)
{
return;
}
// Try to populate address and payment method controls with default data if available
ShippingAddressViewModel.SetLoadDefault(true);
BillingAddressViewModel.SetLoadDefault(true);
PaymentMethodViewModel.SetLoadDefault(true);
// This ViewModel is an example of composition. The CheckoutHubPageViewModel manages
// three child view models (Shipping Address, Billing Address, and Payment Method).
// Since the FrameNavigationService calls this OnNavigatedTo method, passing in
// a viewModelState dictionary, it is the responsibility of the parent view model
// to manage separate dictionaries for each of its children. If the parent view model
// were to pass its viewModelState dictionary to each of its children, it would be very
// easy for one child view model to write over a sibling view model's state.
if (e.NavigationMode == NavigationMode.New)
{
viewModelState["ShippingViewModel"] = new Dictionary<string, object>();
viewModelState["BillingViewModel"] = new Dictionary<string, object>();
viewModelState["PaymentMethodViewModel"] = new Dictionary<string, object>();
}
ShippingAddressViewModel.OnNavigatedTo(e, viewModelState["ShippingViewModel"] as Dictionary<string, object>);
BillingAddressViewModel.OnNavigatedTo(e, viewModelState["BillingViewModel"] as Dictionary<string, object>);
PaymentMethodViewModel.OnNavigatedTo(e, viewModelState["PaymentMethodViewModel"] as Dictionary<string, object>);
base.OnNavigatedTo(e, viewModelState);
}
public override void OnNavigatingFrom(NavigatingFromEventArgs e, Dictionary<string, object> viewModelState, bool suspending)
{
if (viewModelState == null || viewModelState.Count == 0)
{
return;
}
ShippingAddressViewModel.OnNavigatingFrom(e, viewModelState["ShippingViewModel"] as Dictionary<string, object>, suspending);
BillingAddressViewModel.OnNavigatingFrom(e, viewModelState["BillingViewModel"] as Dictionary<string, object>, suspending);
PaymentMethodViewModel.OnNavigatingFrom(e, viewModelState["PaymentMethodViewModel"] as Dictionary<string, object>, suspending);
base.OnNavigatingFrom(e, viewModelState, suspending);
}
private async void GoNext()
{
IsShippingAddressInvalid = ShippingAddressViewModel.ValidateForm() == false;
IsBillingAddressInvalid = !UseSameAddressAsShipping && BillingAddressViewModel.ValidateForm() == false;
IsPaymentMethodInvalid = PaymentMethodViewModel.ValidateForm() == false;
if (IsShippingAddressInvalid || IsBillingAddressInvalid || IsPaymentMethodInvalid)
{
return;
}
string errorMessage = string.Empty;
try
{
await _accountService.VerifyUserAuthenticationAsync();
await ProcessFormAsync();
}
catch (Exception ex)
{
errorMessage = string.Format(CultureInfo.CurrentCulture, _resourceLoader.GetString("GeneralServiceErrorMessage"), Environment.NewLine, ex.Message);
}
if (!string.IsNullOrWhiteSpace(errorMessage))
{
await _alertMessageService.ShowAsync(errorMessage, _resourceLoader.GetString("ErrorServiceUnreachable"));
}
}
private async Task ProcessFormAsync()
{
if (UseSameAddressAsShipping)
{
BillingAddressViewModel.Address = new Address
{
Id = Guid.NewGuid().ToString(),
AddressType = AddressType.Billing,
FirstName = ShippingAddressViewModel.Address.FirstName,
MiddleInitial = ShippingAddressViewModel.Address.MiddleInitial,
LastName = ShippingAddressViewModel.Address.LastName,
StreetAddress = ShippingAddressViewModel.Address.StreetAddress,
OptionalAddress = ShippingAddressViewModel.Address.OptionalAddress,
City = ShippingAddressViewModel.Address.City,
State = ShippingAddressViewModel.Address.State,
ZipCode = ShippingAddressViewModel.Address.ZipCode,
Phone = ShippingAddressViewModel.Address.Phone
};
}
try
{
await ShippingAddressViewModel.ProcessFormAsync();
await BillingAddressViewModel.ProcessFormAsync();
await PaymentMethodViewModel.ProcessFormAsync();
}
catch (ModelValidationException)
{
// Handle validation exceptions when the order is created.
}
var user = _accountService.SignedInUser;
var shoppingCart = await _shoppingCartRepository.GetShoppingCartAsync();
try
{
// Create an order with the values entered in the form
await _orderRepository.CreateBasicOrderAsync(user.UserName, shoppingCart, ShippingAddressViewModel.Address, BillingAddressViewModel.Address, PaymentMethodViewModel.PaymentMethod);
_navigationService.Navigate("CheckoutSummary", null);
}
catch (ModelValidationException mvex)
{
DisplayOrderErrorMessages(mvex.ValidationResult);
if (_shippingAddressViewModel.Address.Errors.Errors.Count > 0)
{
IsShippingAddressInvalid = true;
}
if (_billingAddressViewModel.Address.Errors.Errors.Count > 0 && !UseSameAddressAsShipping)
{
IsBillingAddressInvalid = true;
}
if (_paymentMethodViewModel.PaymentMethod.Errors.Errors.Count > 0)
{
IsPaymentMethodInvalid = true;
}
}
}
private void DisplayOrderErrorMessages(ModelValidationResult validationResult)
{
var shippingAddressErrors = new Dictionary<string, ReadOnlyCollection<string>>();
var billingAddressErrors = new Dictionary<string, ReadOnlyCollection<string>>();
var paymentMethodErrors = new Dictionary<string, ReadOnlyCollection<string>>();
// Property keys of the form. Format: order.{ShippingAddress/BillingAddress/PaymentMethod}.{Property}
foreach (var propkey in validationResult.ModelState.Keys)
{
string orderPropAndEntityProp = propkey.Substring(propkey.IndexOf('.') + 1); // strip off order. prefix
string orderProperty = orderPropAndEntityProp.Substring(0, orderPropAndEntityProp.IndexOf('.') + 1);
string entityProperty = orderPropAndEntityProp.Substring(orderProperty.IndexOf('.') + 1);
if (orderProperty.ToLower().Contains("shipping"))
{
shippingAddressErrors.Add(entityProperty, new ReadOnlyCollection<string>(validationResult.ModelState[propkey]));
}
if (orderProperty.ToLower().Contains("billing") && !UseSameAddressAsShipping)
{
billingAddressErrors.Add(entityProperty, new ReadOnlyCollection<string>(validationResult.ModelState[propkey]));
}
if (orderProperty.ToLower().Contains("payment"))
{
paymentMethodErrors.Add(entityProperty, new ReadOnlyCollection<string>(validationResult.ModelState[propkey]));
}
}
if (shippingAddressErrors.Count > 0)
{
_shippingAddressViewModel.Address.Errors.SetAllErrors(shippingAddressErrors);
}
if (billingAddressErrors.Count > 0)
{
_billingAddressViewModel.Address.Errors.SetAllErrors(billingAddressErrors);
}
if (paymentMethodErrors.Count > 0)
{
_paymentMethodViewModel.PaymentMethod.Errors.SetAllErrors(paymentMethodErrors);
}
}
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.IO.Packaging;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Globalization;
namespace System.IO.Packaging
{
/// <summary>
/// The package properties are a subset of the standard OLE property sets
/// SummaryInformation and DocumentSummaryInformation, and include such properties
/// as Title and Subject.
/// </summary>
/// <remarks>
/// <para>Setting a property to null deletes this property. 'null' is never strictly speaking
/// a property value, but an absence indicator.</para>
/// </remarks>
internal class PartBasedPackageProperties : PackageProperties
{
#region Constructors
internal PartBasedPackageProperties(Package package)
{
_package = package;
// Initialize literals as Xml Atomic strings.
_nameTable = PackageXmlStringTable.NameTable;
ReadPropertyValuesFromPackage();
// No matter what happens during initialization, the dirty flag should not be set.
_dirty = false;
}
#endregion Constructors
#region Public Properties
/// <value>
/// The primary creator. The identification is environment-specific and
/// can consist of a name, email address, employee ID, etc. It is
/// recommended that this value be only as verbose as necessary to
/// identify the individual.
/// </value>
public override string Creator
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Creator);
}
set
{
RecordNewBinding(PackageXmlEnum.Creator, value);
}
}
/// <value>
/// The title.
/// </value>
public override string Title
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Title);
}
set
{
RecordNewBinding(PackageXmlEnum.Title, value);
}
}
/// <value>
/// The topic of the contents.
/// </value>
public override string Subject
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Subject);
}
set
{
RecordNewBinding(PackageXmlEnum.Subject, value);
}
}
/// <value>
/// The category. This value is typically used by UI applications to create navigation
/// controls.
/// </value>
public override string Category
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Category);
}
set
{
RecordNewBinding(PackageXmlEnum.Category, value);
}
}
/// <value>
/// A delimited set of keywords to support searching and indexing. This
/// is typically a list of terms that are not available elsewhere in the
/// properties.
/// </value>
public override string Keywords
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Keywords);
}
set
{
RecordNewBinding(PackageXmlEnum.Keywords, value);
}
}
/// <value>
/// The description or abstract of the contents.
/// </value>
public override string Description
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Description);
}
set
{
RecordNewBinding(PackageXmlEnum.Description, value);
}
}
/// <value>
/// The type of content represented, generally defined by a specific
/// use and intended audience. Example values include "Whitepaper",
/// "Security Bulletin", and "Exam". (This property is distinct from
/// MIME content types as defined in RFC 2616.)
/// </value>
public override string ContentType
{
get
{
string contentType = GetPropertyValue(PackageXmlEnum.ContentType) as string;
return contentType;
}
set
{
RecordNewBinding(PackageXmlEnum.ContentType, value);
}
}
/// <value>
/// The status of the content. Example values include "Draft",
/// "Reviewed", and "Final".
/// </value>
public override string ContentStatus
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.ContentStatus);
}
set
{
RecordNewBinding(PackageXmlEnum.ContentStatus, value);
}
}
/// <value>
/// The version number. This value is set by the user or by the application.
/// </value>
public override string Version
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Version);
}
set
{
RecordNewBinding(PackageXmlEnum.Version, value);
}
}
/// <value>
/// The revision number. This value indicates the number of saves or
/// revisions. The application is responsible for updating this value
/// after each revision.
/// </value>
public override string Revision
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Revision);
}
set
{
RecordNewBinding(PackageXmlEnum.Revision, value);
}
}
/// <value>
/// The creation date and time.
/// </value>
public override Nullable<DateTime> Created
{
get
{
return GetDateTimePropertyValue(PackageXmlEnum.Created);
}
set
{
RecordNewBinding(PackageXmlEnum.Created, value);
}
}
/// <value>
/// The date and time of the last modification.
/// </value>
public override Nullable<DateTime> Modified
{
get
{
return GetDateTimePropertyValue(PackageXmlEnum.Modified);
}
set
{
RecordNewBinding(PackageXmlEnum.Modified, value);
}
}
/// <value>
/// The user who performed the last modification. The identification is
/// environment-specific and can consist of a name, email address,
/// employee ID, etc. It is recommended that this value be only as
/// verbose as necessary to identify the individual.
/// </value>
public override string LastModifiedBy
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.LastModifiedBy);
}
set
{
RecordNewBinding(PackageXmlEnum.LastModifiedBy, value);
}
}
/// <value>
/// The date and time of the last printing.
/// </value>
public override Nullable<DateTime> LastPrinted
{
get
{
return GetDateTimePropertyValue(PackageXmlEnum.LastPrinted);
}
set
{
RecordNewBinding(PackageXmlEnum.LastPrinted, value);
}
}
/// <value>
/// A language of the intellectual content of the resource
/// </value>
public override string Language
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Language);
}
set
{
RecordNewBinding(PackageXmlEnum.Language, value);
}
}
/// <value>
/// A unique identifier.
/// </value>
public override string Identifier
{
get
{
return (string)GetPropertyValue(PackageXmlEnum.Identifier);
}
set
{
RecordNewBinding(PackageXmlEnum.Identifier, value);
}
}
#endregion Public Properties
#region Internal Methods
// Invoked from Package.Flush.
// The expectation is that whatever is currently dirty will get flushed.
internal void Flush()
{
if (!_dirty)
return;
// Make sure there is a part to write to and that it contains
// the expected start markup.
EnsureXmlWriter();
// Write the property elements and clear _dirty.
SerializeDirtyProperties();
// add closing markup and close the writer.
CloseXmlWriter();
}
// Invoked from Package.Close.
internal void Close()
{
Flush();
}
#endregion Internal Methods
#region Private Methods
// The property store is implemented as a hash table of objects.
// Keys are taken from the set of string constants defined in this
// class and compared by their references rather than their values.
private object GetPropertyValue(PackageXmlEnum propertyName)
{
_package.ThrowIfWriteOnly();
if (!_propertyDictionary.ContainsKey(propertyName))
return null;
return _propertyDictionary[propertyName];
}
// Shim function to adequately cast the result of GetPropertyValue.
private Nullable<DateTime> GetDateTimePropertyValue(PackageXmlEnum propertyName)
{
object valueObject = GetPropertyValue(propertyName);
if (valueObject == null)
return null;
// If an object is there, it will be a DateTime (not a Nullable<DateTime>).
return (Nullable<DateTime>)valueObject;
}
// Set new property value.
// Override that sets the initializing flag to false to reflect the default
// situation: recording a binding to implement a value assignment.
private void RecordNewBinding(PackageXmlEnum propertyenum, object value)
{
RecordNewBinding(propertyenum, value, false /* not invoked at construction */, null);
}
// Set new property value.
// Null value is passed for deleting a property.
// While initializing, we are not assigning new values, and so the dirty flag should
// stay untouched.
private void RecordNewBinding(PackageXmlEnum propertyenum, object value, bool initializing, XmlReader reader)
{
// If we are reading values from the package, reader cannot be null
Debug.Assert(!initializing || reader != null);
if (!initializing)
_package.ThrowIfReadOnly();
// Case of an existing property.
if (_propertyDictionary.ContainsKey(propertyenum))
{
// Parsing should detect redundant entries.
if (initializing)
{
throw new XmlException(SR.Format(SR.DuplicateCorePropertyName, reader.Name),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// Nullable<DateTime> values can be checked against null
if (value == null) // a deletion
{
_propertyDictionary.Remove(propertyenum);
}
else // an update
{
_propertyDictionary[propertyenum] = value;
}
// If the binding is an assignment rather than an initialization, set the dirty flag.
_dirty = !initializing;
}
// Case of an initial value being set for a property.
else
{
_propertyDictionary.Add(propertyenum, value);
// If the binding is an assignment rather than an initialization, set the dirty flag.
_dirty = !initializing;
}
}
// Initialize object from property values found in package.
// All values will remain null if the package is not enabled for reading.
private void ReadPropertyValuesFromPackage()
{
Debug.Assert(_propertyPart == null); // This gets called exclusively from constructor.
// Don't try to read properties from the package it does not have read access
if (_package.FileOpenAccess == FileAccess.Write)
return;
_propertyPart = GetPropertyPart();
if (_propertyPart == null)
return;
ParseCorePropertyPart(_propertyPart);
}
// Locate core properties part using the package relationship that points to it.
private PackagePart GetPropertyPart()
{
// Find a package-wide relationship of type CoreDocumentPropertiesRelationshipType.
PackageRelationship corePropertiesRelationship = GetCorePropertiesRelationship();
if (corePropertiesRelationship == null)
return null;
// Retrieve the part referenced by its target URI.
if (corePropertiesRelationship.TargetMode != TargetMode.Internal)
throw new FileFormatException(SR.NoExternalTargetForMetadataRelationship);
PackagePart propertiesPart = null;
Uri propertiesPartUri = PackUriHelper.ResolvePartUri(
PackUriHelper.PackageRootUri,
corePropertiesRelationship.TargetUri);
if (!_package.PartExists(propertiesPartUri))
throw new FileFormatException(SR.DanglingMetadataRelationship);
propertiesPart = _package.GetPart(propertiesPartUri);
if (!propertiesPart.ValidatedContentType.AreTypeAndSubTypeEqual(s_coreDocumentPropertiesContentType))
{
throw new FileFormatException(SR.WrongContentTypeForPropertyPart);
}
return propertiesPart;
}
// Find a package-wide relationship of type CoreDocumentPropertiesRelationshipType.
private PackageRelationship GetCorePropertiesRelationship()
{
PackageRelationship propertiesPartRelationship = null;
foreach (PackageRelationship rel
in _package.GetRelationshipsByType(CoreDocumentPropertiesRelationshipType))
{
if (propertiesPartRelationship != null)
{
throw new FileFormatException(SR.MoreThanOneMetadataRelationships);
}
propertiesPartRelationship = rel;
}
return propertiesPartRelationship;
}
// Deserialize properties part.
private void ParseCorePropertyPart(PackagePart part)
{
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.NameTable = _nameTable;
using (Stream stream = part.GetStream(FileMode.Open, FileAccess.Read))
// Create a reader that uses _nameTable so as to use the set of tag literals
// in effect as a set of atomic identifiers.
using (XmlReader reader = XmlReader.Create(stream, xrs))
{
//This method expects the reader to be in ReadState.Initial.
//It will make the first read call.
PackagingUtilities.PerformInitialReadAndVerifyEncoding(reader);
//Note: After the previous method call the reader should be at the first tag in the markup.
//MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
//If the reader is currently at a content node then this function call is a no-op
if (reader.MoveToContent() != XmlNodeType.Element
|| (object)reader.NamespaceURI != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.PackageCorePropertiesNamespace)
|| (object)reader.LocalName != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.CoreProperties))
{
throw new XmlException(SR.CorePropertiesElementExpected,
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// The schema is closed and defines no attributes on the root element.
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 0)
{
throw new XmlException(SR.Format(SR.PropertyWrongNumbOfAttribsDefinedOn, reader.Name),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// Iterate through property elements until EOF. Note the proper closing of all
// open tags is checked by the reader itself.
// This loop deals only with depth-1 start tags. Handling of element content
// is delegated to dedicated functions.
int attributesCount;
while (reader.Read() && reader.MoveToContent() != XmlNodeType.None)
{
// Ignore end-tags. We check element errors on opening tags.
if (reader.NodeType == XmlNodeType.EndElement)
continue;
// Any content markup that is not an element here is unexpected.
if (reader.NodeType != XmlNodeType.Element)
{
throw new XmlException(SR.PropertyStartTagExpected,
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// Any element below the root should open at level 1 exclusively.
if (reader.Depth != 1)
{
throw new XmlException(SR.NoStructuredContentInsideProperties,
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
attributesCount = PackagingUtilities.GetNonXmlnsAttributeCount(reader);
// Property elements can occur in any order (xsd:all).
object localName = reader.LocalName;
PackageXmlEnum xmlStringIndex = PackageXmlStringTable.GetEnumOf(localName);
String valueType = PackageXmlStringTable.GetValueType(xmlStringIndex);
if (Array.IndexOf(s_validProperties, xmlStringIndex) == -1) // An unexpected element is an error.
{
throw new XmlException(
SR.Format(SR.InvalidPropertyNameInCorePropertiesPart, reader.LocalName),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// Any element not in the valid core properties namespace is unexpected.
// The following is an object comparison, not a string comparison.
if ((object)reader.NamespaceURI != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlStringTable.GetXmlNamespace(xmlStringIndex)))
{
throw new XmlException(SR.UnknownNamespaceInCorePropertiesPart,
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
if (String.CompareOrdinal(valueType, "String") == 0)
{
// The schema is closed and defines no attributes on this type of element.
if (attributesCount != 0)
{
throw new XmlException(SR.Format(SR.PropertyWrongNumbOfAttribsDefinedOn, reader.Name),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
RecordNewBinding(xmlStringIndex, GetStringData(reader), true /*initializing*/, reader);
}
else if (String.CompareOrdinal(valueType, "DateTime") == 0)
{
int allowedAttributeCount = (object)reader.NamespaceURI ==
PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.DublinCoreTermsNamespace)
? 1 : 0;
// The schema is closed and defines no attributes on this type of element.
if (attributesCount != allowedAttributeCount)
{
throw new XmlException(SR.Format(SR.PropertyWrongNumbOfAttribsDefinedOn, reader.Name),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
if (allowedAttributeCount != 0)
{
ValidateXsiType(reader,
PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.DublinCoreTermsNamespace),
W3cdtf);
}
RecordNewBinding(xmlStringIndex, GetDateData(reader), true /*initializing*/, reader);
}
else // An unexpected element is an error.
{
Debug.Assert(false, "Unknown value type for properties");
}
}
}
}
// This method validates xsi:type="dcterms:W3CDTF"
// The value of xsi:type is a qualified name. It should have a prefix that matches
// the xml namespace (ns) within the scope and the name that matches name
// The comparisons should be case-sensitive comparisons
internal static void ValidateXsiType(XmlReader reader, Object ns, string name)
{
// Get the value of xsi;type
String typeValue = reader.GetAttribute(PackageXmlStringTable.GetXmlString(PackageXmlEnum.Type),
PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlSchemaInstanceNamespace));
// Missing xsi:type
if (typeValue == null)
{
throw new XmlException(SR.Format(SR.UnknownDCDateTimeXsiType, reader.Name),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
int index = typeValue.IndexOf(':');
// The value of xsi:type is not a qualified name
if (index == -1)
{
throw new XmlException(SR.Format(SR.UnknownDCDateTimeXsiType, reader.Name),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// Check the following conditions
// The namespace of the prefix (string before ":") matches "ns"
// The name (string after ":") matches "name"
if (!Object.ReferenceEquals(ns, reader.LookupNamespace(typeValue.Substring(0, index)))
|| String.CompareOrdinal(name, typeValue.Substring(index + 1, typeValue.Length - index - 1)) != 0)
{
throw new XmlException(SR.Format(SR.UnknownDCDateTimeXsiType, reader.Name),
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
}
// Expect to find text data and return its value.
private string GetStringData(XmlReader reader)
{
if (reader.IsEmptyElement)
return string.Empty;
reader.Read();
if (reader.MoveToContent() == XmlNodeType.EndElement)
return string.Empty;
// If there is any content in the element, it should be text content and nothing else.
if (reader.NodeType != XmlNodeType.Text)
{
throw new XmlException(SR.NoStructuredContentInsideProperties,
null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
return reader.Value;
}
// Expect to find text data and return its value as DateTime.
private Nullable<DateTime> GetDateData(XmlReader reader)
{
string data = GetStringData(reader);
DateTime dateTime;
try
{
// Note: No more than 7 second decimals are accepted by the
// list of formats given. There currently is no method that
// would perform XSD-compliant parsing.
dateTime = DateTime.ParseExact(data, s_dateTimeFormats, CultureInfo.InvariantCulture, DateTimeStyles.None);
}
catch (FormatException exc)
{
throw new XmlException(SR.XsdDateTimeExpected,
exc, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
return dateTime;
}
// Make sure there is a part to write to and that it contains
// the expected start markup.
private void EnsureXmlWriter()
{
if (_xmlWriter != null)
return;
EnsurePropertyPart(); // Should succeed or throw an exception.
Stream writerStream = new IgnoreFlushAndCloseStream(_propertyPart.GetStream(FileMode.Create, FileAccess.Write));
_xmlWriter = XmlWriter.Create(writerStream, new XmlWriterSettings { Encoding = System.Text.Encoding.UTF8 });
WriteXmlStartTagsForPackageProperties();
}
// Create a property part if none exists yet.
private void EnsurePropertyPart()
{
if (_propertyPart != null)
return;
// If _propertyPart is null, no property part existed when this object was created,
// and this function is being called for the first time.
// However, when read access is available, we can afford the luxury of checking whether
// a property part and its referring relationship got correctly created in the meantime
// outside of this class.
// In write-only mode, it is impossible to perform this check, and the external creation
// scenario will result in an exception being thrown.
if (_package.FileOpenAccess == FileAccess.Read || _package.FileOpenAccess == FileAccess.ReadWrite)
{
_propertyPart = GetPropertyPart();
if (_propertyPart != null)
return;
}
CreatePropertyPart();
}
// Create a new property relationship pointing to a new property part.
// If only this class is used for manipulating property relationships, there cannot be a
// pre-existing dangling property relationship.
// No check is performed here for other classes getting misused insofar as this function
// has to work in write-only mode.
private void CreatePropertyPart()
{
_propertyPart = _package.CreatePart(GeneratePropertyPartUri(), s_coreDocumentPropertiesContentType.ToString());
_package.CreateRelationship(_propertyPart.Uri, TargetMode.Internal,
CoreDocumentPropertiesRelationshipType);
}
private Uri GeneratePropertyPartUri()
{
string propertyPartName = DefaultPropertyPartNamePrefix
+ Guid.NewGuid().ToString(GuidStorageFormatString)
+ DefaultPropertyPartNameExtension;
return PackUriHelper.CreatePartUri(new Uri(propertyPartName, UriKind.Relative));
}
private void WriteXmlStartTagsForPackageProperties()
{
_xmlWriter.WriteStartDocument();
// <coreProperties
_xmlWriter.WriteStartElement(PackageXmlStringTable.GetXmlString(PackageXmlEnum.CoreProperties), // local name
PackageXmlStringTable.GetXmlString(PackageXmlEnum.PackageCorePropertiesNamespace)); // namespace
// xmlns:dc
_xmlWriter.WriteAttributeString(PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlNamespacePrefix),
PackageXmlStringTable.GetXmlString(PackageXmlEnum.DublinCorePropertiesNamespacePrefix),
null,
PackageXmlStringTable.GetXmlString(PackageXmlEnum.DublinCorePropertiesNamespace));
// xmlns:dcterms
_xmlWriter.WriteAttributeString(PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlNamespacePrefix),
PackageXmlStringTable.GetXmlString(PackageXmlEnum.DublincCoreTermsNamespacePrefix),
null,
PackageXmlStringTable.GetXmlString(PackageXmlEnum.DublinCoreTermsNamespace));
// xmlns:xsi
_xmlWriter.WriteAttributeString(PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlNamespacePrefix),
PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlSchemaInstanceNamespacePrefix),
null,
PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlSchemaInstanceNamespace));
}
// Write the property elements and clear _dirty.
private void SerializeDirtyProperties()
{
// Create a property element for each non-null entry.
foreach (KeyValuePair<PackageXmlEnum, Object> entry in _propertyDictionary)
{
Debug.Assert(entry.Value != null);
PackageXmlEnum propertyNamespace = PackageXmlStringTable.GetXmlNamespace(entry.Key);
_xmlWriter.WriteStartElement(PackageXmlStringTable.GetXmlString(entry.Key),
PackageXmlStringTable.GetXmlString(propertyNamespace));
if (entry.Value is Nullable<DateTime>)
{
if (propertyNamespace == PackageXmlEnum.DublinCoreTermsNamespace)
{
// xsi:type=
_xmlWriter.WriteStartAttribute(PackageXmlStringTable.GetXmlString(PackageXmlEnum.Type),
PackageXmlStringTable.GetXmlString(PackageXmlEnum.XmlSchemaInstanceNamespace));
// "dcterms:W3CDTF"
_xmlWriter.WriteQualifiedName(W3cdtf,
PackageXmlStringTable.GetXmlString(PackageXmlEnum.DublinCoreTermsNamespace));
_xmlWriter.WriteEndAttribute();
}
// Use sortable ISO 8601 date/time pattern. Include second fractions down to the 100-nanosecond interval,
// which is the definition of a "tick" for the DateTime type.
_xmlWriter.WriteString(XmlConvert.ToString(((Nullable<DateTime>)entry.Value).Value.ToUniversalTime(), "yyyy-MM-ddTHH:mm:ss.fffffffZ"));
}
else
{
// The following uses the fact that ToString is virtual.
_xmlWriter.WriteString(entry.Value.ToString());
}
_xmlWriter.WriteEndElement();
}
// Mark properties as saved.
_dirty = false;
}
// Add end markup and close the writer.
private void CloseXmlWriter()
{
// Close the root element.
_xmlWriter.WriteEndElement();
// Close the writer itself.
_xmlWriter.Dispose();
// Make sure we know it's closed.
_xmlWriter = null;
}
#endregion Private Methods
#region Private Fields
private Package _package;
private PackagePart _propertyPart;
private XmlWriter _xmlWriter;
// Table of objects from the closed set of literals defined below.
// (Uses object comparison rather than string comparison.)
private const int NumCoreProperties = 16;
private Dictionary<PackageXmlEnum, Object> _propertyDictionary = new Dictionary<PackageXmlEnum, Object>(NumCoreProperties);
private bool _dirty = false;
// This System.Xml.NameTable makes sure that we use the same references to strings
// throughout (including when parsing Xml) and so can perform reference comparisons
// rather than value comparisons.
private NameTable _nameTable;
// Literals.
private static readonly ContentType s_coreDocumentPropertiesContentType
= new ContentType("application/vnd.openxmlformats-package.core-properties+xml");
private const string CoreDocumentPropertiesRelationshipType
= "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties";
private const string DefaultPropertyPartNamePrefix =
"/package/services/metadata/core-properties/";
private const string W3cdtf = "W3CDTF";
private const string DefaultPropertyPartNameExtension = ".psmdcp";
private const string GuidStorageFormatString = @"N"; // N - simple format without adornments
private static PackageXmlEnum[] s_validProperties = new PackageXmlEnum[] {
PackageXmlEnum.Creator,
PackageXmlEnum.Identifier,
PackageXmlEnum.Title,
PackageXmlEnum.Subject,
PackageXmlEnum.Description,
PackageXmlEnum.Language,
PackageXmlEnum.Created,
PackageXmlEnum.Modified,
PackageXmlEnum.ContentType,
PackageXmlEnum.Keywords,
PackageXmlEnum.Category,
PackageXmlEnum.Version,
PackageXmlEnum.LastModifiedBy,
PackageXmlEnum.ContentStatus,
PackageXmlEnum.Revision,
PackageXmlEnum.LastPrinted
};
// Array of formats to supply to XmlConvert.ToDateTime or DateTime.ParseExact.
// xsd:DateTime requires full date time in sortable (ISO 8601) format.
// It can be expressed in local time, universal time (Z), or relative to universal time (zzz).
// Negative years are accepted.
// IMPORTANT: Second fractions are recognized only down to 1 tenth of a microsecond because this is the resolution
// of the DateTime type. The Xml standard, however, allows any number of decimals; but XmlConvert only offers
// this very awkward API with an explicit pattern enumeration.
private static readonly string[] s_dateTimeFormats = new string[] {
"yyyy-MM-ddTHH:mm:ss",
"yyyy-MM-ddTHH:mm:ssZ",
"yyyy-MM-ddTHH:mm:sszzz",
@"\-yyyy-MM-ddTHH:mm:ss",
@"\-yyyy-MM-ddTHH:mm:ssZ",
@"\-yyyy-MM-ddTHH:mm:sszzz",
"yyyy-MM-ddTHH:mm:ss.ff",
"yyyy-MM-ddTHH:mm:ss.fZ",
"yyyy-MM-ddTHH:mm:ss.fzzz",
@"\-yyyy-MM-ddTHH:mm:ss.f",
@"\-yyyy-MM-ddTHH:mm:ss.fZ",
@"\-yyyy-MM-ddTHH:mm:ss.fzzz",
"yyyy-MM-ddTHH:mm:ss.ff",
"yyyy-MM-ddTHH:mm:ss.ffZ",
"yyyy-MM-ddTHH:mm:ss.ffzzz",
@"\-yyyy-MM-ddTHH:mm:ss.ff",
@"\-yyyy-MM-ddTHH:mm:ss.ffZ",
@"\-yyyy-MM-ddTHH:mm:ss.ffzzz",
"yyyy-MM-ddTHH:mm:ss.fff",
"yyyy-MM-ddTHH:mm:ss.fffZ",
"yyyy-MM-ddTHH:mm:ss.fffzzz",
@"\-yyyy-MM-ddTHH:mm:ss.fff",
@"\-yyyy-MM-ddTHH:mm:ss.fffZ",
@"\-yyyy-MM-ddTHH:mm:ss.fffzzz",
"yyyy-MM-ddTHH:mm:ss.ffff",
"yyyy-MM-ddTHH:mm:ss.ffffZ",
"yyyy-MM-ddTHH:mm:ss.ffffzzz",
@"\-yyyy-MM-ddTHH:mm:ss.ffff",
@"\-yyyy-MM-ddTHH:mm:ss.ffffZ",
@"\-yyyy-MM-ddTHH:mm:ss.ffffzzz",
"yyyy-MM-ddTHH:mm:ss.fffff",
"yyyy-MM-ddTHH:mm:ss.fffffZ",
"yyyy-MM-ddTHH:mm:ss.fffffzzz",
@"\-yyyy-MM-ddTHH:mm:ss.fffff",
@"\-yyyy-MM-ddTHH:mm:ss.fffffZ",
@"\-yyyy-MM-ddTHH:mm:ss.fffffzzz",
"yyyy-MM-ddTHH:mm:ss.ffffff",
"yyyy-MM-ddTHH:mm:ss.ffffffZ",
"yyyy-MM-ddTHH:mm:ss.ffffffzzz",
@"\-yyyy-MM-ddTHH:mm:ss.ffffff",
@"\-yyyy-MM-ddTHH:mm:ss.ffffffZ",
@"\-yyyy-MM-ddTHH:mm:ss.ffffffzzz",
"yyyy-MM-ddTHH:mm:ss.fffffff",
"yyyy-MM-ddTHH:mm:ss.fffffffZ",
"yyyy-MM-ddTHH:mm:ss.fffffffzzz",
@"\-yyyy-MM-ddTHH:mm:ss.fffffff",
@"\-yyyy-MM-ddTHH:mm:ss.fffffffZ",
@"\-yyyy-MM-ddTHH:mm:ss.fffffffzzz",
};
#endregion Private Fields
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace WebApiUniqueConstraintHandling.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) 2010-2013 SharpDoc - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using HtmlAgilityPack;
using SharpDoc.Logging;
namespace SharpDoc.Model
{
/// <summary>
/// A delegate to create an HTML string from a template name used by <see cref="NTopic"/>
/// </summary>
/// <param name="filePath">Name of the template (currently supported are an html file or markdown file).</param>
/// <returns>A HTML content</returns>
public delegate string TopicContentLoaderDelegate(string filePath);
/// <summary>
/// Documentation topic store in an external file.
/// </summary>
[XmlType("topic")]
public class NTopic : IModelReference
{
/// <summary>
/// Id for the default class library topic
/// </summary>
public const string ClassLibraryTopicId = "X:ClassLibraryReference";
/// <summary>
/// Id for the default search results topic
/// </summary>
public const string SearchResultsTopicId = "X:SearchResults";
/// <summary>
/// Initializes a new instance of the <see cref="NTopic"/> class.
/// </summary>
public NTopic()
{
SubTopics = new List<NTopic>();
Resources = new List<string>();
Excludes = new List<string>();
Category = "Article";
}
/// <summary>
/// Initializes a new instance of the <see cref="NTopic"/> class.
/// </summary>
/// <param name="reference">The reference.</param>
public NTopic(IModelReference reference)
{
SubTopics = new List<NTopic>();
Resources = new List<string>();
Excludes = new List<string>();
Id = reference.Id;
Index = reference.Index;
PageId = reference.PageId;
PageTitle = reference.PageTitle;
Name = reference.Name;
FullName = reference.FullName;
Category = reference.Category;
}
/// <summary>
/// Gets or sets the XML generated comment ID.
/// See http://msdn.microsoft.com/en-us/library/fsbx0t7x.aspx for more information.
/// </summary>
/// <value>The id.</value>
[XmlAttribute("id")]
public string Id { get; set; }
/// <summary>
/// Gets or sets the unique index of this node.
/// </summary>
/// <value>
/// The unique index.
/// </value>
[XmlAttribute("index")]
public int Index { get; set; }
/// <summary>
/// Gets or sets the normalized id. This is a normalized version of the <see cref="IModelReference.Id"/> that
/// can be used for filename.
/// </summary>
/// <value>The file id.</value>
[XmlAttribute("page-id")]
public string PageId { get; set; }
/// <summary>
/// Gets or sets the page title.
/// </summary>
/// <value>
/// The page title.
/// </value>
[XmlAttribute("page-title")]
public string PageTitle { get; set; }
/// <summary>
/// Gets or sets the name of this instance.
/// </summary>
/// <value>The name.</value>
[XmlAttribute("name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the full name of this instance.
/// </summary>
/// <value>The full name.</value>
[XmlAttribute("fullname")]
public string FullName { get; set; }
/// <summary>
/// Gets or sets the category.
/// </summary>
/// <value>
/// The category.
/// </value>
[XmlAttribute("category")]
public string Category { get; set; }
[XmlIgnore]
public IModelReference Assembly { get; set; }
/// <summary>
/// Gets or sets the name of the file that contains the documentation.
/// </summary>
/// <value>The name of the file.</value>
[XmlAttribute("filename")]
public string FileName { get; set; }
/// <summary>
/// Gets or sets a value indicating whether topic children will be inlined instead of using the topic itself.
/// </summary>
/// <value>
/// <c>true</c> if [inline]; otherwise, <c>false</c>.
/// </value>
[XmlAttribute("inline")]
public bool Inline { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [use page id URL].
/// </summary>
/// <value>
/// <c>true</c> if [use page id URL]; otherwise, <c>false</c>.
/// </value>
[XmlAttribute("on-url")]
public bool IsPageIdOnUrl { get; set; }
/// <summary>
/// Gets or sets the sub topics.
/// </summary>
/// <value>The sub topics.</value>
[XmlElement("topic")]
public List<NTopic> SubTopics { get; set; }
/// <summary>
/// Gets or sets the parameters.
/// </summary>
/// <value>
/// The parameters.
/// </value>
[XmlElement("param")]
public List<ConfigParam> Parameters { get; set; }
/// <summary>
/// Gets or sets the excludes.
/// </summary>
/// <value>
/// The excludes.
/// </value>
[XmlElement("exclude")]
public List<string> Excludes { get; set; }
/// <summary>
/// Gets or sets the attached resources.
/// </summary>
/// <value>
/// The attached resources.
/// </value>
[XmlElement("resource")]
public List<string> Resources { get; set; }
/// <summary>
/// Gets or sets the web document.
/// </summary>
/// <value>The web document.</value>
[XmlAttribute("webdoc")]
public string WebDoc { get; set; }
/// <summary>
/// Gets or sets the html content. This is loaded from the filename.
/// </summary>
/// <value>The content.</value>
[XmlIgnore]
public string Content { get; set; }
/// <summary>
/// Gets or sets the parent topic.
/// </summary>
/// <value>The parent topic.</value>
[XmlIgnore]
public NTopic Parent { get; set; }
/// <summary>
/// Gets or sets the class node.
/// </summary>
/// <value>
/// The class node.
/// </value>
[XmlIgnore]
public NModelBase AttachedClassNode { get; set; }
/// <inheritdoc/>
[XmlIgnore]
public XmlNode DocNode { get; set; }
/// <inheritdoc/>
[XmlIgnore]
public string Description { get; set; }
/// <inheritdoc/>
[XmlIgnore]
public string Remarks { get; set; }
/// <inheritdoc/>
[XmlIgnore]
public XmlNode WebDocPage { get; set; }
/// <inheritdoc/>
[XmlIgnore]
public XmlNode InheritDoc { get; set; }
[XmlIgnore]
public Config Config { get; set; }
/// <summary>
/// Gets a value indicating whether this instance is class library.
/// </summary>
/// <value>
/// <c>true</c> if this instance is class library; otherwise, <c>false</c>.
/// </value>
[XmlIgnore]
public bool IsClassLibrary
{
get { return Id == ClassLibraryTopicId; }
}
/// <summary>
/// Gets a value indicating whether this instance is search result.
/// </summary>
/// <value>
/// <c>true</c> if this instance is search result; otherwise, <c>false</c>.
/// </value>
[XmlIgnore]
public bool IsSearchResult
{
get { return Id == SearchResultsTopicId; }
}
/// <summary>
/// Finds the topic by id.
/// </summary>
/// <param name="topicId">The topic id.</param>
/// <returns></returns>
public NTopic FindTopicById(string topicId)
{
if (Id == topicId)
return this;
return FindTopicById(SubTopics, topicId);
}
/// <summary>
/// Performs an action on each each topic.
/// </summary>
/// <param name="topicFunction">The topic function.</param>
public void ForEachTopic(Action<NTopic> topicFunction)
{
topicFunction(this);
foreach (var subTopic in SubTopics)
{
subTopic.ForEachTopic(topicFunction);
}
}
/// <summary>
/// Finds the topic by id.
/// </summary>
/// <param name="topics">The topics.</param>
/// <param name="topicId">The topic id.</param>
/// <returns></returns>
public static NTopic FindTopicById(IEnumerable<NTopic> topics, string topicId)
{
NTopic topicFound = null;
foreach (var topic in topics)
{
topicFound = topic.FindTopicById(topicId);
if (topicFound != null)
break;
}
return topicFound;
}
/// <summary>
/// Associate topics with their parent
/// </summary>
public void BuildParents(NTopic parentTopic = null)
{
Parent = parentTopic;
foreach (var subTopic in SubTopics)
subTopic.BuildParents(this);
}
/// <summary>
/// Gets the parents of this instance.
/// </summary>
/// <returns>Parents of this instance</returns>
/// <remarks>
/// The parents is ordered from the root level to this instance (excluding this instance)
/// </remarks>
public List<NTopic> GetParents()
{
var topics = new List<NTopic>();
var topic = Parent;
while (topic != null)
{
topics.Insert(0, topic);
topic = topic.Parent;
}
return topics;
}
/// <summary>
/// Loads the content of this topic.
/// </summary>
/// <param name="contentLoader">The template factory.</param>
/// <exception cref="System.ArgumentNullException">contentLoader</exception>
public void Init(TopicContentLoaderDelegate contentLoader)
{
if (contentLoader == null) throw new ArgumentNullException("contentLoader");
// Check that id is valid
if (string.IsNullOrEmpty(Id))
Logger.Error("Missing id for topic [{0}]", this);
// Check that name is valid
if (string.IsNullOrEmpty(Name))
{
if (Id == ClassLibraryTopicId)
{
Name = "Class Library";
}
else
{
Logger.Error("Missing name for topic [{0}]", this);
}
}
// Copy Name to Fullname if empty
if (string.IsNullOrEmpty(FullName))
FullName = Name;
if (string.IsNullOrEmpty(PageTitle))
PageTitle = Name;
var rootPath = Path.GetDirectoryName(Config.FilePath);
rootPath = rootPath ?? "";
// Initialize sub topics
foreach(var topic in SubTopics)
topic.Init(contentLoader);
// Create non existing topic files based on template
if (Config.TopicTemplate != null && File.Exists(Config.TopicTemplate))
{
var regex = new Regex(@"(\$\w+)");
if (FileName != null && !File.Exists(FileName))
{
var content = File.ReadAllText(Config.TopicTemplate);
content = regex.Replace(
content,
match =>
{
var propertyName = match.Groups[1].Value.Substring(1);
var value = this.GetType().GetProperty(propertyName).GetValue(this, null);
return value == null ? string.Empty : value.ToString();
});
File.WriteAllText(FileName, content);
}
}
if (Id != ClassLibraryTopicId)
{
// Load content file
if (!string.IsNullOrEmpty(FileName))
{
string filePath = null;
try
{
filePath = Path.Combine(rootPath, FileName);
var rawContent = contentLoader(filePath);
if (rawContent == null)
{
Logger.Warning("Cannot use template documentation [{0}] not supported", FileName);
return;
}
var htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(rawContent);
// Override title
var titleNode = htmlDocument.DocumentNode.SelectSingleNode("html/head/title");
if (titleNode != null)
{
PageTitle = titleNode.InnerText;
Name = titleNode.InnerText;
}
// Get body
var bodyNode = htmlDocument.DocumentNode.Descendants("body").FirstOrDefault();
Content = bodyNode == null ? rawContent : bodyNode.InnerHtml;
Content = Content.Trim();
}
catch (Exception ex)
{
Logger.Error("Cannot load content for topic [{0}] from path [{1}]. Reason: {2}", this, filePath, ex.Message);
}
}
else if (!string.IsNullOrEmpty(WebDoc))
{
Content = "<webdoc>" + WebDoc + "</webdoc>";
}
else
{
// Check that filename is valid
Logger.Error("Filname or WebDoc for topic [{0}] cannot be empty", this);
}
}
}
/// <summary>
/// Gets the default class library topic.
/// </summary>
/// <value>The default class library topic.</value>
public static NTopic DefaultClassLibraryTopic
{
get
{
return new NTopic()
{
Index = 0,
Id = ClassLibraryTopicId,
PageId = "api",
Name = "Class Library Reference",
PageTitle = "Class Library Reference",
};
}
}
/// <summary>
/// Gets the default search results topic.
/// </summary>
/// <value>The default search results topic.</value>
public static NTopic DefaultSearchResultsTopic
{
get
{
return new NTopic()
{
Id = SearchResultsTopicId,
PageId = "search-results",
Name = "Search results",
PageTitle = "Search results",
};
}
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
return string.Format(System.Globalization.CultureInfo.InvariantCulture, "Id: {0}, PageId: {1}, Name: {2}, FullName: {3}, FileName: {4}, SubTopics.Count: {5}", Id, PageId, Name, FullName, FileName, SubTopics.Count);
}
}
}
| |
/*******************************************************************************
* Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and
* limitations under the License.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
* API Version: 2012-11-05
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.SQS.Model;
using Amazon.SQS.Util;
using Amazon.Util;
using Attribute = Amazon.SQS.Model.Attribute;
using ErrorResponse = Amazon.SQS.Model.ErrorResponse;
namespace Amazon.SQS
{
/// <summary>
/// AmazonSQSClient is an implementation of AmazonSQS;
/// the client allows you to manage your AmazonSQS resources.<br />
/// If you want to use the AmazonSQSClient from a Medium Trust
/// hosting environment, please create the client with an
/// AmazonSQSConfig object whose UseSecureStringForAwsSecretKey
/// property is false.
/// </summary>
/// <remarks>
/// Amazon Simple Queue Service (Amazon SQS) offers a reliable, highly scalable hosted queue for storing
/// messages as they travel between computers. By using Amazon SQS, developers can simply move data between
/// distributed application components performing different tasks, without losing messages or requiring each
/// component to be always available. Amazon SQS works by exposing Amazon's web-scale messaging infrastructure
/// as a web service. Any computer on the Internet can add or read messages without any installed software or
/// special firewall configurations. Components of applications using Amazon SQS can run independently, and do
/// not need to be on the same network, developed with the same technologies, or running at the same time.
/// </remarks>
/// <seealso cref="P:Amazon.SQS.AmazonSQSConfig.UseSecureStringForAwsSecretKey"/>
public class AmazonSQSClient : AmazonSQS
{
private bool ownCredentials;
private AWSCredentials credentials;
private AmazonSQSConfig config;
private bool disposed;
#region Dispose Pattern Implementation
/// <summary>
/// Implements the Dispose pattern for the AmazonSQSClient
/// </summary>
/// <param name="fDisposing">Whether this object is being disposed via a call to Dispose
/// or garbage collected.</param>
protected virtual void Dispose(bool fDisposing)
{
if (!this.disposed)
{
if (fDisposing && credentials != null)
{
if (ownCredentials)
{
credentials.Dispose();
}
credentials = null;
}
this.disposed = true;
}
}
/// <summary>
/// Disposes of all managed and unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// The destructor for the client class.
/// </summary>
~AmazonSQSClient()
{
this.Dispose(false);
}
#endregion
#region Constructors
/// <summary>
/// Constructs AmazonSQSClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSAccessKey" value="********************"/>
/// <add key="AWSSecretKey" value="****************************************"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonSQSClient()
: this(FallbackCredentialsFactory.GetCredentials(), new AmazonSQSConfig(), true) { }
/// <summary>
/// Constructs AmazonSQSClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSAccessKey" value="********************"/>
/// <add key="AWSSecretKey" value="****************************************"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect to.</param>
public AmazonSQSClient(RegionEndpoint region)
: this(FallbackCredentialsFactory.GetCredentials(), new AmazonSQSConfig() { RegionEndpoint = region }, true) { }
/// <summary>
/// Constructs AmazonSQSClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSAccessKey" value="********************"/>
/// <add key="AWSSecretKey" value="****************************************"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonSQS Configuration Object</param>
public AmazonSQSClient(AmazonSQSConfig config)
: this(FallbackCredentialsFactory.GetCredentials(), config, true) { }
/// <summary>
/// Constructs AmazonSQSClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonSQSClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonSQSConfig()) { }
/// <summary>
/// Constructs AmazonSQSClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect to.</param>
public AmazonSQSClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonSQSConfig() { RegionEndpoint = region }) { }
/// <summary>
/// Constructs AmazonSQSClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonSQS Configuration object. If the config object's
/// UseSecureStringForAwsSecretKey is false, the AWS Secret Key
/// is stored as a clear-text string. Please use this option only
/// if the application environment doesn't allow the use of SecureStrings.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="config">The AmazonSQS Configuration Object</param>
public AmazonSQSClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonSQSConfig config)
: this(new BasicAWSCredentials(awsAccessKeyId, awsSecretAccessKey), config, true) { }
/// <summary>
/// Constructs an AmazonSQSClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonSQS Configuration object
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key as a SecureString</param>
/// <param name="config">The AmazonSQS Configuration Object</param>
public AmazonSQSClient(string awsAccessKeyId, SecureString awsSecretAccessKey, AmazonSQSConfig config)
: this(new BasicAWSCredentials(awsAccessKeyId, awsSecretAccessKey), config, true) { }
/// <summary>
/// Constructs an AmazonSQSClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonSQS Configuration object
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key as a SecureString</param>
/// <param name="region">The region to connect to.</param>
public AmazonSQSClient(string awsAccessKeyId, SecureString awsSecretAccessKey, RegionEndpoint region)
: this(new BasicAWSCredentials(awsAccessKeyId, awsSecretAccessKey), new AmazonSQSConfig() { RegionEndpoint = region }, true) { }
/// <summary>
/// Constructs AmazonSQSClient with AWSCredentials
/// </summary>
/// <param name="credentials"></param>
public AmazonSQSClient(AWSCredentials credentials)
: this(credentials, new AmazonSQSConfig()) { }
/// <summary>
/// Constructs AmazonSQSClient with AWSCredentials
/// </summary>
/// <param name="credentials"></param>
/// <param name="region">The region to connect to.</param>
public AmazonSQSClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonSQSConfig() { RegionEndpoint = region }) { }
/// <summary>
/// Constructs AmazonSQSClient with AWSCredentials and an AmazonSQS Configuration object.
/// </summary>
/// <param name="credentials"></param>
/// <param name="config"></param>
public AmazonSQSClient(AWSCredentials credentials, AmazonSQSConfig config)
: this(credentials, config, false) { }
// Constructs an AmazonSQSClient with credentials, config and flag which
// specifies if the credentials are owned by the client or not
private AmazonSQSClient(AWSCredentials credentials, AmazonSQSConfig config, bool ownCredentials)
{
this.credentials = credentials;
this.config = config;
this.ownCredentials = ownCredentials;
}
#endregion
#region Public API
/// <summary>
/// Creates a new queue, or returns the URL of an existing one.
/// </summary>
/// <remarks>
/// <para>
/// When you request CreateQueue, you provide a name for the queue. To successfully
/// create a new queue, you must provide a name that is unique within the scope of
/// your own queues. If you provide the name of an existing queue, a new queue isn't
/// created and an error isn't returned. Instead, the request succeeds and the queue
/// URL for the existing queue is returned.
/// </para>
/// <para>
/// Exception: if you provide a value for DefaultVisibilityTimeout that is different
/// from the value for the existing queue, you receive an error.
/// </para>
/// </remarks>
/// <param name="request">Create Queue request</param>
/// <returns>Create Queue Response from the service</returns>
public CreateQueueResponse CreateQueue(CreateQueueRequest request)
{
return Invoke<CreateQueueResponse>(request, ConvertCreateQueue(request));
}
/// <summary>
/// Returns a list of your queues. The maximum number of queues that can be returned is 1000.
/// </summary>
/// <remarks>
/// If you specify a value for the optional QueueNamePrefix parameter, only queues with a name beginning with the
/// specified value are returned.
/// </remarks>
/// <param name="request">List Queues request</param>
/// <returns>List Queues Response from the service</returns>
public ListQueuesResponse ListQueues(ListQueuesRequest request)
{
return Invoke<ListQueuesResponse>(request, ConvertListQueues(request));
}
/// <summary>
/// Adds the specified permission(s) to a queue for the specified principal(s).
/// </summary>
/// <remarks>
/// This allows for sharing access to the queue.
/// </remarks>
/// <param name="request">Add Permission request</param>
/// <returns>Add Permission Response from the service</returns>
public AddPermissionResponse AddPermission(AddPermissionRequest request)
{
return Invoke<AddPermissionResponse>(request, ConvertAddPermission(request));
}
/// <summary>
/// Extends the read lock timeout of a single message in a queue.
/// </summary>
/// <param name="request">Change Message Visibility request</param>
/// <returns>Change Message Visibility Response from the service</returns>
public ChangeMessageVisibilityResponse ChangeMessageVisibility(ChangeMessageVisibilityRequest request)
{
return Invoke<ChangeMessageVisibilityResponse>(request, ConvertChangeMessageVisibility(request));
}
/// <summary>
/// Extends the read lock timeout of multiple messages in a queue.
/// </summary>
/// <remarks>
/// This operation takes multiple receipt handles and extends the lock timeout for each of the them.
/// The result of the operation on each message is reported individually in the response.
/// </remarks>
/// <param name="request">Change Message Visibility Batch request</param>
/// <returns>Change Message Visibility Response from the service</returns>
public ChangeMessageVisibilityBatchResponse ChangeMessageVisibilityBatch(ChangeMessageVisibilityBatchRequest request)
{
return Invoke<ChangeMessageVisibilityBatchResponse>(request, ConvertChangeMessageVisibilityBatch(request));
}
/// <summary>
/// Unconditionally removes the specified message from the specified queue.
/// </summary>
/// <remarks>
/// Even if the message is locked by another reader due to the visibility timeout setting, it is still deleted from the queue.
/// </remarks>
/// <param name="request">Delete Message request</param>
/// <returns>Delete Message Response from the service</returns>
public DeleteMessageResponse DeleteMessage(DeleteMessageRequest request)
{
return Invoke<DeleteMessageResponse>(request, ConvertDeleteMessage(request));
}
/// <summary>
/// Removes multiple messages from the specified queue.
/// </summary>
/// <remarks>
/// This operation takes multiple receipt handles and deletes each one of the messages.
/// The result of the delete operation on each message is reported individually in the response.
/// </remarks>
/// <param name="request">DeleteMessageBatch request</param>
/// <returns>DeleteMessageBatch Response from the service</returns>
public DeleteMessageBatchResponse DeleteMessageBatch(DeleteMessageBatchRequest request)
{
return Invoke<DeleteMessageBatchResponse>(request, ConvertDeleteMessageBatch(request));
}
/// <summary>
/// <para>
/// Deletes the queue specified by the queue URL, regardless of whether the queue is empty.
/// </para>
/// </summary>
/// <remarks>
/// <para>
/// If the specified queue does not exist, SQS returns a successful response. Use DeleteQueue with care; once you
/// delete your queue, any messages in the queue are no longer available.
/// </para>
/// <para>
/// When you delete a queue, the deletion process takes up to 60 seconds. Requests you send involving that queue
/// during the 60 seconds might succeed. For example, a SendMessage request might succeed, but after the 60 seconds,
/// the queue and that message you sent no longer exist. Also, when you delete a queue, you must wait at least 60 seconds
/// before creating a queue with the same name.
/// </para>
/// <para>
/// We reserve the right to delete queues that have had no activity for more than 30 days.
/// </para>
/// </remarks>
/// <param name="request">Delete Queue request</param>
/// <returns>Delete Queue Response from the service</returns>
public DeleteQueueResponse DeleteQueue(DeleteQueueRequest request)
{
return Invoke<DeleteQueueResponse>(request, ConvertDeleteQueue(request));
}
/// <summary>
/// Gets one or all attributes of a queue.
/// </summary>
/// <remarks>
/// Gets one or all attributes of a queue. The following table lists the valid values for attributes to be returned.
/// <list type="definition">
/// <item>
/// <term>All</term>
/// <description>All values.</description>
/// </item>
/// <item>
/// <term>ApproximateNumberOfMessages</term>
/// <description>The approximate number of visible messages in a queue.</description>
/// </item>
/// <item>
/// <term>ApproximateNumberOfMessagesNotVisible</term>
/// <description>The approximate number of messages that are not timed-out and not deleted.</description>
/// </item>
/// <item>
/// <term>VisibilityTimeout</term>
/// <description>The visibility timeout for the queue.</description>
/// </item>
/// <item>
/// <term>CreatedTimestamp</term>
/// <description>The time when the queue was created (epoch time in seconds).</description>
/// </item>
/// <item>
/// <term>LastModifiedTimestamp</term>
/// <description>The time when the queue was last changed (epoch time in seconds).</description>
/// </item>
/// <item>
/// <term>Policy</term>
/// <description>The queue's policy.</description>
/// </item>
/// <item>
/// <term>MaximumMessageSize</term>
/// <description>The limit of how many bytes a message can contain before Amazon SQS rejects it.</description>
/// </item>
/// <item>
/// <term>MessageRetentionPeriod</term>
/// <description>The number of seconds Amazon SQS retains a message.</description>
/// </item>
/// <item>
/// <term>QueueArn</term>
/// <description>The queue's Amazon resource name (ARN).</description>
/// </item>
/// <item>
/// <term>DelaySeconds</term>
/// <description>The default delay for messages to be delivered.</description>
/// </item>
/// <item>
/// <term>ApproximateNumberOfMessagesDelayed</term>
/// <description>The approximate number of messages that are delayed from delivery.</description>
/// </item>
/// </list>
/// </remarks>
/// <param name="request">Get Queue Attributes request</param>
/// <returns>Get Queue Attributes Response from the service</returns>
public GetQueueAttributesResponse GetQueueAttributes(GetQueueAttributesRequest request)
{
return Invoke<GetQueueAttributesResponse>(request, ConvertGetQueueAttributes(request));
}
/// <summary>
/// Returns the URL of an existing queue.
/// </summary>
/// <param name="request">GetQueueUrl request</param>
/// <returns>GetQueueUrl Response from the service</returns>
public GetQueueUrlResponse GetQueueUrl(GetQueueUrlRequest request)
{
return Invoke<GetQueueUrlResponse>(request, ConvertGetQueueUrl(request));
}
/// <summary>
/// Removes the permission with the specified statement id from the queue.
/// </summary>
/// <param name="request">Remove Permission request</param>
/// <returns>Remove Permission Response from the service</returns>
public RemovePermissionResponse RemovePermission(RemovePermissionRequest request)
{
return Invoke<RemovePermissionResponse>(request, ConvertRemovePermission(request));
}
/// <summary>
/// <para>
/// Retrieves one or more messages from the specified queue, including the message
/// body and message ID of each message. Messages returned by this action stay in
/// the queue until you delete them. However, once a message is returned to a
/// ReceiveMessage request, it is not returned on subsequent ReceiveMessage requests
/// for the duration of the VisibilityTimeout. If you do not specify a
/// VisibilityTimeout in the request, the overall visibility timeout for the queue
/// is used for the returned messages.
/// </para>
/// <para>
/// If a message is available in the queue, the call will return immediately. Otherwise,
/// it will wait up to WaitTimeSeconds for a message to arrive. If you do not specify
/// WaitTimeSeconds in the request, the queue attribute by the same name is used to
/// determine how long to wait.
/// </para>
/// <para>
/// You could ask for additional information about each message through the attributes.
/// Attributes that can be requested are [SenderId, ApproximateFirstReceiveTimestamp,
/// ApproximateReceiveCount, SentTimestamp].
/// </para>
/// </summary>
/// <remarks>
/// Messages returned by this action stay in the queue until you delete them. However, once a message is returned to a
/// ReceiveMessage request, it is not returned on subsequent ReceiveMessage requests for the duration of the
/// VisibilityTimeout. If you do not specify a VisibilityTimeout in the request, the overall visibility timeout for the
/// queue is used for the returned messages.
/// </remarks>
/// <param name="request">Receive Message request</param>
/// <returns>Receive Message Response from the service</returns>
public ReceiveMessageResponse ReceiveMessage(ReceiveMessageRequest request)
{
ReceiveMessageResponse response = Invoke<ReceiveMessageResponse>(request, ConvertReceiveMessage(request));
AmazonSQSUtil.ValidateReceiveMessage(response);
return response;
}
/// <summary>
/// Delivers a message to the specified queue.
/// </summary>
/// <param name="request">Send Message request</param>
/// <returns>Send Message Response from the service</returns>
public SendMessageResponse SendMessage(SendMessageRequest request)
{
SendMessageResponse response = Invoke<SendMessageResponse>(request, ConvertSendMessage(request));
AmazonSQSUtil.ValidateSendMessage(request, response);
return response;
}
/// <summary>
/// Sends multiple messages to a queue.
/// </summary>
/// <remarks>
/// This operation takes multiple messages and adds each of them to the queue.
/// The result of each add operation is reported individually in the response.
/// </remarks>
/// <param name="request">SendMessageBatch request</param>
/// <returns>SendMessageBatch Response from the service</returns>
public SendMessageBatchResponse SendMessageBatch(SendMessageBatchRequest request)
{
SendMessageBatchResponse response = Invoke<SendMessageBatchResponse>(request, ConvertSendMessageBatch(request));
AmazonSQSUtil.ValidateSendMessageBatch(request, response);
return response;
}
/// <summary>
/// <para>
/// Sets the value of one or more queue attributes. Currently, you can set only one attribute per request. Valid attributes that
/// can be set are [VisibilityTimeout, Policy, MaximumMessageSize,
/// MessageRetentionPeriod, WaitTimeSeconds].
/// </para>
/// </summary>
/// <param name="request">Set Queue Attributes request</param>
/// <returns>Set Queue Attributes Response from the service</returns>
public SetQueueAttributesResponse SetQueueAttributes(SetQueueAttributesRequest request)
{
return Invoke<SetQueueAttributesResponse>(request, ConvertSetQueueAttributes(request));
}
#endregion
#region Private API
/**
* Configure HttpClient with set of defaults as well as configuration
* from AmazonSQSConfig instance
*/
private static HttpWebRequest ConfigureWebRequest(int contentLength, string queueUrl, AmazonSQSConfig config, IDictionary<string, string> headers)
{
HttpWebRequest request = WebRequest.Create(queueUrl) as HttpWebRequest;
if (request != null)
{
request.ServicePoint.ConnectionLimit = config.ConnectionLimit;
if (config.IsSetProxyHost() && config.IsSetProxyPort())
{
WebProxy proxy = new WebProxy(config.ProxyHost, config.ProxyPort);
request.Proxy = proxy;
}
if (request.Proxy != null && config.IsSetProxyCredentials())
{
request.Proxy.Credentials = config.ProxyCredentials;
}
request.Method = "POST";
request.Timeout = 50000;
request.ContentType = AWSSDKUtils.UrlEncodedContent;
request.ContentLength = contentLength;
request.ServicePoint.Expect100Continue = false;
request.ServicePoint.UseNagleAlgorithm = false;
}
Amazon.Runtime.AmazonWebServiceClient.AddHeaders(request, headers);
return request;
}
/**
* Invoke request and return response
*/
private T Invoke<T>(SQSRequest sqsRequest, IDictionary<string, string> parameters)
{
string actionName = parameters["Action"];
T response = default(T);
string url;
if (config.RegionEndpoint != null)
url = "https://" + config.RegionEndpoint.GetEndpointForService(config.RegionEndpointServiceName).Hostname;
else
url = config.ServiceURL;
string queueUrl = parameters.ContainsKey("QueueUrl") ? parameters["QueueUrl"] : url;
if (parameters.ContainsKey("QueueUrl"))
{
parameters.Remove("QueueUrl");
}
HttpStatusCode statusCode = default(HttpStatusCode);
/* Add required request parameters */
IDictionary<string, string> headers = new Dictionary<string, string>();
headers[AWSSDKUtils.UserAgentHeader] = config.UserAgent;
ProcessRequestHandlers(sqsRequest, headers);
AddRequiredParameters(headers, parameters, queueUrl);
string queryString = AWSSDKUtils.GetParametersAsString(parameters);
byte[] requestData = Encoding.UTF8.GetBytes(queryString);
bool shouldRetry = true;
int retries = 0;
int maxRetries = config.IsSetMaxErrorRetry() ? config.MaxErrorRetry : AWSSDKUtils.DefaultMaxRetry;
do
{
string responseBody = null;
HttpWebRequest request = ConfigureWebRequest(requestData.Length, queueUrl, config, headers);
/* Submit the request and read response body */
try
{
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(requestData, 0, requestData.Length);
}
using (HttpWebResponse httpResponse = request.GetResponse() as HttpWebResponse)
{
if (httpResponse == null)
{
throw new WebException(
"The Web Response for a successful request is null!",
WebExceptionStatus.ProtocolError
);
}
statusCode = httpResponse.StatusCode;
using (StreamReader reader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
{
responseBody = reader.ReadToEnd();
}
}
/* Attempt to deserialize response into <Action> Response type */
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (XmlTextReader sr = new XmlTextReader(new StringReader(responseBody)))
{
response = (T)serializer.Deserialize(sr);
}
shouldRetry = false;
}
/* Web exception is thrown on unsucessful responses */
catch (WebException we)
{
shouldRetry = false;
using (HttpWebResponse httpErrorResponse = we.Response as HttpWebResponse)
{
if (httpErrorResponse == null)
{
// Abort the unsuccessful request
request.Abort();
throw we;
}
statusCode = httpErrorResponse.StatusCode;
using (StreamReader reader = new StreamReader(httpErrorResponse.GetResponseStream(), Encoding.UTF8))
{
responseBody = reader.ReadToEnd();
}
// Abort the unsuccessful request
request.Abort();
}
if (statusCode == HttpStatusCode.InternalServerError ||
statusCode == HttpStatusCode.ServiceUnavailable)
{
shouldRetry = true;
PauseOnRetry(++retries, maxRetries, statusCode, we);
}
else
{
/* Attempt to deserialize response into ErrorResponse type */
try
{
using (XmlTextReader sr = new XmlTextReader(new StringReader(responseBody)))
{
XmlSerializer serializer = new XmlSerializer(typeof(ErrorResponse));
ErrorResponse errorResponse = (ErrorResponse)serializer.Deserialize(sr);
Error error = errorResponse.Error[0];
/* Throw formatted exception with information available from the error response */
throw new AmazonSQSException(
error.Message,
statusCode,
error.Code,
error.Type,
errorResponse.RequestId,
errorResponse.ToXML()
);
}
}
/* Rethrow on deserializer error */
catch (Exception e)
{
if (e is AmazonSQSException)
{
throw;
}
else
{
throw ReportAnyErrors(responseBody, statusCode);
}
}
}
}
/* Catch other exceptions, attempt to convert to formatted exception,
* else rethrow wrapped exception */
catch (Exception)
{
// Abort the unsuccessful request
request.Abort();
throw;
}
} while (shouldRetry);
return response;
}
protected virtual void ProcessRequestHandlers(IRequestEvents request, IDictionary<string, string> headers)
{
if (request == null) throw new ArgumentNullException("request");
HeadersRequestEventArgs args = HeadersRequestEventArgs.Create(headers);
request.FireBeforeRequestEvent(this, args);
}
/**
* Look for additional error strings in the response and return formatted exception
*/
private static AmazonSQSException ReportAnyErrors(string responseBody, HttpStatusCode status)
{
AmazonSQSException ex = null;
if (responseBody != null && responseBody.StartsWith("<"))
{
Match errorMatcherOne = Regex.Match(
responseBody,
"<RequestId>(.*)</RequestId>.*<Error><Code>(.*)</Code><Message>(.*)</Message></Error>.*(<Error>)?",
RegexOptions.Multiline);
Match errorMatcherTwo = Regex.Match(
responseBody,
"<Error><Code>(.*)</Code><Message>(.*)</Message></Error>.*(<Error>)?.*<RequestID>(.*)</RequestID>",
RegexOptions.Multiline);
if (errorMatcherOne.Success)
{
string requestId = errorMatcherOne.Groups[1].Value;
string code = errorMatcherOne.Groups[2].Value;
string message = errorMatcherOne.Groups[3].Value;
ex = new AmazonSQSException(message, status, code, "Unknown", requestId, responseBody);
}
else if (errorMatcherTwo.Success)
{
string code = errorMatcherTwo.Groups[1].Value;
string message = errorMatcherTwo.Groups[2].Value;
string requestId = errorMatcherTwo.Groups[4].Value;
ex = new AmazonSQSException(message, status, code, "Unknown", requestId, responseBody);
}
else
{
ex = new AmazonSQSException("Internal Error", status);
}
}
else
{
ex = new AmazonSQSException("Internal Error", status);
}
return ex;
}
/**
* Exponential sleep on failed request
*/
private static void PauseOnRetry(int retries, int maxRetries, HttpStatusCode status, Exception cause)
{
if (retries <= maxRetries)
{
int delay = (int)Math.Pow(4, retries) * 100;
System.Threading.Thread.Sleep(delay);
}
else
{
throw new AmazonSQSException(
"Maximum number of retry attempts reached : " + (retries - 1),
status,
cause
);
}
}
/**
* Add authentication related and version parameters
*/
private void AddRequiredParameters(IDictionary<string, string> headers, IDictionary<string, string> parameters, string queueUrl)
{
using (ImmutableCredentials immutableCredentials = this.credentials.GetCredentials())
{
if (immutableCredentials.UseToken)
{
parameters["SecurityToken"] = immutableCredentials.Token;
}
parameters["AWSAccessKeyId"] = immutableCredentials.AccessKey;
parameters["SignatureVersion"] = config.SignatureVersion;
parameters["SignatureMethod"] = config.SignatureMethod;
parameters["Timestamp"] = AWSSDKUtils.FormattedCurrentTimestampISO8601;
parameters["Version"] = config.ServiceVersion;
if (!config.SignatureVersion.Equals("4"))
{
throw new AmazonSQSException("Invalid Signature Version specified");
}
string region = this.config.AuthenticationRegion ?? AWSSDKUtils.DetermineRegion(queueUrl);
string authorizationHeader = AWS4Signer.CalculateSignature(headers, parameters, queueUrl, "POST", "sqs", region, immutableCredentials);
headers.Add("Authorization", authorizationHeader);
}
}
/**
* Convert CreateQueueRequest to name value pairs
*/
private static IDictionary<string, string> ConvertCreateQueue(CreateQueueRequest request)
{
IDictionary<string, string> parameters = new Dictionary<string, string>();
parameters["Action"] = "CreateQueue";
if (request.IsSetQueueName())
{
parameters["QueueName"] = request.QueueName;
}
if (request.IsSetDefaultVisibilityTimeout())
{
parameters["DefaultVisibilityTimeout"] = request.DefaultVisibilityTimeout.ToString();
}
List<Attribute> createQueueRequestAttributeList = request.Attribute;
int createQueueRequestAttributeListIndex = 1;
foreach (Attribute createQueueRequestAttribute in createQueueRequestAttributeList)
{
if (createQueueRequestAttribute.IsSetName())
{
parameters[String.Concat("Attribute", ".", createQueueRequestAttributeListIndex, ".", "Name")] = createQueueRequestAttribute.Name;
}
if (createQueueRequestAttribute.IsSetValue())
{
parameters[String.Concat("Attribute", ".", createQueueRequestAttributeListIndex, ".", "Value")] = createQueueRequestAttribute.Value;
}
createQueueRequestAttributeListIndex++;
}
return parameters;
}
/**
* Convert ListQueuesRequest to name value pairs
*/
private static IDictionary<string, string> ConvertListQueues(ListQueuesRequest request)
{
IDictionary<string, string> parameters = new Dictionary<string, string>();
parameters["Action"] = "ListQueues";
if (request.IsSetQueueNamePrefix())
{
parameters["QueueNamePrefix"] = request.QueueNamePrefix;
}
List<Attribute> listQueuesRequestAttributeList = request.Attribute;
int listQueuesRequestAttributeListIndex = 1;
foreach (Attribute listQueuesRequestAttribute in listQueuesRequestAttributeList)
{
if (listQueuesRequestAttribute.IsSetName())
{
parameters[String.Concat("Attribute", ".", listQueuesRequestAttributeListIndex, ".", "Name")] = listQueuesRequestAttribute.Name;
}
if (listQueuesRequestAttribute.IsSetValue())
{
parameters[String.Concat("Attribute", ".", listQueuesRequestAttributeListIndex, ".", "Value")] = listQueuesRequestAttribute.Value;
}
listQueuesRequestAttributeListIndex++;
}
return parameters;
}
/**
* Convert ChangeMessageVisibilityRequest to name value pairs
*/
private static IDictionary<string, string> ConvertChangeMessageVisibility(ChangeMessageVisibilityRequest request)
{
IDictionary<string, string> parameters = new Dictionary<string, string>();
parameters["Action"] = "ChangeMessageVisibility";
if (request.IsSetQueueUrl())
{
parameters["QueueUrl"] = request.QueueUrl;
}
if (request.IsSetReceiptHandle())
{
parameters["ReceiptHandle"] = request.ReceiptHandle;
}
if (request.IsSetVisibilityTimeout())
{
parameters["VisibilityTimeout"] = request.VisibilityTimeout.ToString();
}
List<Attribute> changeMessageVisibilityRequestAttributeList = request.Attribute;
int changeMessageVisibilityRequestAttributeListIndex = 1;
foreach (Attribute changeMessageVisibilityRequestAttribute in changeMessageVisibilityRequestAttributeList)
{
if (changeMessageVisibilityRequestAttribute.IsSetName())
{
parameters[String.Concat("Attribute", ".", changeMessageVisibilityRequestAttributeListIndex, ".", "Name")] = changeMessageVisibilityRequestAttribute.Name;
}
if (changeMessageVisibilityRequestAttribute.IsSetValue())
{
parameters[String.Concat("Attribute", ".", changeMessageVisibilityRequestAttributeListIndex, ".", "Value")] = changeMessageVisibilityRequestAttribute.Value;
}
changeMessageVisibilityRequestAttributeListIndex++;
}
return parameters;
}
private static IDictionary<string, string> ConvertChangeMessageVisibilityBatch(ChangeMessageVisibilityBatchRequest request)
{
IDictionary<string, string> parameters = new Dictionary<string, string>();
parameters["Action"] = "ChangeMessageVisibilityBatch";
if (request.IsSetQueueUrl())
{
parameters["QueueUrl"] = request.QueueUrl;
}
int changeMessageVisibilityBatchRequestEntryListIndex = 1;
foreach (ChangeMessageVisibilityBatchRequestEntry changeMessageVisibilityBatchRequestEntry in request.Entries)
{
if (changeMessageVisibilityBatchRequestEntry.IsSetId())
{
parameters[String.Concat("ChangeMessageVisibilityBatchRequestEntry", ".", changeMessageVisibilityBatchRequestEntryListIndex, ".Id")] = changeMessageVisibilityBatchRequestEntry.Id;
}
if (changeMessageVisibilityBatchRequestEntry.IsSetReceiptHandle())
{
parameters[String.Concat("ChangeMessageVisibilityBatchRequestEntry", ".", changeMessageVisibilityBatchRequestEntryListIndex, ".ReceiptHandle")] = changeMessageVisibilityBatchRequestEntry.ReceiptHandle;
}
if (changeMessageVisibilityBatchRequestEntry.IsSetVisibilityTimeout())
{
parameters[String.Concat("ChangeMessageVisibilityBatchRequestEntry", ".", changeMessageVisibilityBatchRequestEntryListIndex, ".VisibilityTimeout")] = changeMessageVisibilityBatchRequestEntry.VisibilityTimeout.ToString();
}
changeMessageVisibilityBatchRequestEntryListIndex++;
}
return parameters;
}
/**
* Convert DeleteMessageRequest to name value pairs
*/
private static IDictionary<string, string> ConvertDeleteMessage(DeleteMessageRequest request)
{
IDictionary<string, string> parameters = new Dictionary<string, string>();
parameters["Action"] = "DeleteMessage";
if (request.IsSetQueueUrl())
{
parameters["QueueUrl"] = request.QueueUrl;
}
if (request.IsSetReceiptHandle())
{
parameters["ReceiptHandle"] = request.ReceiptHandle;
}
List<Attribute> deleteMessageRequestAttributeList = request.Attribute;
int deleteMessageRequestAttributeListIndex = 1;
foreach (Attribute deleteMessageRequestAttribute in deleteMessageRequestAttributeList)
{
if (deleteMessageRequestAttribute.IsSetName())
{
parameters[String.Concat("Attribute", ".", deleteMessageRequestAttributeListIndex, ".", "Name")] = deleteMessageRequestAttribute.Name;
}
if (deleteMessageRequestAttribute.IsSetValue())
{
parameters[String.Concat("Attribute", ".", deleteMessageRequestAttributeListIndex, ".", "Value")] = deleteMessageRequestAttribute.Value;
}
deleteMessageRequestAttributeListIndex++;
}
return parameters;
}
private static IDictionary<string, string> ConvertDeleteMessageBatch(DeleteMessageBatchRequest request)
{
IDictionary<string, string> parameters = new Dictionary<string, string>();
parameters["Action"] = "DeleteMessageBatch";
if (request.IsSetQueueUrl())
{
parameters["QueueUrl"] = request.QueueUrl;
}
int deleteMessageBatchRequestEntryListIndex = 1;
foreach (DeleteMessageBatchRequestEntry deleteMessageBatchRequestEntry in request.Entries)
{
if (deleteMessageBatchRequestEntry.IsSetId())
{
parameters[String.Concat("DeleteMessageBatchRequestEntry", ".", deleteMessageBatchRequestEntryListIndex, ".Id")] = deleteMessageBatchRequestEntry.Id;
}
if (deleteMessageBatchRequestEntry.IsSetReceiptHandle())
{
parameters[String.Concat("DeleteMessageBatchRequestEntry", ".", deleteMessageBatchRequestEntryListIndex, ".ReceiptHandle")] = deleteMessageBatchRequestEntry.ReceiptHandle;
}
deleteMessageBatchRequestEntryListIndex++;
}
return parameters;
}
/**
* Convert DeleteQueueRequest to name value pairs
*/
private static IDictionary<string, string> ConvertDeleteQueue(DeleteQueueRequest request)
{
IDictionary<string, string> parameters = new Dictionary<string, string>();
parameters["Action"] = "DeleteQueue";
if (request.IsSetQueueUrl())
{
parameters["QueueUrl"] = request.QueueUrl;
}
List<Attribute> deleteQueueRequestAttributeList = request.Attribute;
int deleteQueueRequestAttributeListIndex = 1;
foreach (Attribute deleteQueueRequestAttribute in deleteQueueRequestAttributeList)
{
if (deleteQueueRequestAttribute.IsSetName())
{
parameters[String.Concat("Attribute", ".", deleteQueueRequestAttributeListIndex, ".", "Name")] = deleteQueueRequestAttribute.Name;
}
if (deleteQueueRequestAttribute.IsSetValue())
{
parameters[String.Concat("Attribute", ".", deleteQueueRequestAttributeListIndex, ".", "Value")] = deleteQueueRequestAttribute.Value;
}
deleteQueueRequestAttributeListIndex++;
}
return parameters;
}
/**
* Convert GetQueueAttributesRequest to name value pairs
*/
private static IDictionary<string, string> ConvertGetQueueAttributes(GetQueueAttributesRequest request)
{
IDictionary<string, string> parameters = new Dictionary<string, string>();
parameters["Action"] = "GetQueueAttributes";
if (request.IsSetQueueUrl())
{
parameters["QueueUrl"] = request.QueueUrl;
}
List<string> getQueueAttributesRequestAttributeNameList = request.AttributeName;
int getQueueAttributesRequestAttributeNameListIndex = 1;
foreach (string getQueueAttributesRequestAttributeName in getQueueAttributesRequestAttributeNameList)
{
parameters[String.Concat("AttributeName", ".", getQueueAttributesRequestAttributeNameListIndex)] = getQueueAttributesRequestAttributeName;
getQueueAttributesRequestAttributeNameListIndex++;
}
return parameters;
}
/**
* Convert GetQueueAttributesRequest to name value pairs
*/
private static IDictionary<string, string> ConvertGetQueueUrl(GetQueueUrlRequest request)
{
IDictionary<string, string> parameters = new Dictionary<string, string>();
parameters["Action"] = "GetQueueUrl";
if (request.IsSetQueueName())
{
parameters["QueueName"] = request.QueueName;
}
if (request.IsSetQueueOwnerAWSAccountId())
{
parameters["QueueOwnerAWSAccountId"] = request.QueueOwnerAWSAccountId;
}
return parameters;
}
/**
* Convert ReceiveMessageRequest to name value pairs
*/
private static IDictionary<string, string> ConvertReceiveMessage(ReceiveMessageRequest request)
{
IDictionary<string, string> parameters = new Dictionary<string, string>();
parameters["Action"] = "ReceiveMessage";
if (request.IsSetQueueUrl())
{
parameters["QueueUrl"] = request.QueueUrl;
}
if (request.IsSetMaxNumberOfMessages())
{
parameters["MaxNumberOfMessages"] = request.MaxNumberOfMessages.ToString();
}
if (request.IsSetVisibilityTimeout())
{
parameters["VisibilityTimeout"] = request.VisibilityTimeout.ToString();
}
if (request.IsSetWaitTimeSeconds())
{
parameters["WaitTimeSeconds"] = request.WaitTimeSeconds.ToString();
}
List<string> receiveMessageRequestAttributeNameList = request.AttributeName;
int receiveMessageRequestAttributeNameListIndex = 1;
foreach (string receiveMessageRequestAttributeName in receiveMessageRequestAttributeNameList)
{
parameters[String.Concat("AttributeName", ".", receiveMessageRequestAttributeNameListIndex)] = receiveMessageRequestAttributeName;
receiveMessageRequestAttributeNameListIndex++;
}
return parameters;
}
/**
* Convert SendMessageRequest to name value pairs
*/
private static IDictionary<string, string> ConvertSendMessage(SendMessageRequest request)
{
IDictionary<string, string> parameters = new Dictionary<string, string>();
parameters["Action"] = "SendMessage";
if (request.IsSetQueueUrl())
{
parameters["QueueUrl"] = request.QueueUrl;
}
if (request.IsSetMessageBody())
{
parameters["MessageBody"] = request.MessageBody;
}
if (request.IsSetDelaySeconds())
{
parameters["DelaySeconds"] = request.DelaySeconds.ToString();
}
return parameters;
}
private static IDictionary<string, string> ConvertSendMessageBatch(SendMessageBatchRequest request)
{
IDictionary<string, string> parameters = new Dictionary<string, string>();
parameters["Action"] = "SendMessageBatch";
if (request.IsSetQueueUrl())
{
parameters["QueueUrl"] = request.QueueUrl;
}
int sendMessageBatchRequestEntryListIndex = 1;
foreach (SendMessageBatchRequestEntry sendMessageBatchRequestEntry in request.Entries)
{
if (sendMessageBatchRequestEntry.IsSetId())
{
parameters[String.Concat("SendMessageBatchRequestEntry", ".", sendMessageBatchRequestEntryListIndex, ".Id")] = sendMessageBatchRequestEntry.Id;
}
if (sendMessageBatchRequestEntry.IsSetMessageBody())
{
parameters[String.Concat("SendMessageBatchRequestEntry", ".", sendMessageBatchRequestEntryListIndex, ".MessageBody")] = sendMessageBatchRequestEntry.MessageBody;
}
if (sendMessageBatchRequestEntry.IsSetDelaySeconds())
{
parameters[String.Concat("SendMessageBatchRequestEntry", ".", sendMessageBatchRequestEntryListIndex, ".DelaySeconds")] = sendMessageBatchRequestEntry.DelaySeconds.ToString();
}
sendMessageBatchRequestEntryListIndex++;
}
return parameters;
}
/**
* Convert SetQueueAttributesRequest to name value pairs
*/
private static IDictionary<string, string> ConvertSetQueueAttributes(SetQueueAttributesRequest request)
{
IDictionary<string, string> parameters = new Dictionary<string, string>();
parameters["Action"] = "SetQueueAttributes";
if (request.IsSetQueueUrl())
{
parameters["QueueUrl"] = request.QueueUrl;
}
List<Attribute> setQueueAttributesRequestAttributeList = request.Attribute;
int setQueueAttributesRequestAttributeListIndex = 1;
foreach (Attribute setQueueAttributesRequestAttribute in setQueueAttributesRequestAttributeList)
{
if (setQueueAttributesRequestAttribute.IsSetName())
{
parameters[String.Concat("Attribute", ".", setQueueAttributesRequestAttributeListIndex, ".", "Name")] = setQueueAttributesRequestAttribute.Name;
}
if (setQueueAttributesRequestAttribute.IsSetValue())
{
parameters[String.Concat("Attribute", ".", setQueueAttributesRequestAttributeListIndex, ".", "Value")] = setQueueAttributesRequestAttribute.Value;
}
setQueueAttributesRequestAttributeListIndex++;
}
return parameters;
}
/**
* Convert AddPermissionRequest to name value pairs
*/
private static IDictionary<string, string> ConvertAddPermission(AddPermissionRequest request)
{
IDictionary<string, string> parameters = new Dictionary<string, string>();
parameters["Action"] = "AddPermission";
if (request.IsSetQueueUrl())
{
parameters["QueueUrl"] = request.QueueUrl;
}
if (request.IsSetLabel())
{
parameters["Label"] = request.Label;
}
List<string> addPermissionRequestAWSAccountIdList = request.AWSAccountId;
int addPermissionRequestAWSAccountIdListIndex = 1;
foreach (string addPermissionRequestAWSAccountId in addPermissionRequestAWSAccountIdList)
{
parameters[String.Concat("AWSAccountId", ".", addPermissionRequestAWSAccountIdListIndex)] = addPermissionRequestAWSAccountId;
addPermissionRequestAWSAccountIdListIndex++;
}
List<string> addPermissionRequestActionNameList = request.ActionName;
int addPermissionRequestActionNameListIndex = 1;
foreach (string addPermissionRequestActionName in addPermissionRequestActionNameList)
{
parameters[String.Concat("ActionName", ".", addPermissionRequestActionNameListIndex)] = addPermissionRequestActionName;
addPermissionRequestActionNameListIndex++;
}
return parameters;
}
/**
* Convert RemovePermissionRequest to name value pairs
*/
private static IDictionary<string, string> ConvertRemovePermission(RemovePermissionRequest request)
{
IDictionary<string, string> parameters = new Dictionary<string, string>();
parameters["Action"] = "RemovePermission";
if (request.IsSetQueueUrl())
{
parameters["QueueUrl"] = request.QueueUrl;
}
if (request.IsSetLabel())
{
parameters["Label"] = request.Label;
}
return parameters;
}
#endregion
}
}
| |
//
// Options.cs
//
// Authors:
// Jonathan Pryor <jpryor@novell.com>
//
// Copyright (C) 2008 Novell (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.
//
// Compile With:
// gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
// gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
//
// The LINQ version just changes the implementation of
// OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
//
// A Getopt::Long-inspired option parsing library for C#.
//
// NDesk.Options.OptionSet is built upon a key/val table, where the
// key is a option format string and the val is a delegate that is
// invoked when the format string is matched.
//
// Option format strings:
// Regex-like BNF Grammar:
// name: .+
// type: [=:]
// sep: ( [^{}]+ | '{' .+ '}' )?
// aliases: ( name type sep ) ( '|' name type sep )*
//
// Each '|'-delimited name is an alias for the associated action. If the
// format string ends in a '=', it has a required val. If the format
// string ends in a ':', it has an optional val. If neither '=' or ':'
// is present, no val is supported. `=' or `:' need only be defined on one
// alias, but if they are provided on more than one they must be consistent.
//
// Each alias portion may also end with a "key/val separator", which is used
// to split option values if the option accepts > 1 val. If not specified,
// it defaults to '=' and ':'. If specified, it can be any character except
// '{' and '}' OR the *string* between '{' and '}'. If no separator should be
// used (i.e. the separate values should be distinct arguments), then "{}"
// should be used as the separator.
//
// Options are extracted either from the current option by looking for
// the option name followed by an '=' or ':', or is taken from the
// following option IFF:
// - The current option does not contain a '=' or a ':'
// - The current option requires a val (i.e. not a Option type of ':')
//
// The `name' used in the option format string does NOT include any leading
// option indicator, such as '-', '--', or '/'. All three of these are
// permitted/required on any named option.
//
// Option bundling is permitted so long as:
// - '-' is used to start the option group
// - all of the bundled options are a single character
// - at most one of the bundled options accepts a val, and the val
// provided starts from the next character to the end of the string.
//
// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=val'
// as '-Dname=val'.
//
// Option processing is disabled by specifying "--". All options after "--"
// are returned by OptionSet.Parse() unchanged and unprocessed.
//
// Unprocessed options are returned from OptionSet.Parse().
//
// Examples:
// int verbose = 0;
// OptionSet p = new OptionSet ()
// .Insert ("v", v => ++verbose)
// .Insert ("name=|val=", v => Console.WriteLine (v));
// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
//
// The above would parse the argument string array, and would invoke the
// lambda expression three times, setting `verbose' to 3 when complete.
// It would also print out "A" and "B" to standard output.
// The returned array would contain the string "extra".
//
// C# 3.0 collection initializers are supported and encouraged:
// var p = new OptionSet () {
// { "h|?|help", v => ShowHelp () },
// };
//
// System.ComponentModel.TypeConverter is also supported, allowing the use of
// custom data types in the callback type; TypeConverter.ConvertFromString()
// is used to convert the val option to an instance of the specified
// type:
//
// var p = new OptionSet () {
// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
// };
//
// Random other tidbits:
// - Boolean options (those w/o '=' or ':' in the option format string)
// are explicitly enabled if they are followed with '+', and explicitly
// disabled if they are followed with '-':
// string a = null;
// var p = new OptionSet () {
// { "a", s => a = s },
// };
// p.Parse (new string[]{"-a"}); // sets v != null
// p.Parse (new string[]{"-a+"}); // sets v != null
// p.Parse (new string[]{"-a-"}); // sets v == null
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
#if LINQ
using System.Linq;
#endif
#if TEST
using NDesk.Options;
#endif
#if NDESK_OPTIONS
namespace NDesk.Options
#else
namespace Mono.Options
#endif
{
public class OptionValueCollection : IList, IList<string>
{
List<string> values = new List<string>();
OptionContext c;
internal OptionValueCollection(OptionContext c)
{
this.c = c;
}
#region ICollection
void ICollection.CopyTo(Array array, int index) { (values as ICollection).CopyTo(array, index); }
bool ICollection.IsSynchronized { get { return (values as ICollection).IsSynchronized; } }
object ICollection.SyncRoot { get { return (values as ICollection).SyncRoot; } }
#endregion
#region ICollection<T>
public void Add(string item) { values.Add(item); }
public void Clear() { values.Clear(); }
public bool Contains(string item) { return values.Contains(item); }
public void CopyTo(string[] array, int arrayIndex) { values.CopyTo(array, arrayIndex); }
public bool Remove(string item) { return values.Remove(item); }
public int Count { get { return values.Count; } }
public bool IsReadOnly { get { return false; } }
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator() { return values.GetEnumerator(); }
#endregion
#region IEnumerable<T>
public IEnumerator<string> GetEnumerator() { return values.GetEnumerator(); }
#endregion
#region IList
int IList.Add(object value) { return (values as IList).Add(value); }
bool IList.Contains(object value) { return (values as IList).Contains(value); }
int IList.IndexOf(object value) { return (values as IList).IndexOf(value); }
void IList.Insert(int index, object value) { (values as IList).Insert(index, value); }
void IList.Remove(object value) { (values as IList).Remove(value); }
void IList.RemoveAt(int index) { (values as IList).RemoveAt(index); }
bool IList.IsFixedSize { get { return false; } }
object IList.this[int index] { get { return this[index]; } set { (values as IList)[index] = value; } }
#endregion
#region IList<T>
public int IndexOf(string item) { return values.IndexOf(item); }
public void Insert(int index, string item) { values.Insert(index, item); }
public void RemoveAt(int index) { values.RemoveAt(index); }
private void AssertValid(int index)
{
if (c.Option == null)
throw new InvalidOperationException("OptionContext.Option is null.");
if (index >= c.Option.MaxValueCount)
throw new ArgumentOutOfRangeException("index");
if (c.Option.OptionValueType == OptionValueType.Required &&
index >= values.Count)
throw new OptionException(string.Format(
c.OptionSet.MessageLocalizer("Missing required value for option '{0}'."), c.OptionName),
c.OptionName);
}
public string this[int index]
{
get
{
AssertValid(index);
return index >= values.Count ? null : values[index];
}
set
{
values[index] = value;
}
}
#endregion
public List<string> ToList()
{
return new List<string>(values);
}
public string[] ToArray()
{
return values.ToArray();
}
public override string ToString()
{
return string.Join(", ", values.ToArray());
}
}
public class OptionContext
{
private Option option;
private string name;
private int index;
private OptionSet set;
private OptionValueCollection c;
public OptionContext(OptionSet set)
{
this.set = set;
this.c = new OptionValueCollection(this);
}
public Option Option
{
get { return option; }
set { option = value; }
}
public string OptionName
{
get { return name; }
set { name = value; }
}
public int OptionIndex
{
get { return index; }
set { index = value; }
}
public OptionSet OptionSet
{
get { return set; }
}
public OptionValueCollection OptionValues
{
get { return c; }
}
}
public enum OptionValueType
{
None,
Optional,
Required,
}
public abstract class Option
{
string prototype, description;
string[] names;
OptionValueType type;
int count;
string[] separators;
protected Option(string prototype, string description)
: this(prototype, description, 1)
{
}
protected Option(string prototype, string description, int maxValueCount)
{
if (prototype == null)
throw new ArgumentNullException("prototype");
if (prototype.Length == 0)
throw new ArgumentException("Cannot be the empty string.", "prototype");
if (maxValueCount < 0)
throw new ArgumentOutOfRangeException("maxValueCount");
this.prototype = prototype;
this.names = prototype.Split('|');
this.description = description;
this.count = maxValueCount;
this.type = ParsePrototype();
if (this.count == 0 && type != OptionValueType.None)
throw new ArgumentException(
"Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
"OptionValueType.Optional.",
"maxValueCount");
if (this.type == OptionValueType.None && maxValueCount > 1)
throw new ArgumentException(
string.Format("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
"maxValueCount");
if (Array.IndexOf(names, "<>") >= 0 &&
((names.Length == 1 && this.type != OptionValueType.None) ||
(names.Length > 1 && this.MaxValueCount > 1)))
throw new ArgumentException(
"The default option handler '<>' cannot require values.",
"prototype");
}
public string Prototype { get { return prototype; } }
public string Description { get { return description; } }
public OptionValueType OptionValueType { get { return type; } }
public int MaxValueCount { get { return count; } }
public string[] GetNames()
{
return (string[])names.Clone();
}
public string[] GetValueSeparators()
{
if (separators == null)
return new string[0];
return (string[])separators.Clone();
}
protected static T Parse<T>(string value, OptionContext c)
{
Type tt = typeof(T);
bool nullable = tt.IsValueType && tt.IsGenericType &&
!tt.IsGenericTypeDefinition &&
tt.GetGenericTypeDefinition() == typeof(Nullable<>);
Type targetType = nullable ? tt.GetGenericArguments()[0] : typeof(T);
TypeConverter conv = TypeDescriptor.GetConverter(targetType);
T t = default(T);
try
{
if (value != null)
t = (T)conv.ConvertFromString(value);
}
catch (Exception e)
{
throw new OptionException(
string.Format(
c.OptionSet.MessageLocalizer("Could not convert string `{0}' to type {1} for option `{2}'."),
value, targetType.Name, c.OptionName),
c.OptionName, e);
}
return t;
}
internal string[] Names { get { return names; } }
internal string[] ValueSeparators { get { return separators; } }
static readonly char[] NameTerminator = new char[] { '=', ':' };
private OptionValueType ParsePrototype()
{
char type = '\0';
List<string> seps = new List<string>();
for (int i = 0; i < names.Length; ++i)
{
string name = names[i];
if (name.Length == 0)
throw new ArgumentException("Empty option names are not supported.", "prototype");
int end = name.IndexOfAny(NameTerminator);
if (end == -1)
continue;
names[i] = name.Substring(0, end);
if (type == '\0' || type == name[end])
type = name[end];
else
throw new ArgumentException(
string.Format("Conflicting option types: '{0}' vs. '{1}'.", type, name[end]),
"prototype");
AddSeparators(name, end, seps);
}
if (type == '\0')
return OptionValueType.None;
if (count <= 1 && seps.Count != 0)
throw new ArgumentException(
string.Format("Cannot provide key/value separators for Options taking {0} value(s).", count),
"prototype");
if (count > 1)
{
if (seps.Count == 0)
this.separators = new string[] { ":", "=" };
else if (seps.Count == 1 && seps[0].Length == 0)
this.separators = null;
else
this.separators = seps.ToArray();
}
return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
}
private static void AddSeparators(string name, int end, ICollection<string> seps)
{
int start = -1;
for (int i = end + 1; i < name.Length; ++i)
{
switch (name[i])
{
case '{':
if (start != -1)
throw new ArgumentException(
string.Format("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
start = i + 1;
break;
case '}':
if (start == -1)
throw new ArgumentException(
string.Format("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
seps.Add(name.Substring(start, i - start));
start = -1;
break;
default:
if (start == -1)
seps.Add(name[i].ToString());
break;
}
}
if (start != -1)
throw new ArgumentException(
string.Format("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
}
public void Invoke(OptionContext c)
{
OnParseComplete(c);
c.OptionName = null;
c.Option = null;
c.OptionValues.Clear();
}
protected abstract void OnParseComplete(OptionContext c);
public override string ToString()
{
return Prototype;
}
}
[Serializable]
public class OptionException : Exception
{
private string option;
public OptionException()
{
}
public OptionException(string message, string optionName)
: base(message)
{
this.option = optionName;
}
public OptionException(string message, string optionName, Exception innerException)
: base(message, innerException)
{
this.option = optionName;
}
protected OptionException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
this.option = info.GetString("OptionName");
}
public string OptionName
{
get { return this.option; }
}
[SecurityPermission(SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("OptionName", option);
}
}
public delegate void OptionAction<TKey, TValue>(TKey key, TValue value);
public class OptionSet : KeyedCollection<string, Option>
{
public OptionSet()
: this(delegate (string f) { return f; })
{
}
public OptionSet(Converter<string, string> localizer)
{
this.localizer = localizer;
}
Converter<string, string> localizer;
public Converter<string, string> MessageLocalizer
{
get { return localizer; }
}
protected override string GetKeyForItem(Option item)
{
if (item == null)
throw new ArgumentNullException("option");
if (item.Names != null && item.Names.Length > 0)
return item.Names[0];
// This should never happen, as it's invalid for Option to be
// constructed w/o any names.
throw new InvalidOperationException("Option has no names!");
}
[Obsolete("Use KeyedCollection.this[string]")]
protected Option GetOptionForName(string option)
{
if (option == null)
throw new ArgumentNullException("option");
try
{
return base[option];
}
catch (KeyNotFoundException)
{
return null;
}
}
protected override void InsertItem(int index, Option item)
{
base.InsertItem(index, item);
AddImpl(item);
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
Option p = Items[index];
// KeyedCollection.RemoveItem() handles the 0th item
for (int i = 1; i < p.Names.Length; ++i)
{
Dictionary.Remove(p.Names[i]);
}
}
protected override void SetItem(int index, Option item)
{
base.SetItem(index, item);
RemoveItem(index);
AddImpl(item);
}
private void AddImpl(Option option)
{
if (option == null)
throw new ArgumentNullException("option");
List<string> added = new List<string>(option.Names.Length);
try
{
// KeyedCollection.InsertItem/SetItem handle the 0th name.
for (int i = 1; i < option.Names.Length; ++i)
{
Dictionary.Add(option.Names[i], option);
added.Add(option.Names[i]);
}
}
catch (Exception)
{
foreach (string name in added)
Dictionary.Remove(name);
throw;
}
}
public new OptionSet Add(Option option)
{
base.Add(option);
return this;
}
sealed class ActionOption : Option
{
Action<OptionValueCollection> action;
public ActionOption(string prototype, string description, int count, Action<OptionValueCollection> action)
: base(prototype, description, count)
{
if (action == null)
throw new ArgumentNullException("action");
this.action = action;
}
protected override void OnParseComplete(OptionContext c)
{
action(c.OptionValues);
}
}
public OptionSet Add(string prototype, Action<string> action)
{
return Add(prototype, null, action);
}
public OptionSet Add(string prototype, string description, Action<string> action)
{
if (action == null)
throw new ArgumentNullException("action");
Option p = new ActionOption(prototype, description, 1,
delegate (OptionValueCollection v) { action(v[0]); });
base.Add(p);
return this;
}
public OptionSet Add(string prototype, OptionAction<string, string> action)
{
return Add(prototype, null, action);
}
public OptionSet Add(string prototype, string description, OptionAction<string, string> action)
{
if (action == null)
throw new ArgumentNullException("action");
Option p = new ActionOption(prototype, description, 2,
delegate (OptionValueCollection v) { action(v[0], v[1]); });
base.Add(p);
return this;
}
sealed class ActionOption<T> : Option
{
Action<T> action;
public ActionOption(string prototype, string description, Action<T> action)
: base(prototype, description, 1)
{
if (action == null)
throw new ArgumentNullException("action");
this.action = action;
}
protected override void OnParseComplete(OptionContext c)
{
action(Parse<T>(c.OptionValues[0], c));
}
}
sealed class ActionOption<TKey, TValue> : Option
{
OptionAction<TKey, TValue> action;
public ActionOption(string prototype, string description, OptionAction<TKey, TValue> action)
: base(prototype, description, 2)
{
if (action == null)
throw new ArgumentNullException("action");
this.action = action;
}
protected override void OnParseComplete(OptionContext c)
{
action(
Parse<TKey>(c.OptionValues[0], c),
Parse<TValue>(c.OptionValues[1], c));
}
}
public OptionSet Add<T>(string prototype, Action<T> action)
{
return Add(prototype, null, action);
}
public OptionSet Add<T>(string prototype, string description, Action<T> action)
{
return Add(new ActionOption<T>(prototype, description, action));
}
public OptionSet Add<TKey, TValue>(string prototype, OptionAction<TKey, TValue> action)
{
return Add(prototype, null, action);
}
public OptionSet Add<TKey, TValue>(string prototype, string description, OptionAction<TKey, TValue> action)
{
return Add(new ActionOption<TKey, TValue>(prototype, description, action));
}
protected virtual OptionContext CreateOptionContext()
{
return new OptionContext(this);
}
#if LINQ
public List<string> Parse (IEnumerable<string> arguments)
{
bool process = true;
OptionContext c = CreateOptionContext ();
c.OptionIndex = -1;
var def = GetOptionForName ("<>");
var unprocessed =
from argument in arguments
where ++c.OptionIndex >= 0 && (process || def != null)
? process
? argument == "--"
? (process = false)
: !Parse (argument, c)
? def != null
? Unprocessed (null, def, c, argument)
: true
: false
: def != null
? Unprocessed (null, def, c, argument)
: true
: true
select argument;
List<string> r = unprocessed.ToList ();
if (c.Option != null)
c.Option.Invoke (c);
return r;
}
#else
public List<string> Parse(IEnumerable<string> arguments)
{
OptionContext c = CreateOptionContext();
c.OptionIndex = -1;
bool process = true;
List<string> unprocessed = new List<string>();
Option def = Contains("<>") ? this["<>"] : null;
foreach (string argument in arguments)
{
++c.OptionIndex;
if (argument == "--")
{
process = false;
continue;
}
if (!process)
{
Unprocessed(unprocessed, def, c, argument);
continue;
}
if (!Parse(argument, c))
Unprocessed(unprocessed, def, c, argument);
}
if (c.Option != null)
c.Option.Invoke(c);
return unprocessed;
}
#endif
private static bool Unprocessed(ICollection<string> extra, Option def, OptionContext c, string argument)
{
if (def == null)
{
extra.Add(argument);
return false;
}
c.OptionValues.Add(argument);
c.Option = def;
c.Option.Invoke(c);
return false;
}
private readonly Regex ValueOption = new Regex(
@"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
protected bool GetOptionParts(string argument, out string flag, out string name, out string sep, out string value)
{
if (argument == null)
throw new ArgumentNullException("argument");
flag = name = sep = value = null;
Match m = ValueOption.Match(argument);
if (!m.Success)
{
return false;
}
flag = m.Groups["flag"].Value;
name = m.Groups["name"].Value;
if (m.Groups["sep"].Success && m.Groups["value"].Success)
{
sep = m.Groups["sep"].Value;
value = m.Groups["value"].Value;
}
return true;
}
protected virtual bool Parse(string argument, OptionContext c)
{
if (c.Option != null)
{
ParseValue(argument, c);
return true;
}
string f, n, s, v;
if (!GetOptionParts(argument, out f, out n, out s, out v))
return false;
Option p;
if (Contains(n))
{
p = this[n];
c.OptionName = f + n;
c.Option = p;
switch (p.OptionValueType)
{
case OptionValueType.None:
c.OptionValues.Add(n);
c.Option.Invoke(c);
break;
case OptionValueType.Optional:
case OptionValueType.Required:
ParseValue(v, c);
break;
}
return true;
}
// no match; is it a bool option?
if (ParseBool(argument, n, c))
return true;
// is it a bundled option?
if (ParseBundledValue(f, string.Concat(n + s + v), c))
return true;
return false;
}
private void ParseValue(string option, OptionContext c)
{
if (option != null)
foreach (string o in c.Option.ValueSeparators != null
? option.Split(c.Option.ValueSeparators, StringSplitOptions.None)
: new string[] { option })
{
c.OptionValues.Add(o);
}
if (c.OptionValues.Count == c.Option.MaxValueCount ||
c.Option.OptionValueType == OptionValueType.Optional)
c.Option.Invoke(c);
else if (c.OptionValues.Count > c.Option.MaxValueCount)
{
throw new OptionException(localizer(string.Format(
"Error: Found {0} option values when expecting {1}.",
c.OptionValues.Count, c.Option.MaxValueCount)),
c.OptionName);
}
}
private bool ParseBool(string option, string n, OptionContext c)
{
Option p;
string rn;
if (n.Length >= 1 && (n[n.Length - 1] == '+' || n[n.Length - 1] == '-') &&
Contains((rn = n.Substring(0, n.Length - 1))))
{
p = this[rn];
string v = n[n.Length - 1] == '+' ? option : null;
c.OptionName = option;
c.Option = p;
c.OptionValues.Add(v);
p.Invoke(c);
return true;
}
return false;
}
private bool ParseBundledValue(string f, string n, OptionContext c)
{
if (f != "-")
return false;
for (int i = 0; i < n.Length; ++i)
{
Option p;
string opt = f + n[i].ToString();
string rn = n[i].ToString();
if (!Contains(rn))
{
if (i == 0)
return false;
throw new OptionException(string.Format(localizer(
"Cannot bundle unregistered option '{0}'."), opt), opt);
}
p = this[rn];
switch (p.OptionValueType)
{
case OptionValueType.None:
Invoke(c, opt, n, p);
break;
case OptionValueType.Optional:
case OptionValueType.Required:
{
string v = n.Substring(i + 1);
c.Option = p;
c.OptionName = opt;
ParseValue(v.Length != 0 ? v : null, c);
return true;
}
default:
throw new InvalidOperationException("Unknown OptionValueType: " + p.OptionValueType);
}
}
return true;
}
private static void Invoke(OptionContext c, string name, string value, Option option)
{
c.OptionName = name;
c.Option = option;
c.OptionValues.Add(value);
option.Invoke(c);
}
private const int OptionWidth = 29;
public void WriteOptionDescriptions(TextWriter o)
{
foreach (Option p in this)
{
int written = 0;
if (!WriteOptionPrototype(o, p, ref written))
continue;
if (written < OptionWidth)
o.Write(new string(' ', OptionWidth - written));
else
{
o.WriteLine();
o.Write(new string(' ', OptionWidth));
}
bool indent = false;
string prefix = new string(' ', OptionWidth + 2);
foreach (string line in GetLines(localizer(GetDescription(p.Description))))
{
if (indent)
o.Write(prefix);
o.WriteLine(line);
indent = true;
}
}
}
bool WriteOptionPrototype(TextWriter o, Option p, ref int written)
{
string[] names = p.Names;
int i = GetNextOptionIndex(names, 0);
if (i == names.Length)
return false;
if (names[i].Length == 1)
{
Write(o, ref written, " -");
Write(o, ref written, names[0]);
}
else
{
Write(o, ref written, " --");
Write(o, ref written, names[0]);
}
for (i = GetNextOptionIndex(names, i + 1);
i < names.Length; i = GetNextOptionIndex(names, i + 1))
{
Write(o, ref written, ", ");
Write(o, ref written, names[i].Length == 1 ? "-" : "--");
Write(o, ref written, names[i]);
}
if (p.OptionValueType == OptionValueType.Optional ||
p.OptionValueType == OptionValueType.Required)
{
if (p.OptionValueType == OptionValueType.Optional)
{
Write(o, ref written, localizer("["));
}
Write(o, ref written, localizer("=" + GetArgumentName(0, p.MaxValueCount, p.Description)));
string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
? p.ValueSeparators[0]
: " ";
for (int c = 1; c < p.MaxValueCount; ++c)
{
Write(o, ref written, localizer(sep + GetArgumentName(c, p.MaxValueCount, p.Description)));
}
if (p.OptionValueType == OptionValueType.Optional)
{
Write(o, ref written, localizer("]"));
}
}
return true;
}
static int GetNextOptionIndex(string[] names, int i)
{
while (i < names.Length && names[i] == "<>")
{
++i;
}
return i;
}
static void Write(TextWriter o, ref int n, string s)
{
n += s.Length;
o.Write(s);
}
private static string GetArgumentName(int index, int maxIndex, string description)
{
if (description == null)
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
string[] nameStart;
if (maxIndex == 1)
nameStart = new string[] { "{0:", "{" };
else
nameStart = new string[] { "{" + index + ":" };
for (int i = 0; i < nameStart.Length; ++i)
{
int start, j = 0;
do
{
start = description.IndexOf(nameStart[i], j);
} while (start >= 0 && j != 0 ? description[j++ - 1] == '{' : false);
if (start == -1)
continue;
int end = description.IndexOf("}", start);
if (end == -1)
continue;
return description.Substring(start + nameStart[i].Length, end - start - nameStart[i].Length);
}
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
}
private static string GetDescription(string description)
{
if (description == null)
return string.Empty;
StringBuilder sb = new StringBuilder(description.Length);
int start = -1;
for (int i = 0; i < description.Length; ++i)
{
switch (description[i])
{
case '{':
if (i == start)
{
sb.Append('{');
start = -1;
}
else if (start < 0)
start = i + 1;
break;
case '}':
if (start < 0)
{
if ((i + 1) == description.Length || description[i + 1] != '}')
throw new InvalidOperationException("Invalid option description: " + description);
++i;
sb.Append("}");
}
else
{
sb.Append(description.Substring(start, i - start));
start = -1;
}
break;
case ':':
if (start < 0)
goto default;
start = i + 1;
break;
default:
if (start < 0)
sb.Append(description[i]);
break;
}
}
return sb.ToString();
}
private static IEnumerable<string> GetLines(string description)
{
if (string.IsNullOrEmpty(description))
{
yield return string.Empty;
yield break;
}
int length = 80 - OptionWidth - 1;
int start = 0, end;
do
{
end = GetLineEnd(start, length, description);
char c = description[end - 1];
if (char.IsWhiteSpace(c))
--end;
bool writeContinuation = end != description.Length && !IsEolChar(c);
string line = description.Substring(start, end - start) +
(writeContinuation ? "-" : "");
yield return line;
start = end;
if (char.IsWhiteSpace(c))
++start;
length = 80 - OptionWidth - 2 - 1;
} while (end < description.Length);
}
private static bool IsEolChar(char c)
{
return !char.IsLetterOrDigit(c);
}
private static int GetLineEnd(int start, int length, string description)
{
int end = System.Math.Min(start + length, description.Length);
int sep = -1;
for (int i = start + 1; i < end; ++i)
{
if (description[i] == '\n')
return i + 1;
if (IsEolChar(description[i]))
sep = i + 1;
}
if (sep == -1 || end == description.Length)
return end;
return sep;
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using System.Reflection;
#if !NETCORE
using System.Runtime.Remoting;
using Alachisoft.NCache.Common.Remoting;
#endif
namespace Alachisoft.NCache.Management
{
[CLSCompliant(false)]
public class HostBase :IDisposable
{
protected MarshalByRefObject _remoteableObject;
#if !NETCORE
protected RemotingChannels _channel = new RemotingChannels();
#endif
protected static string _appName = "NCache";
protected string _url;
/// <summary>
/// Overloaded constructor.
/// </summary>
/// <param name="application"></param>
static HostBase()
{
#if !NETCORE
try
{
RemotingConfiguration.ApplicationName = _appName;
}
catch (Exception) { }
#endif
}
public HostBase(MarshalByRefObject remoteableObject,string url)
{
_remoteableObject = remoteableObject;
_url = url;
}
#if !NETCORE
/// <summary> </summary>
public RemotingChannels Channels
{
get { return _channel; }
}
#endif
/// <summary> Returns the application name of this session. </summary>
static public string ApplicationName
{
get { return _appName; }
}
protected virtual int GetHttpPort() { return 0; }
protected virtual int GetTcpPort() { return 0; }
/// <summary>
/// Set things in motion so your service can do its work.
/// </summary>
public void StartHosting(string tcpChannel, string httpChannel)
{
StartHosting(tcpChannel,
GetTcpPort(),
httpChannel,
GetHttpPort());
}
/// <summary>
/// Set things in motion so your service can do its work.
/// </summary>
public void StartHosting(string tcpChannel, string httpChannel, string ip)
{
StartHosting(tcpChannel,
GetTcpPort(),
httpChannel,
GetHttpPort(), ip);
}
public void StartHosting(string tcpChannel, string ip, int port)
{
StartHosting(tcpChannel,
port, ip);
}
public void StartHosting(string tcpChannel, int tcpPort, string ip)
{
#if !NETCORE
_channel.RegisterTcpChannels(tcpChannel, ip, tcpPort);
#endif
//assign the BindToIP to cacheserver.clusterip
if (_remoteableObject is CacheServer)
((CacheServer)_remoteableObject).ClusterIP = ip;
#if !NETCORE
RemotingServices.Marshal(_remoteableObject, _url);
#endif
}
/// <summary>
/// Set things in motion so your service can do its work.
/// </summary>
public void StartHosting(string tcpChannel, int tcpPort, string httpChannel, int httpPort, string ip)
{
try
{
#if !NETCORE
_channel.RegisterTcpChannels(tcpChannel, ip, tcpPort);
_channel.RegisterHttpChannels(httpChannel, ip, httpPort);
Assembly remoting = Assembly.GetAssembly(typeof(System.Runtime.Remoting.RemotingConfiguration));
#endif
//assign the BindToIP to cacheserver.clusterip
if (_remoteableObject is CacheServer)
((CacheServer)_remoteableObject).ClusterIP = ip;
#if !NETCORE
RemotingServices.Marshal(_remoteableObject, _url);
RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off;
#endif
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Set things in motion so your service can do its work.
/// </summary>
public void StartHosting(string tcpChannel, int tcpPort, string httpChannel, int httpPort)
{
try
{
#if !NETCORE
_channel.RegisterTcpChannels(tcpChannel, tcpPort);
_channel.RegisterHttpChannels(httpChannel, httpPort);
#endif
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Set things in motion so your service can do its work.
/// </summary>
private void StartHosting(string tcpChannel, int tcpPort, string httpChannel, int httpPort, int sendBuffer, int receiveBuffer)
{
try
{
#if !NETCORE
_channel.RegisterTcpChannels(tcpChannel, tcpPort);
_channel.RegisterHttpChannels(httpChannel, httpPort);
RemotingServices.Marshal(_remoteableObject, CacheServer.ObjectUri);
RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off;
#endif
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Stop this service.
/// </summary>
public void StopHosting()
{
try
{
if (_remoteableObject != null)
{
#if !NETCORE
RemotingServices.Disconnect(_remoteableObject);
_channel.UnregisterTcpChannels();
_channel.UnregisterHttpChannels();
#endif
((IDisposable)_remoteableObject).Dispose();
}
}
catch (Exception)
{
throw;
}
}
#region IDisposable
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or
/// resetting unmanaged resources.
/// </summary>
/// <param name="disposing"></param>
/// <remarks>
/// </remarks>
private void Dispose(bool disposing)
{
if (_remoteableObject != null)
{
((IDisposable)_remoteableObject).Dispose();
_remoteableObject = null;
if (disposing) GC.SuppressFinalize(this);
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or
/// resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
}
#endregion
}
}
| |
namespace java.net
{
[global::MonoJavaBridge.JavaClass(typeof(global::java.net.SocketImpl_))]
public abstract partial class SocketImpl : java.lang.Object, SocketOptions
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static SocketImpl()
{
InitJNI();
}
protected SocketImpl(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _getOption13810;
public abstract global::java.lang.Object getOption(int arg0);
internal static global::MonoJavaBridge.MethodId _setOption13811;
public abstract void setOption(int arg0, java.lang.Object arg1);
internal static global::MonoJavaBridge.MethodId _toString13812;
public override global::java.lang.String toString()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.net.SocketImpl._toString13812)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.net.SocketImpl.staticClass, global::java.net.SocketImpl._toString13812)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _close13813;
protected abstract void close();
internal static global::MonoJavaBridge.MethodId _accept13814;
protected abstract void accept(java.net.SocketImpl arg0);
internal static global::MonoJavaBridge.MethodId _getPort13815;
protected virtual int getPort()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.net.SocketImpl._getPort13815);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.net.SocketImpl.staticClass, global::java.net.SocketImpl._getPort13815);
}
internal static global::MonoJavaBridge.MethodId _create13816;
protected abstract void create(bool arg0);
internal static global::MonoJavaBridge.MethodId _getInputStream13817;
protected abstract global::java.io.InputStream getInputStream();
internal static global::MonoJavaBridge.MethodId _available13818;
protected abstract int available();
internal static global::MonoJavaBridge.MethodId _connect13819;
protected abstract void connect(java.net.SocketAddress arg0, int arg1);
internal static global::MonoJavaBridge.MethodId _connect13820;
protected abstract void connect(java.net.InetAddress arg0, int arg1);
internal static global::MonoJavaBridge.MethodId _connect13821;
protected abstract void connect(java.lang.String arg0, int arg1);
internal static global::MonoJavaBridge.MethodId _getOutputStream13822;
protected abstract global::java.io.OutputStream getOutputStream();
internal static global::MonoJavaBridge.MethodId _getFileDescriptor13823;
protected virtual global::java.io.FileDescriptor getFileDescriptor()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.net.SocketImpl._getFileDescriptor13823)) as java.io.FileDescriptor;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.net.SocketImpl.staticClass, global::java.net.SocketImpl._getFileDescriptor13823)) as java.io.FileDescriptor;
}
internal static global::MonoJavaBridge.MethodId _listen13824;
protected abstract void listen(int arg0);
internal static global::MonoJavaBridge.MethodId _bind13825;
protected abstract void bind(java.net.InetAddress arg0, int arg1);
internal static global::MonoJavaBridge.MethodId _shutdownInput13826;
protected virtual void shutdownInput()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.net.SocketImpl._shutdownInput13826);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.net.SocketImpl.staticClass, global::java.net.SocketImpl._shutdownInput13826);
}
internal static global::MonoJavaBridge.MethodId _shutdownOutput13827;
protected virtual void shutdownOutput()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.net.SocketImpl._shutdownOutput13827);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.net.SocketImpl.staticClass, global::java.net.SocketImpl._shutdownOutput13827);
}
internal static global::MonoJavaBridge.MethodId _getInetAddress13828;
protected virtual global::java.net.InetAddress getInetAddress()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.net.SocketImpl._getInetAddress13828)) as java.net.InetAddress;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.net.SocketImpl.staticClass, global::java.net.SocketImpl._getInetAddress13828)) as java.net.InetAddress;
}
internal static global::MonoJavaBridge.MethodId _getLocalPort13829;
protected virtual int getLocalPort()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.net.SocketImpl._getLocalPort13829);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.net.SocketImpl.staticClass, global::java.net.SocketImpl._getLocalPort13829);
}
internal static global::MonoJavaBridge.MethodId _sendUrgentData13830;
protected abstract void sendUrgentData(int arg0);
internal static global::MonoJavaBridge.MethodId _setPerformancePreferences13831;
protected virtual void setPerformancePreferences(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.net.SocketImpl._setPerformancePreferences13831, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.net.SocketImpl.staticClass, global::java.net.SocketImpl._setPerformancePreferences13831, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _supportsUrgentData13832;
protected virtual bool supportsUrgentData()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.net.SocketImpl._supportsUrgentData13832);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.net.SocketImpl.staticClass, global::java.net.SocketImpl._supportsUrgentData13832);
}
internal static global::MonoJavaBridge.MethodId _SocketImpl13833;
public SocketImpl() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.net.SocketImpl.staticClass, global::java.net.SocketImpl._SocketImpl13833);
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.net.SocketImpl.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/net/SocketImpl"));
global::java.net.SocketImpl._getOption13810 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "getOption", "(I)Ljava/lang/Object;");
global::java.net.SocketImpl._setOption13811 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "setOption", "(ILjava/lang/Object;)V");
global::java.net.SocketImpl._toString13812 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "toString", "()Ljava/lang/String;");
global::java.net.SocketImpl._close13813 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "close", "()V");
global::java.net.SocketImpl._accept13814 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "accept", "(Ljava/net/SocketImpl;)V");
global::java.net.SocketImpl._getPort13815 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "getPort", "()I");
global::java.net.SocketImpl._create13816 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "create", "(Z)V");
global::java.net.SocketImpl._getInputStream13817 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "getInputStream", "()Ljava/io/InputStream;");
global::java.net.SocketImpl._available13818 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "available", "()I");
global::java.net.SocketImpl._connect13819 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "connect", "(Ljava/net/SocketAddress;I)V");
global::java.net.SocketImpl._connect13820 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "connect", "(Ljava/net/InetAddress;I)V");
global::java.net.SocketImpl._connect13821 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "connect", "(Ljava/lang/String;I)V");
global::java.net.SocketImpl._getOutputStream13822 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "getOutputStream", "()Ljava/io/OutputStream;");
global::java.net.SocketImpl._getFileDescriptor13823 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "getFileDescriptor", "()Ljava/io/FileDescriptor;");
global::java.net.SocketImpl._listen13824 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "listen", "(I)V");
global::java.net.SocketImpl._bind13825 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "bind", "(Ljava/net/InetAddress;I)V");
global::java.net.SocketImpl._shutdownInput13826 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "shutdownInput", "()V");
global::java.net.SocketImpl._shutdownOutput13827 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "shutdownOutput", "()V");
global::java.net.SocketImpl._getInetAddress13828 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "getInetAddress", "()Ljava/net/InetAddress;");
global::java.net.SocketImpl._getLocalPort13829 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "getLocalPort", "()I");
global::java.net.SocketImpl._sendUrgentData13830 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "sendUrgentData", "(I)V");
global::java.net.SocketImpl._setPerformancePreferences13831 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "setPerformancePreferences", "(III)V");
global::java.net.SocketImpl._supportsUrgentData13832 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "supportsUrgentData", "()Z");
global::java.net.SocketImpl._SocketImpl13833 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl.staticClass, "<init>", "()V");
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::java.net.SocketImpl))]
public sealed partial class SocketImpl_ : java.net.SocketImpl
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static SocketImpl_()
{
InitJNI();
}
internal SocketImpl_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _getOption13834;
public override global::java.lang.Object getOption(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.net.SocketImpl_._getOption13834, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.net.SocketImpl_.staticClass, global::java.net.SocketImpl_._getOption13834, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object;
}
internal static global::MonoJavaBridge.MethodId _setOption13835;
public override void setOption(int arg0, java.lang.Object arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.net.SocketImpl_._setOption13835, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.net.SocketImpl_.staticClass, global::java.net.SocketImpl_._setOption13835, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _close13836;
protected override void close()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.net.SocketImpl_._close13836);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.net.SocketImpl_.staticClass, global::java.net.SocketImpl_._close13836);
}
internal static global::MonoJavaBridge.MethodId _accept13837;
protected override void accept(java.net.SocketImpl arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.net.SocketImpl_._accept13837, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.net.SocketImpl_.staticClass, global::java.net.SocketImpl_._accept13837, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _create13838;
protected override void create(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.net.SocketImpl_._create13838, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.net.SocketImpl_.staticClass, global::java.net.SocketImpl_._create13838, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getInputStream13839;
protected override global::java.io.InputStream getInputStream()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.net.SocketImpl_._getInputStream13839)) as java.io.InputStream;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.net.SocketImpl_.staticClass, global::java.net.SocketImpl_._getInputStream13839)) as java.io.InputStream;
}
internal static global::MonoJavaBridge.MethodId _available13840;
protected override int available()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.net.SocketImpl_._available13840);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.net.SocketImpl_.staticClass, global::java.net.SocketImpl_._available13840);
}
internal static global::MonoJavaBridge.MethodId _connect13841;
protected override void connect(java.net.SocketAddress arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.net.SocketImpl_._connect13841, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.net.SocketImpl_.staticClass, global::java.net.SocketImpl_._connect13841, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _connect13842;
protected override void connect(java.net.InetAddress arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.net.SocketImpl_._connect13842, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.net.SocketImpl_.staticClass, global::java.net.SocketImpl_._connect13842, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _connect13843;
protected override void connect(java.lang.String arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.net.SocketImpl_._connect13843, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.net.SocketImpl_.staticClass, global::java.net.SocketImpl_._connect13843, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getOutputStream13844;
protected override global::java.io.OutputStream getOutputStream()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.net.SocketImpl_._getOutputStream13844)) as java.io.OutputStream;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.net.SocketImpl_.staticClass, global::java.net.SocketImpl_._getOutputStream13844)) as java.io.OutputStream;
}
internal static global::MonoJavaBridge.MethodId _listen13845;
protected override void listen(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.net.SocketImpl_._listen13845, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.net.SocketImpl_.staticClass, global::java.net.SocketImpl_._listen13845, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _bind13846;
protected override void bind(java.net.InetAddress arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.net.SocketImpl_._bind13846, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.net.SocketImpl_.staticClass, global::java.net.SocketImpl_._bind13846, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _sendUrgentData13847;
protected override void sendUrgentData(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.net.SocketImpl_._sendUrgentData13847, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.net.SocketImpl_.staticClass, global::java.net.SocketImpl_._sendUrgentData13847, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.net.SocketImpl_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/net/SocketImpl"));
global::java.net.SocketImpl_._getOption13834 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl_.staticClass, "getOption", "(I)Ljava/lang/Object;");
global::java.net.SocketImpl_._setOption13835 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl_.staticClass, "setOption", "(ILjava/lang/Object;)V");
global::java.net.SocketImpl_._close13836 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl_.staticClass, "close", "()V");
global::java.net.SocketImpl_._accept13837 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl_.staticClass, "accept", "(Ljava/net/SocketImpl;)V");
global::java.net.SocketImpl_._create13838 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl_.staticClass, "create", "(Z)V");
global::java.net.SocketImpl_._getInputStream13839 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl_.staticClass, "getInputStream", "()Ljava/io/InputStream;");
global::java.net.SocketImpl_._available13840 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl_.staticClass, "available", "()I");
global::java.net.SocketImpl_._connect13841 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl_.staticClass, "connect", "(Ljava/net/SocketAddress;I)V");
global::java.net.SocketImpl_._connect13842 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl_.staticClass, "connect", "(Ljava/net/InetAddress;I)V");
global::java.net.SocketImpl_._connect13843 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl_.staticClass, "connect", "(Ljava/lang/String;I)V");
global::java.net.SocketImpl_._getOutputStream13844 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl_.staticClass, "getOutputStream", "()Ljava/io/OutputStream;");
global::java.net.SocketImpl_._listen13845 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl_.staticClass, "listen", "(I)V");
global::java.net.SocketImpl_._bind13846 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl_.staticClass, "bind", "(Ljava/net/InetAddress;I)V");
global::java.net.SocketImpl_._sendUrgentData13847 = @__env.GetMethodIDNoThrow(global::java.net.SocketImpl_.staticClass, "sendUrgentData", "(I)V");
}
}
}
| |
// $begin{copyright}
//
// This file is part of WebSharper
//
// Copyright (c) 2008-2018 IntelliFactory
//
// 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.
//
// $end{copyright}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebSharper.Testing;
namespace WebSharper.CSharp.Tests
{
[JavaScript, Test("C# classes")]
class ObjectTests : TestCategory
{
public static bool StaticConstructorRan = false;
class CctorTest
{
public static int TestStatic = 0;
static CctorTest()
{
TestStatic = 1;
StaticConstructorRan = true;
}
public static void RunCctor() { }
}
[Test]
public void StaticConstructor()
{
CctorTest.RunCctor();
IsTrue(StaticConstructorRan);
Equal(CctorTest.TestStatic, 1);
}
class CtorTest
{
public int OriginalValue;
public int Value = 1;
public CtorTest()
{
OriginalValue = Value;
Value = 2;
}
public CtorTest(int value) : this()
{
Value = value;
}
public CtorTest(bool bvalue) : this(bvalue ? 1 : 0)
{
}
}
[Test]
public void Constructor()
{
var o1 = new CtorTest();
Equal(o1.OriginalValue, 1);
Equal(o1.Value, 2);
var o2 = new CtorTest(3);
Equal(o2.OriginalValue, 1);
Equal(o2.Value, 3);
var o3 = new CtorTest() { Value = 4 };
Equal(o3.OriginalValue, 1);
Equal(o3.Value, 4);
}
class GenericClass<T>
{
public U GenericMethod<U>(U x)
{
return x;
}
}
[Test]
public void Generics()
{
Equal(new GenericClass<int>().GenericMethod<string>("test"), "test");
}
class SubClass : BaseClass
{
public SubClass() : base(2) { }
public override int VirtualMethod() { return 2; }
public int BaseCall() { return base.VirtualMethod(); }
public SubClass(int v) : this() { Value += v; }
}
class BaseClass : AbstractBaseClass
{
public virtual int VirtualMethod() { return 1; }
public override int AbstractMethod() { return 2; }
public BaseClass() { }
public BaseClass(int v) { Value = v; }
public int Value = 1;
}
abstract class AbstractBaseClass
{
public abstract int AbstractMethod();
}
[Test]
public void Inheritance()
{
Equal(new BaseClass().Value, 1, "Field initialization");
Equal(new BaseClass().VirtualMethod(), 1, "Virtual method");
Equal(new BaseClass().AbstractMethod(), 2, "Abstract method");
Equal((new BaseClass() as AbstractBaseClass).AbstractMethod(), 2, "Abstract method called on base class");
Equal(new BaseClass(3).Value, 3, "Overloaded constructor");
Equal(new SubClass().Value, 2, "Base call on constructor");
Equal(new SubClass().VirtualMethod(), 2, "Overridden method");
Equal(new SubClass().BaseCall(), 1, "Base method call");
Equal(new SubClass(3).Value, 5, "Chained constructor");
}
interface ISomething
{
int Foo();
string Bar { get; }
}
class Something : ISomething
{
public string Bar => "Bar";
public int Foo() => 42;
}
[Test]
public void InterfaceImplementations()
{
var o = new Something();
Equal(o.Bar, "Bar");
Equal(((ISomething)o).Bar, "Bar");
Equal(o.Foo(), 42);
Equal(((ISomething)o).Foo(), 42);
}
struct StructTest
{
public readonly int X;
public readonly string Y;
public StructTest(int x, string y)
{
X = x;
Y = y;
}
public int X2 => X + 1;
}
StructTest DefStruct;
[Test]
public void Struct()
{
Equal(new StructTest().X, 0);
Equal(new StructTest().Y, null);
Equal(DefStruct.X, 0);
Equal(DefStruct.Y, null);
Equal(new StructTest(1, "").X, 1);
Equal(new StructTest(1, "").X2, 2);
}
[Test]
public void PartialClasses()
{
var o = new PartialClass();
Equal(o.Field1, 1);
Equal(o.Field2, 2);
Equal(o.Value, 0);
o.SetValueTo3ByPartialMethod();
Equal(o.Value, 3);
o.SetValueTo4();
Equal(o.Value, 4);
}
class Renamings
{
[Name("x")]
public int y = 1;
[Name("X")]
public int RNValue { get { return y; } set { y = value; } }
[Name("GetX")]
public int RNMethod() => y;
[Name("xx")]
public int yy { get; set; } = 2;
}
[Test]
public void Renaming()
{
var r = new Renamings();
Equal(r.y, 1);
r.y = 2;
Equal(r.y, 2);
Equal(r.RNValue, 2);
r.RNValue = 3;
Equal(r.RNValue, 3);
Equal(r.RNMethod(), 3);
Equal(r.yy, 2);
r.yy = 3;
Equal(r.yy, 3);
dynamic o = r;
Equal(o.x, 3);
Equal(o.X(), 3);
Equal(o.GetX(), 3);
o.set_X(4);
Equal(o.x, 4);
Equal(o.xx(), 3);
o.set_xx(4);
Equal(o.xx(), 4);
}
[JavaScript]
public struct MyStruct
{
public readonly int X;
public readonly int Y;
public MyStruct(int x, int y)
{
this.X = x;
this.Y = y;
}
public int Sum => X + Y;
}
[Test]
public void Structs()
{
var s1 = new MyStruct(1, 2);
var s2 = new MyStruct(1, 2);
var s3 = new MyStruct(1, 3);
IsTrue(s1.Equals(s2));
IsTrue((object)s1 == (object)s2);
IsTrue((System.ValueType)s1 == (System.ValueType)s2);
IsFalse(s1.Equals(s3));
IsTrue(s1.GetHashCode() != -1);
Equal(s1.Sum, 3);
}
public class MyException : Exception
{
public bool IsThisMyException => true;
public MyException() : base("This is my exception") { }
}
[Test]
public void Exception()
{
var res = "";
try
{
throw new MyException();
}
catch (MyException e)
{
if (e.IsThisMyException)
{
if (e.Message == "This is my exception")
res = "ok";
else
res = "wrong message on exception";
}
else
res = "wrong method value on exception";
}
catch (ArgumentException)
{
res = "wrong type of exception";
}
catch
{
res = "wrong type of exception";
}
Equal(res, "ok");
}
}
[JavaScript]
public partial class PartialClass
{
public int Field1 = 1;
public int Value { get; set; }
partial void PartialMethod();
public void SetValueTo3ByPartialMethod()
{
PartialMethod();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KSP.Localization;
namespace KERBALISM
{
public class ExperimentRequirements
{
public enum Require
{
OrbitMinInclination,
OrbitMaxInclination,
OrbitMinEccentricity,
OrbitMaxEccentricity,
OrbitMinArgOfPeriapsis,
OrbitMaxArgOfPeriapsis,
TemperatureMin,
TemperatureMax,
AltitudeMin,
AltitudeMax,
RadiationMin,
RadiationMax,
Shadow,
Sunlight,
CrewMin,
CrewMax,
CrewCapacityMin,
CrewCapacityMax,
VolumePerCrewMin,
VolumePerCrewMax,
Greenhouse,
AtmosphereAltMin,
AtmosphereAltMax,
SunAngleMin,
SunAngleMax,
AbsoluteZero,
InnerBelt,
OuterBelt,
MagneticBelt,
Magnetosphere,
InterStellar,
SurfaceSpeedMin,
SurfaceSpeedMax,
VerticalSpeedMin,
VerticalSpeedMax,
SpeedMin,
SpeedMax,
DynamicPressureMin,
DynamicPressureMax,
StaticPressureMin,
StaticPressureMax,
AtmDensityMin,
AtmDensityMax,
AltAboveGroundMin,
AltAboveGroundMax,
Part,
Module,
MaxAsteroidDistance,
AstronautComplexLevelMin,
AstronautComplexLevelMax,
TrackingStationLevelMin,
TrackingStationLevelMax,
MissionControlLevelMin,
MissionControlLevelMax,
AdministrationLevelMin,
AdministrationLevelMax,
}
public class RequireDef
{
public Require require;
public object value;
public RequireDef(Require require, object requireValue)
{
this.require = require;
this.value = requireValue;
}
}
public class RequireResult
{
public RequireDef requireDef;
public object value;
public double result;
public RequireResult(RequireDef requireDef)
{
this.requireDef = requireDef;
result = 0.0;
}
}
// not ideal because unboxing at but least we won't be parsing strings all the time and the array should be fast
public RequireDef[] Requires { get; private set; }
public ExperimentRequirements(string requires)
{
Requires = ParseRequirements(requires);
}
public double TestRequirements(Vessel v, out RequireResult[] results, bool testAll = false)
{
UnityEngine.Profiling.Profiler.BeginSample("Kerbalism.ExperimentRequirements.TestRequirements");
VesselData vd = v.KerbalismData();
results = new RequireResult[Requires.Length];
double result = 1.0;
for (int i = 0; i < Requires.Length; i++)
{
results[i] = new RequireResult(Requires[i]);
switch (Requires[i].require)
{
case Require.OrbitMinInclination : TestReq((c, r) => c >= r, v.orbit.inclination, (double)Requires[i].value, results[i]); break;
case Require.OrbitMaxInclination : TestReq((c, r) => c <= r, v.orbit.inclination, (double)Requires[i].value, results[i]); break;
case Require.OrbitMinEccentricity : TestReq((c, r) => c >= r, v.orbit.eccentricity, (double)Requires[i].value, results[i]); break;
case Require.OrbitMaxEccentricity : TestReq((c, r) => c <= r, v.orbit.eccentricity, (double)Requires[i].value, results[i]); break;
case Require.OrbitMinArgOfPeriapsis: TestReq((c, r) => c >= r, v.orbit.argumentOfPeriapsis, (double)Requires[i].value, results[i]); break;
case Require.OrbitMaxArgOfPeriapsis: TestReq((c, r) => c <= r, v.orbit.argumentOfPeriapsis, (double)Requires[i].value, results[i]); break;
case Require.TemperatureMin : TestReq((c, r) => c >= r, vd.EnvTemperature, (double)Requires[i].value, results[i]); break;
case Require.TemperatureMax : TestReq((c, r) => c <= r, vd.EnvTemperature, (double)Requires[i].value, results[i]); break;
case Require.AltitudeMin : TestReq((c, r) => c >= r, v.altitude, (double)Requires[i].value, results[i]); break;
case Require.AltitudeMax : TestReq((c, r) => c <= r, v.altitude, (double)Requires[i].value, results[i]); break;
case Require.RadiationMin : TestReq((c, r) => c >= r, vd.EnvRadiation, (double)Requires[i].value, results[i]); break;
case Require.RadiationMax : TestReq((c, r) => c <= r, vd.EnvRadiation, (double)Requires[i].value, results[i]); break;
case Require.VolumePerCrewMin : TestReq((c, r) => c >= r, vd.VolumePerCrew, (double)Requires[i].value, results[i]); break;
case Require.VolumePerCrewMax : TestReq((c, r) => c <= r, vd.VolumePerCrew, (double)Requires[i].value, results[i]); break;
case Require.SunAngleMin : TestReq((c, r) => c >= r, vd.EnvSunBodyAngle, (double)Requires[i].value, results[i]); break;
case Require.SunAngleMax : TestReq((c, r) => c <= r, vd.EnvSunBodyAngle, (double)Requires[i].value, results[i]); break;
case Require.SurfaceSpeedMin : TestReq((c, r) => c >= r, v.srfSpeed, (double)Requires[i].value, results[i]); break;
case Require.SurfaceSpeedMax : TestReq((c, r) => c <= r, v.srfSpeed, (double)Requires[i].value, results[i]); break;
case Require.VerticalSpeedMin : TestReq((c, r) => c >= r, v.verticalSpeed, (double)Requires[i].value, results[i]); break;
case Require.VerticalSpeedMax : TestReq((c, r) => c <= r, v.verticalSpeed, (double)Requires[i].value, results[i]); break;
case Require.SpeedMin : TestReq((c, r) => c >= r, v.speed, (double)Requires[i].value, results[i]); break;
case Require.SpeedMax : TestReq((c, r) => c <= r, v.speed, (double)Requires[i].value, results[i]); break;
case Require.DynamicPressureMin : TestReq((c, r) => c >= r, v.dynamicPressurekPa, (double)Requires[i].value, results[i]); break;
case Require.DynamicPressureMax : TestReq((c, r) => c <= r, v.dynamicPressurekPa, (double)Requires[i].value, results[i]); break;
case Require.StaticPressureMin : TestReq((c, r) => c >= r, v.staticPressurekPa, (double)Requires[i].value, results[i]); break;
case Require.StaticPressureMax : TestReq((c, r) => c <= r, v.staticPressurekPa, (double)Requires[i].value, results[i]); break;
case Require.AtmDensityMin : TestReq((c, r) => c >= r, v.atmDensity, (double)Requires[i].value, results[i]); break;
case Require.AtmDensityMax : TestReq((c, r) => c <= r, v.atmDensity, (double)Requires[i].value, results[i]); break;
case Require.AltAboveGroundMin : TestReq((c, r) => c >= r, v.heightFromTerrain, (double)Requires[i].value, results[i]); break;
case Require.AltAboveGroundMax : TestReq((c, r) => c <= r, v.heightFromTerrain, (double)Requires[i].value, results[i]); break;
case Require.MaxAsteroidDistance : TestReq((c, r) => c <= r, TestAsteroidDistance(v), (double)Requires[i].value, results[i]); break;
case Require.AtmosphereAltMin : TestReq((c, r) => c >= r, v.mainBody.atmosphere ? v.altitude / v.mainBody.atmosphereDepth : double.NaN, (double)Requires[i].value, results[i]); break;
case Require.AtmosphereAltMax : TestReq((c, r) => c <= r, v.mainBody.atmosphere ? v.altitude / v.mainBody.atmosphereDepth : double.NaN, (double)Requires[i].value, results[i]); break;
case Require.CrewMin : TestReq((c, r) => c >= r, vd.CrewCount, (int)Requires[i].value, results[i]); break;
case Require.CrewMax : TestReq((c, r) => c <= r, vd.CrewCount, (int)Requires[i].value, results[i]); break;
case Require.CrewCapacityMin : TestReq((c, r) => c >= r, vd.CrewCapacity, (int)Requires[i].value, results[i]); break;
case Require.CrewCapacityMax : TestReq((c, r) => c <= r, vd.CrewCapacity, (int)Requires[i].value, results[i]); break;
case Require.AstronautComplexLevelMin: TestReq((c, r) => c >= r, GetFacilityLevel(SpaceCenterFacility.AstronautComplex), (int)Requires[i].value, results[i]); break;
case Require.AstronautComplexLevelMax: TestReq((c, r) => c <= r, GetFacilityLevel(SpaceCenterFacility.AstronautComplex), (int)Requires[i].value, results[i]); break;
case Require.TrackingStationLevelMin : TestReq((c, r) => c >= r, GetFacilityLevel(SpaceCenterFacility.TrackingStation), (int)Requires[i].value, results[i]); break;
case Require.TrackingStationLevelMax : TestReq((c, r) => c <= r, GetFacilityLevel(SpaceCenterFacility.TrackingStation), (int)Requires[i].value, results[i]); break;
case Require.MissionControlLevelMin : TestReq((c, r) => c >= r, GetFacilityLevel(SpaceCenterFacility.MissionControl), (int)Requires[i].value, results[i]); break;
case Require.MissionControlLevelMax : TestReq((c, r) => c <= r, GetFacilityLevel(SpaceCenterFacility.MissionControl), (int)Requires[i].value, results[i]); break;
case Require.AdministrationLevelMin : TestReq((c, r) => c >= r, GetFacilityLevel(SpaceCenterFacility.Administration), (int)Requires[i].value, results[i]); break;
case Require.AdministrationLevelMax : TestReq((c, r) => c <= r, GetFacilityLevel(SpaceCenterFacility.Administration), (int)Requires[i].value, results[i]); break;
case Require.Shadow : TestReq(1.0 - vd.EnvSunlightFactor, results[i]); break;
case Require.Sunlight : TestReq(vd.EnvSunlightFactor, results[i]); break;
case Require.Greenhouse : TestReq(() => vd.Greenhouses.Count > 0, results[i]); break;
case Require.AbsoluteZero : TestReq(() => vd.EnvTemperature < 30.0, results[i]); break;
case Require.InnerBelt : TestReq(() => vd.EnvInnerBelt, results[i]); break;
case Require.OuterBelt : TestReq(() => vd.EnvOuterBelt, results[i]); break;
case Require.MagneticBelt : TestReq(() => vd.EnvInnerBelt || vd.EnvOuterBelt, results[i]); break;
case Require.Magnetosphere : TestReq(() => vd.EnvMagnetosphere, results[i]); break;
case Require.InterStellar : TestReq(() => Lib.IsSun(v.mainBody) && vd.EnvInterstellar, results[i]); break;
case Require.Part : TestReq(() => Lib.HasPart(v, (string)Requires[i].value), results[i]); break;
case Require.Module : TestReq(() => Lib.FindModules(v.protoVessel, (string)Requires[i].value).Count > 0, results[i]); break;
default: results[i].result = 1.0; break;
}
if (!testAll && results[i].result == 0.0)
{
UnityEngine.Profiling.Profiler.EndSample();
return 0.0;
}
result *= results[i].result;
}
UnityEngine.Profiling.Profiler.EndSample();
return result;
}
public bool TestProgressionRequirements()
{
RequireResult[] results = new RequireResult[Requires.Length];
for (int i = 0; i < Requires.Length; i++)
{
results[i] = new RequireResult(Requires[i]);
switch (Requires[i].require)
{
case Require.AstronautComplexLevelMin: TestReq((c, r) => c >= r, GetFacilityLevel(SpaceCenterFacility.AstronautComplex), (int)Requires[i].value, results[i]); break;
case Require.AstronautComplexLevelMax: TestReq((c, r) => c <= r, GetFacilityLevel(SpaceCenterFacility.AstronautComplex), (int)Requires[i].value, results[i]); break;
case Require.TrackingStationLevelMin: TestReq((c, r) => c >= r, GetFacilityLevel(SpaceCenterFacility.TrackingStation), (int)Requires[i].value, results[i]); break;
case Require.TrackingStationLevelMax: TestReq((c, r) => c <= r, GetFacilityLevel(SpaceCenterFacility.TrackingStation), (int)Requires[i].value, results[i]); break;
case Require.MissionControlLevelMin: TestReq((c, r) => c >= r, GetFacilityLevel(SpaceCenterFacility.MissionControl), (int)Requires[i].value, results[i]); break;
case Require.MissionControlLevelMax: TestReq((c, r) => c <= r, GetFacilityLevel(SpaceCenterFacility.MissionControl), (int)Requires[i].value, results[i]); break;
case Require.AdministrationLevelMin: TestReq((c, r) => c >= r, GetFacilityLevel(SpaceCenterFacility.Administration), (int)Requires[i].value, results[i]); break;
case Require.AdministrationLevelMax: TestReq((c, r) => c <= r, GetFacilityLevel(SpaceCenterFacility.Administration), (int)Requires[i].value, results[i]); break;
default: results[i].result = 1.0; break;
}
if (results[i].result == 0.0)
return false;
}
return true;
}
private void TestReq(Func<bool> Condition, RequireResult result)
{
result.result = Condition() ? 1.0 : 0.0;
}
private void TestReq<T, U>(Func<T, U, bool> Condition, T val, U reqVal, RequireResult result)
{
result.result = Condition(val, reqVal) ? 1.0 : 0.0;
result.value = val;
}
private void TestReq(double val, RequireResult result)
{
result.result = val;
result.value = val;
}
private RequireDef[] ParseRequirements(string requires)
{
List<RequireDef> reqList = new List<RequireDef>();
if (string.IsNullOrEmpty(requires))
return reqList.ToArray();
foreach (string s in requires.Split(','))
{
s.Trim();
string[] reqString = s.Split(':');
if (reqString.Length > 0)
{
reqString[0].Trim();
if (reqString.Length > 1)
{
reqString[1].Trim();
// key/value requirements
if (!Enum.IsDefined(typeof(Require), reqString[0]))
{
Lib.Log("Could not parse the experiment requires '" + s + "'", Lib.LogLevel.Warning);
continue;
}
Require reqEnum = (Require)Enum.Parse(typeof(Require), reqString[0]);
if (reqEnum == Require.Part)
reqString[1] = reqString[1].Replace('_', '.');
reqList.Add(ParseRequiresValue(reqEnum, reqString[1]));
}
else
{
// boolean condition, no value
if (!Enum.IsDefined(typeof(Require), reqString[0]))
{
Lib.Log("Could not parse the experiment requires '" + s + "'", Lib.LogLevel.Warning);
continue;
}
Require reqEnum = (Require)Enum.Parse(typeof(Require), reqString[0]);
reqList.Add(new RequireDef(reqEnum, null));
}
}
}
return reqList.ToArray();
}
private RequireDef ParseRequiresValue(Require req, string value)
{
switch (req)
{
case Require.OrbitMinInclination:
case Require.OrbitMaxInclination:
case Require.OrbitMinEccentricity:
case Require.OrbitMaxEccentricity:
case Require.OrbitMinArgOfPeriapsis:
case Require.OrbitMaxArgOfPeriapsis:
case Require.TemperatureMin:
case Require.TemperatureMax:
case Require.AltitudeMin:
case Require.AltitudeMax:
case Require.RadiationMin:
case Require.RadiationMax:
case Require.VolumePerCrewMin:
case Require.VolumePerCrewMax:
case Require.AtmosphereAltMin:
case Require.AtmosphereAltMax:
case Require.SunAngleMin:
case Require.SunAngleMax:
case Require.SurfaceSpeedMin:
case Require.SurfaceSpeedMax:
case Require.VerticalSpeedMin:
case Require.VerticalSpeedMax:
case Require.SpeedMin:
case Require.SpeedMax:
case Require.DynamicPressureMin:
case Require.DynamicPressureMax:
case Require.StaticPressureMin:
case Require.StaticPressureMax:
case Require.AtmDensityMin:
case Require.AtmDensityMax:
case Require.AltAboveGroundMin:
case Require.AltAboveGroundMax:
case Require.MaxAsteroidDistance:
return new RequireDef(req, double.Parse(value));
case Require.CrewMin:
case Require.CrewMax:
case Require.CrewCapacityMin:
case Require.CrewCapacityMax:
case Require.AstronautComplexLevelMin:
case Require.AstronautComplexLevelMax:
case Require.TrackingStationLevelMin:
case Require.TrackingStationLevelMax:
case Require.MissionControlLevelMin:
case Require.MissionControlLevelMax:
case Require.AdministrationLevelMin:
case Require.AdministrationLevelMax:
return new RequireDef(req, int.Parse(value));
default:
return new RequireDef(req, value);
}
}
private int GetFacilityLevel(SpaceCenterFacility facility)
{
if (ScenarioUpgradeableFacilities.Instance == null || !ScenarioUpgradeableFacilities.Instance.enabled)
return int.MaxValue;
double maxlevel = ScenarioUpgradeableFacilities.GetFacilityLevelCount(facility);
if (maxlevel <= 0) maxlevel = 2; // not sure why, but GetFacilityLevelCount return -1 in career
return (int)Math.Round(ScenarioUpgradeableFacilities.GetFacilityLevel(facility) * maxlevel + 1); // They start counting at 0
}
private double TestAsteroidDistance(Vessel vessel)
{
var target = vessel.targetObject;
var vesselPosition = Lib.VesselPosition(vessel);
// while there is a target, only consider the targeted vessel
if (!vessel.loaded || target != null)
{
// asteroid MUST be the target if vessel is unloaded
if (target == null) return double.MaxValue;
var targetVessel = target.GetVessel();
if (targetVessel == null) return double.MaxValue;
if (targetVessel.vesselType != VesselType.SpaceObject) return double.MaxValue;
// this assumes that all vessels of type space object are asteroids.
// should be a safe bet unless Squad introduces alien UFOs.
var asteroidPosition = Lib.VesselPosition(targetVessel);
return Vector3d.Distance(vesselPosition, asteroidPosition);
}
// there's no target and vessel is not unloaded
// look for nearby asteroids
double result = double.MaxValue;
foreach (Vessel v in FlightGlobals.VesselsLoaded)
{
if (v.vesselType != VesselType.SpaceObject) continue;
var asteroidPosition = Lib.VesselPosition(v);
double distance = Vector3d.Distance(vesselPosition, asteroidPosition);
if (distance < result) result = distance;
}
return result;
}
public static string ReqValueFormat(Require req, object reqValue)
{
if (reqValue == null)
return string.Empty;
switch (req)
{
case Require.OrbitMinEccentricity:
case Require.OrbitMaxEccentricity:
case Require.OrbitMinArgOfPeriapsis:
case Require.OrbitMaxArgOfPeriapsis:
case Require.AtmosphereAltMin:
case Require.AtmosphereAltMax:
return ((double)reqValue).ToString("F2");
case Require.SunAngleMin:
case Require.SunAngleMax:
case Require.OrbitMinInclination:
case Require.OrbitMaxInclination:
return Lib.HumanReadableAngle((double)reqValue);
case Require.TemperatureMin:
case Require.TemperatureMax:
return Lib.HumanReadableTemp((double)reqValue);
case Require.AltitudeMin:
case Require.AltitudeMax:
case Require.AltAboveGroundMin:
case Require.AltAboveGroundMax:
case Require.MaxAsteroidDistance:
return Lib.HumanReadableDistance((double)reqValue);
case Require.RadiationMin:
case Require.RadiationMax:
return Lib.HumanReadableRadiation((double)reqValue);
case Require.VolumePerCrewMin:
case Require.VolumePerCrewMax:
return Lib.HumanReadableVolume((double)reqValue);
case Require.SurfaceSpeedMin:
case Require.SurfaceSpeedMax:
case Require.VerticalSpeedMin:
case Require.VerticalSpeedMax:
case Require.SpeedMin:
case Require.SpeedMax:
return Lib.HumanReadableSpeed((double)reqValue);
case Require.DynamicPressureMin:
case Require.DynamicPressureMax:
case Require.StaticPressureMin:
case Require.StaticPressureMax:
case Require.AtmDensityMin:
case Require.AtmDensityMax:
return Lib.HumanReadablePressure((double)reqValue);
case Require.CrewMin:
case Require.CrewMax:
case Require.CrewCapacityMin:
case Require.CrewCapacityMax:
case Require.AstronautComplexLevelMin:
case Require.AstronautComplexLevelMax:
case Require.TrackingStationLevelMin:
case Require.TrackingStationLevelMax:
case Require.MissionControlLevelMin:
case Require.MissionControlLevelMax:
case Require.AdministrationLevelMin:
case Require.AdministrationLevelMax:
return ((int)reqValue).ToString();
case Require.Module:
return KSPUtil.PrintModuleName((string)reqValue);
case Require.Part:
return PartLoader.getPartInfoByName((string)reqValue)?.title ?? (string)reqValue;
case Require.Sunlight:
case Require.Shadow:
return ((double)reqValue).ToString("P2");
default:
return string.Empty;
}
}
public static string ReqName(Require req)
{
switch (req)
{
case Require.OrbitMinInclination: return Local.ExperimentReq_OrbitMinInclination;//"Min. inclination "
case Require.OrbitMaxInclination: return Local.ExperimentReq_OrbitMaxInclination;//"Max. inclination "
case Require.OrbitMinEccentricity: return Local.ExperimentReq_OrbitMinEccentricity;//"Min. eccentricity "
case Require.OrbitMaxEccentricity: return Local.ExperimentReq_OrbitMaxEccentricity;//"Max. eccentricity "
case Require.OrbitMinArgOfPeriapsis: return Local.ExperimentReq_OrbitMinArgOfPeriapsis;//"Min. argument of Pe "
case Require.OrbitMaxArgOfPeriapsis: return Local.ExperimentReq_OrbitMaxArgOfPeriapsis;//"Max. argument of Pe "
case Require.TemperatureMin: return Local.ExperimentReq_TemperatureMin;//"Min. temperature "
case Require.TemperatureMax: return Local.ExperimentReq_TemperatureMax;//"Max. temperature "
case Require.AltitudeMin: return Local.ExperimentReq_AltitudeMin;//"Min. altitude "
case Require.AltitudeMax: return Local.ExperimentReq_AltitudeMax;//"Max. altitude "
case Require.RadiationMin: return Local.ExperimentReq_RadiationMin;//"Min. radiation "
case Require.RadiationMax: return Local.ExperimentReq_RadiationMax;//"Max. radiation "
case Require.VolumePerCrewMin: return Local.ExperimentReq_VolumePerCrewMin;//"Min. vol./crew "
case Require.VolumePerCrewMax: return Local.ExperimentReq_VolumePerCrewMax;//"Max. vol./crew "
case Require.SunAngleMin: return Local.ExperimentReq_SunAngleMin;//"Min sun-surface angle"
case Require.SunAngleMax: return Local.ExperimentReq_SunAngleMax;//"Max sun-surface angle"
case Require.SurfaceSpeedMin: return Local.ExperimentReq_SurfaceSpeedMin;//"Min. surface speed "
case Require.SurfaceSpeedMax: return Local.ExperimentReq_SurfaceSpeedMax;//"Max. surface speed "
case Require.VerticalSpeedMin: return Local.ExperimentReq_VerticalSpeedMin;//"Min. vertical speed "
case Require.VerticalSpeedMax: return Local.ExperimentReq_VerticalSpeedMax;//"Max. vertical speed "
case Require.SpeedMin: return Local.ExperimentReq_SpeedMin;//"Min. speed "
case Require.SpeedMax: return Local.ExperimentReq_SpeedMax;//"Max. speed "
case Require.DynamicPressureMin: return Local.ExperimentReq_DynamicPressureMin;//"Min dynamic pressure"
case Require.DynamicPressureMax: return Local.ExperimentReq_DynamicPressureMax;//"Max dynamic pressure"
case Require.StaticPressureMin: return Local.ExperimentReq_StaticPressureMin;//"Min. pressure "
case Require.StaticPressureMax: return Local.ExperimentReq_StaticPressureMax;//"Max. pressure "
case Require.AtmDensityMin: return Local.ExperimentReq_AtmDensityMin;//"Min. atm. density "
case Require.AtmDensityMax: return Local.ExperimentReq_AtmDensityMax;//"Max. atm. density "
case Require.AltAboveGroundMin: return Local.ExperimentReq_AltAboveGroundMin;//"Min ground altitude"
case Require.AltAboveGroundMax: return Local.ExperimentReq_AltAboveGroundMax;//"Max ground altitude"
case Require.MaxAsteroidDistance: return Local.ExperimentReq_MaxAsteroidDistance;//"Max asteroid distance"
case Require.AtmosphereAltMin: return Local.ExperimentReq_AtmosphereAltMin;//"Min atmosphere altitude "
case Require.AtmosphereAltMax: return Local.ExperimentReq_AtmosphereAltMax;//"Max atmosphere altitude "
case Require.CrewMin: return Local.ExperimentReq_CrewMin;//"Min. crew "
case Require.CrewMax: return Local.ExperimentReq_CrewMax;//"Max. crew "
case Require.CrewCapacityMin: return Local.ExperimentReq_CrewCapacityMin;//"Min. crew capacity "
case Require.CrewCapacityMax: return Local.ExperimentReq_CrewCapacityMax;//"Max. crew capacity "
case Require.AstronautComplexLevelMin: return Local.ExperimentReq_AstronautComplexLevelMin;//"Astronaut Complex min level "
case Require.AstronautComplexLevelMax: return Local.ExperimentReq_AstronautComplexLevelMin;//"Astronaut Complex max level "
case Require.TrackingStationLevelMin: return Local.ExperimentReq_TrackingStationLevelMin;//"Tracking Station min level "
case Require.TrackingStationLevelMax: return Local.ExperimentReq_TrackingStationLevelMax;//"Tracking Station max level "
case Require.MissionControlLevelMin: return Local.ExperimentReq_MissionControlLevelMin;//"Mission Control min level "
case Require.MissionControlLevelMax: return Local.ExperimentReq_MissionControlLevelMax;//"Mission Control max level "
case Require.AdministrationLevelMin: return Local.ExperimentReq_AdministrationLevelMin;//"Administration min level "
case Require.AdministrationLevelMax: return Local.ExperimentReq_AdministrationLevelMax;//"Administration max level "
case Require.Part: return Local.ExperimentReq_Part;//"Need part "
case Require.Module: return Local.ExperimentReq_Module;//"Need module "
case Require.AbsoluteZero:
case Require.InnerBelt:
case Require.OuterBelt:
case Require.MagneticBelt:
case Require.Magnetosphere:
case Require.InterStellar:
case Require.Shadow:
case Require.Sunlight:
case Require.Greenhouse:
default:
return req.ToString();
}
}
}
}
| |
/*
* 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
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Security;
using System.Text.RegularExpressions;
using System.Threading;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Store;
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.Services;
using Apache.Ignite.Core.Transactions;
/// <summary>
/// Managed environment. Acts as a gateway for native code.
/// </summary>
internal static class ExceptionUtils
{
/** NoClassDefFoundError fully-qualified class name which is important during startup phase. */
private const string ClsNoClsDefFoundErr = "java.lang.NoClassDefFoundError";
/** NoSuchMethodError fully-qualified class name which is important during startup phase. */
private const string ClsNoSuchMthdErr = "java.lang.NoSuchMethodError";
/** InteropCachePartialUpdateException. */
private const string ClsCachePartialUpdateErr = "org.apache.ignite.internal.processors.platform.cache.PlatformCachePartialUpdateException";
/** Map with predefined exceptions. */
private static readonly IDictionary<string, ExceptionFactory> Exs = new Dictionary<string, ExceptionFactory>();
/** Inner class regex. */
private static readonly Regex InnerClassRegex = new Regex(@"class ([^\s]+): (.*)", RegexOptions.Compiled);
/// <summary>
/// Static initializer.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline",
Justification = "Readability")]
static ExceptionUtils()
{
// Common Java exceptions mapped to common .NET exceptions.
Exs["java.lang.IllegalArgumentException"] = (c, m, e, i) => new ArgumentException(m, e);
Exs["java.lang.IllegalStateException"] = (c, m, e, i) => new InvalidOperationException(m, e);
Exs["java.lang.UnsupportedOperationException"] = (c, m, e, i) => new NotSupportedException(m, e);
Exs["java.lang.InterruptedException"] = (c, m, e, i) => new ThreadInterruptedException(m, e);
Exs["java.lang.IllegalMonitorStateException"] = (c, m, e, i) => new SynchronizationLockException(m, e);
// Generic Ignite exceptions.
Exs["org.apache.ignite.IgniteException"] = (c, m, e, i) => new IgniteException(m, e);
Exs["org.apache.ignite.IgniteCheckedException"] = (c, m, e, i) => new IgniteException(m, e);
Exs["org.apache.ignite.IgniteIllegalStateException"] = (c, m, e, i) => new IgniteIllegalStateException(m, e);
Exs["org.apache.ignite.IgniteClientDisconnectedException"] = (c, m, e, i) => new ClientDisconnectedException(m, e, i.GetCluster().ClientReconnectTask);
Exs["org.apache.ignite.internal.IgniteClientDisconnectedCheckedException"] = (c, m, e, i) => new ClientDisconnectedException(m, e, i.GetCluster().ClientReconnectTask);
Exs["org.apache.ignite.binary.BinaryObjectException"] = (c, m, e, i) => new BinaryObjectException(m, e);
// Cluster exceptions.
Exs["org.apache.ignite.cluster.ClusterGroupEmptyException"] = (c, m, e, i) => new ClusterGroupEmptyException(m, e);
Exs["org.apache.ignite.internal.cluster.ClusterGroupEmptyCheckedException"] = (c, m, e, i) => new ClusterGroupEmptyException(m, e);
Exs["org.apache.ignite.cluster.ClusterTopologyException"] = (c, m, e, i) => new ClusterTopologyException(m, e);
// Compute exceptions.
Exs["org.apache.ignite.compute.ComputeExecutionRejectedException"] = (c, m, e, i) => new ComputeExecutionRejectedException(m, e);
Exs["org.apache.ignite.compute.ComputeJobFailoverException"] = (c, m, e, i) => new ComputeJobFailoverException(m, e);
Exs["org.apache.ignite.compute.ComputeTaskCancelledException"] = (c, m, e, i) => new ComputeTaskCancelledException(m, e);
Exs["org.apache.ignite.compute.ComputeTaskTimeoutException"] = (c, m, e, i) => new ComputeTaskTimeoutException(m, e);
Exs["org.apache.ignite.compute.ComputeUserUndeclaredException"] = (c, m, e, i) => new ComputeUserUndeclaredException(m, e);
// Cache exceptions.
Exs["javax.cache.CacheException"] = (c, m, e, i) => new CacheException(m, e);
Exs["javax.cache.integration.CacheLoaderException"] = (c, m, e, i) => new CacheStoreException(m, e);
Exs["javax.cache.integration.CacheWriterException"] = (c, m, e, i) => new CacheStoreException(m, e);
Exs["javax.cache.processor.EntryProcessorException"] = (c, m, e, i) => new CacheEntryProcessorException(m, e);
// Transaction exceptions.
Exs["org.apache.ignite.transactions.TransactionOptimisticException"] = (c, m, e, i) => new TransactionOptimisticException(m, e);
Exs["org.apache.ignite.internal.transactions.IgniteTxOptimisticCheckedException"] = (c, m, e, i) => new TransactionOptimisticException(m, e);
Exs["org.apache.ignite.transactions.TransactionTimeoutException"] = (c, m, e, i) => new TransactionTimeoutException(m, e);
Exs["org.apache.ignite.transactions.TransactionRollbackException"] = (c, m, e, i) => new TransactionRollbackException(m, e);
Exs["org.apache.ignite.transactions.TransactionHeuristicException"] = (c, m, e, i) => new TransactionHeuristicException(m, e);
Exs["org.apache.ignite.transactions.TransactionDeadlockException"] = (c, m, e, i) => new TransactionDeadlockException(m, e);
// Security exceptions.
Exs["org.apache.ignite.IgniteAuthenticationException"] = (c, m, e, i) => new SecurityException(m, e);
Exs["org.apache.ignite.plugin.security.GridSecurityException"] = (c, m, e, i) => new SecurityException(m, e);
// Future exceptions.
Exs["org.apache.ignite.lang.IgniteFutureCancelledException"] = (c, m, e, i) => new IgniteFutureCancelledException(m, e);
Exs["org.apache.ignite.internal.IgniteFutureCancelledCheckedException"] = (c, m, e, i) => new IgniteFutureCancelledException(m, e);
// Service exceptions.
Exs["org.apache.ignite.services.ServiceDeploymentException"] = (c, m, e, i) => new ServiceDeploymentException(m, e);
}
/// <summary>
/// Creates exception according to native code class and message.
/// </summary>
/// <param name="igniteInt">The ignite.</param>
/// <param name="clsName">Exception class name.</param>
/// <param name="msg">Exception message.</param>
/// <param name="stackTrace">Native stack trace.</param>
/// <param name="reader">Error data reader.</param>
/// <param name="innerException">Inner exception.</param>
/// <returns>Exception.</returns>
public static Exception GetException(IIgniteInternal igniteInt, string clsName, string msg, string stackTrace,
BinaryReader reader = null, Exception innerException = null)
{
// Set JavaException as immediate inner.
var jex = new JavaException(clsName, msg, stackTrace, innerException);
return GetException(igniteInt, jex, reader);
}
/// <summary>
/// Creates exception according to native code class and message.
/// </summary>
/// <param name="igniteInt">The ignite.</param>
/// <param name="innerException">Java exception.</param>
/// <param name="reader">Error data reader.</param>
/// <returns>Exception.</returns>
public static Exception GetException(IIgniteInternal igniteInt, JavaException innerException,
BinaryReader reader = null)
{
var ignite = igniteInt == null ? null : igniteInt.GetIgnite();
var msg = innerException.JavaMessage;
var clsName = innerException.JavaClassName;
ExceptionFactory ctor;
if (Exs.TryGetValue(clsName, out ctor))
{
var match = InnerClassRegex.Match(msg ?? string.Empty);
ExceptionFactory innerCtor;
if (match.Success && Exs.TryGetValue(match.Groups[1].Value, out innerCtor))
{
return ctor(clsName, msg,
innerCtor(match.Groups[1].Value, match.Groups[2].Value, innerException, ignite),
ignite);
}
return ctor(clsName, msg, innerException, ignite);
}
if (ClsNoClsDefFoundErr.Equals(clsName, StringComparison.OrdinalIgnoreCase))
return new IgniteException("Java class is not found (did you set IGNITE_HOME environment " +
"variable?): " + msg, innerException);
if (ClsNoSuchMthdErr.Equals(clsName, StringComparison.OrdinalIgnoreCase))
return new IgniteException("Java class method is not found (did you set IGNITE_HOME environment " +
"variable?): " + msg, innerException);
if (ClsCachePartialUpdateErr.Equals(clsName, StringComparison.OrdinalIgnoreCase))
return ProcessCachePartialUpdateException(igniteInt, msg, innerException.Message, reader);
// Predefined mapping not found - check plugins.
if (igniteInt != null && igniteInt.PluginProcessor != null)
{
ctor = igniteInt.PluginProcessor.GetExceptionMapping(clsName);
if (ctor != null)
{
return ctor(clsName, msg, innerException, ignite);
}
}
// Return default exception.
return new IgniteException(string.Format("Java exception occurred [class={0}, message={1}]", clsName, msg),
innerException);
}
/// <summary>
/// Process cache partial update exception.
/// </summary>
/// <param name="ignite">The ignite.</param>
/// <param name="msg">Message.</param>
/// <param name="stackTrace">Stack trace.</param>
/// <param name="reader">Reader.</param>
/// <returns>CachePartialUpdateException.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static Exception ProcessCachePartialUpdateException(IIgniteInternal ignite, string msg,
string stackTrace, BinaryReader reader)
{
if (reader == null)
return new CachePartialUpdateException(msg, new IgniteException("Failed keys are not available."));
bool dataExists = reader.ReadBoolean();
Debug.Assert(dataExists);
if (reader.ReadBoolean())
{
bool keepBinary = reader.ReadBoolean();
BinaryReader keysReader = reader.Marshaller.StartUnmarshal(reader.Stream, keepBinary);
try
{
return new CachePartialUpdateException(msg, ReadNullableList(keysReader));
}
catch (Exception e)
{
// Failed to deserialize data.
return new CachePartialUpdateException(msg, e);
}
}
// Was not able to write keys.
string innerErrCls = reader.ReadString();
string innerErrMsg = reader.ReadString();
Exception innerErr = GetException(ignite, innerErrCls, innerErrMsg, stackTrace);
return new CachePartialUpdateException(msg, innerErr);
}
/// <summary>
/// Create JVM initialization exception.
/// </summary>
/// <param name="clsName">Class name.</param>
/// <param name="msg">Message.</param>
/// <param name="stackTrace">Stack trace.</param>
/// <returns>Exception.</returns>
[ExcludeFromCodeCoverage] // Covered by a test in a separate process.
public static Exception GetJvmInitializeException(string clsName, string msg, string stackTrace)
{
if (clsName != null)
return new IgniteException("Failed to initialize JVM.", GetException(null, clsName, msg, stackTrace));
if (msg != null)
return new IgniteException("Failed to initialize JVM: " + msg + "\n" + stackTrace);
return new IgniteException("Failed to initialize JVM.");
}
/// <summary>
/// Reads nullable list.
/// </summary>
/// <param name="reader">Reader.</param>
/// <returns>List.</returns>
private static List<object> ReadNullableList(BinaryReader reader)
{
if (!reader.ReadBoolean())
return null;
var size = reader.ReadInt();
var list = new List<object>(size);
for (int i = 0; i < size; i++)
list.Add(reader.ReadObject<object>());
return list;
}
}
}
| |
namespace FakeItEasy.Tests.Core
{
using System;
using System.Diagnostics.CodeAnalysis;
using FakeItEasy.Core;
using FakeItEasy.Creation;
using NUnit.Framework;
[TestFixture]
public class DefaultFixtureInitializerTests
{
#pragma warning disable 649
[UnderTest]
private DefaultFixtureInitializer initializer;
[Fake]
private IFakeAndDummyManager fakeAndDummyManager;
[Fake]
private IFoo fakeReturnedFromFakeAndDummyManager;
[Fake]
private ISutInitializer sutInitializer;
#pragma warning restore 649
private FixtureType fixture;
[SetUp]
public void Setup()
{
this.OnSetup();
}
[Test]
public void Should_set_public_property_that_is_attributed()
{
// Arrange
// Act
this.initializer.InitializeFakes(this.fixture);
// Assert
Assert.That(this.fixture.FooProperty, Is.SameAs(this.fakeReturnedFromFakeAndDummyManager));
}
[Test]
public void Should_not_set_untagged_property()
{
// Arrange
// Act
this.initializer.InitializeFakes(this.fixture);
// Assert
Assert.That(this.fixture.NonFakedProperty, Is.Null);
}
[Test]
public void Should_set_private_property_that_is_tagged()
{
// Arrange
// Act
this.initializer.InitializeFakes(this.fixture);
// Assert
Assert.That(this.fixture.GetValueOfPrivateFakeProperty(), Is.SameAs(this.fakeReturnedFromFakeAndDummyManager));
}
[Test]
public void Should_set_private_field_that_is_tagged()
{
// Arrange
// Act
this.initializer.InitializeFakes(this.fixture);
// Assert
Assert.That(this.fixture.GetValueOfPrivateFakeField(), Is.SameAs(this.fakeReturnedFromFakeAndDummyManager));
}
[Test]
public void Should_set_public_field_that_is_tagged()
{
// Arrange
// Act
this.initializer.InitializeFakes(this.fixture);
// Assert
Assert.That(this.fixture.PublicFakeField, Is.SameAs(this.fakeReturnedFromFakeAndDummyManager));
}
[Test]
public void Should_not_set_non_tagged_field()
{
// Arrange
// Act
this.initializer.InitializeFakes(this.fixture);
// Assert
Assert.That(this.fixture.NonFakeField, Is.Null);
}
[Test]
public void Should_set_sut_from_sut_initializer()
{
// Arrange
var sut = A.Dummy<Sut>();
A.CallTo(() => this.sutInitializer.CreateSut(A<Type>._, A<Action<Type, object>>._))
.Returns(sut);
var sutFixture = new SutFixture();
// Act
this.initializer.InitializeFakes(sutFixture);
// Assert
Assert.That(sutFixture.Sut, Is.SameAs(sut));
}
[Test]
public void Should_set_fake_from_sut_initializer_callback_when_available()
{
// Arrange
var fake = A.Fake<IFoo>();
A.CallTo(() => this.sutInitializer.CreateSut(A<Type>._, A<Action<Type, object>>._))
.Invokes(x => x.GetArgument<Action<Type, object>>(1).Invoke(typeof(IFoo), fake));
var sutFixture = new SutFixture();
// Act
this.initializer.InitializeFakes(sutFixture);
// Assert
Assert.That(sutFixture.Foo, Is.SameAs(fake));
}
[Test]
public void Should_fail_when_more_than_one_member_is_marked_as_sut()
{
// Arrange
// Act
// Assert
Assert.That(
() => this.initializer.InitializeFakes(new SutFixtureWithTwoSutMembers()),
Throws.InstanceOf<InvalidOperationException>().With.Message.EqualTo("A fake fixture can only contain one member marked \"under test\"."));
}
protected virtual void OnSetup()
{
Fake.InitializeFixture(this);
A.CallTo(() => this.fakeAndDummyManager.CreateFake(typeof(IFoo), A<FakeOptions>._)).Returns(this.fakeReturnedFromFakeAndDummyManager);
this.fixture = new FixtureType();
}
public class Sut
{
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "foo", Justification = "Required for testing.")]
public Sut(IFoo foo)
{
}
}
public class SutFixture
{
[Fake]
public IFoo Foo { get; set; }
[UnderTest]
public Sut Sut { get; set; }
}
public class SutFixtureWithTwoSutMembers
{
[UnderTest]
public Sut Sut { get; set; }
[UnderTest]
public Sut Sut2 { get; set; }
}
public class FixtureType
{
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Required for testing.")]
[Fake]
public IFoo PublicFakeField;
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Required for testing.")]
public IFoo NonFakeField;
#pragma warning disable 649
[Fake]
private IFoo privateFakeField;
#pragma warning restore 649
[Fake]
public IFoo FooProperty { get; set; }
public IFoo NonFakedProperty { get; set; }
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required for testing.")]
[Fake]
private IFoo PriveFakeProperty { get; set; }
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Required for testing.")]
public IFoo GetValueOfPrivateFakeProperty()
{
return this.PriveFakeProperty;
}
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Required for testing.")]
public IFoo GetValueOfPrivateFakeField()
{
return this.privateFakeField;
}
}
}
}
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.27.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Google Apps Script Execution API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://developers.google.com/apps-script/execution/rest/v1/scripts/run'>Google Apps Script Execution API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20170712 (923)
* <tr><th>API Docs
* <td><a href='https://developers.google.com/apps-script/execution/rest/v1/scripts/run'>
* https://developers.google.com/apps-script/execution/rest/v1/scripts/run</a>
* <tr><th>Discovery Name<td>script
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Google Apps Script Execution API can be found at
* <a href='https://developers.google.com/apps-script/execution/rest/v1/scripts/run'>https://developers.google.com/apps-script/execution/rest/v1/scripts/run</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.Script.v1
{
/// <summary>The Script Service.</summary>
public class ScriptService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public ScriptService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public ScriptService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
scripts = new ScriptsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "script"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://script.googleapis.com/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return ""; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://script.googleapis.com/batch"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch"; }
}
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Google Apps Script Execution API.</summary>
public class Scope
{
/// <summary>Read, send, delete, and manage your email</summary>
public static string MailGoogleCom = "https://mail.google.com/";
/// <summary>Manage your calendars</summary>
public static string WwwGoogleComCalendarFeeds = "https://www.google.com/calendar/feeds";
/// <summary>Manage your contacts</summary>
public static string WwwGoogleComM8Feeds = "https://www.google.com/m8/feeds";
/// <summary>View and manage the provisioning of groups on your domain</summary>
public static string AdminDirectoryGroup = "https://www.googleapis.com/auth/admin.directory.group";
/// <summary>View and manage the provisioning of users on your domain</summary>
public static string AdminDirectoryUser = "https://www.googleapis.com/auth/admin.directory.user";
/// <summary>View and manage the files in your Google Drive</summary>
public static string Drive = "https://www.googleapis.com/auth/drive";
/// <summary>View and manage your forms in Google Drive</summary>
public static string Forms = "https://www.googleapis.com/auth/forms";
/// <summary>View and manage forms that this application has been installed in</summary>
public static string FormsCurrentonly = "https://www.googleapis.com/auth/forms.currentonly";
/// <summary>View and manage your Google Groups</summary>
public static string Groups = "https://www.googleapis.com/auth/groups";
/// <summary>View and manage your spreadsheets in Google Drive</summary>
public static string Spreadsheets = "https://www.googleapis.com/auth/spreadsheets";
/// <summary>View your email address</summary>
public static string UserinfoEmail = "https://www.googleapis.com/auth/userinfo.email";
}
private readonly ScriptsResource scripts;
/// <summary>Gets the Scripts resource.</summary>
public virtual ScriptsResource Scripts
{
get { return scripts; }
}
}
///<summary>A base abstract class for Script requests.</summary>
public abstract class ScriptBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new ScriptBaseServiceRequest instance.</summary>
protected ScriptBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto,
}
/// <summary>OAuth bearer token.</summary>
[Google.Apis.Util.RequestParameterAttribute("bearer_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string BearerToken { get; set; }
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Pretty-print response.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("pp", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> Pp { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes Script parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"bearer_token", new Google.Apis.Discovery.Parameter
{
Name = "bearer_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pp", new Google.Apis.Discovery.Parameter
{
Name = "pp",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "scripts" collection of methods.</summary>
public class ScriptsResource
{
private const string Resource = "scripts";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ScriptsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Runs a function in an Apps Script project. The project must be deployed for use with the Apps
/// Script Execution API.
///
/// This method requires authorization with an OAuth 2.0 token that includes at least one of the scopes listed
/// in the [Authorization](#authorization) section; script projects that do not require authorization cannot be
/// executed through this API. To find the correct scopes to include in the authentication token, open the
/// project in the script editor, then select **File > Project properties** and click the **Scopes**
/// tab.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="scriptId">The project key of the script to be executed. To find the project key, open the project in
/// the script editor and select **File > Project properties**.</param>
public virtual RunRequest Run(Google.Apis.Script.v1.Data.ExecutionRequest body, string scriptId)
{
return new RunRequest(service, body, scriptId);
}
/// <summary>Runs a function in an Apps Script project. The project must be deployed for use with the Apps
/// Script Execution API.
///
/// This method requires authorization with an OAuth 2.0 token that includes at least one of the scopes listed
/// in the [Authorization](#authorization) section; script projects that do not require authorization cannot be
/// executed through this API. To find the correct scopes to include in the authentication token, open the
/// project in the script editor, then select **File > Project properties** and click the **Scopes**
/// tab.</summary>
public class RunRequest : ScriptBaseServiceRequest<Google.Apis.Script.v1.Data.Operation>
{
/// <summary>Constructs a new Run request.</summary>
public RunRequest(Google.Apis.Services.IClientService service, Google.Apis.Script.v1.Data.ExecutionRequest body, string scriptId)
: base(service)
{
ScriptId = scriptId;
Body = body;
InitParameters();
}
/// <summary>The project key of the script to be executed. To find the project key, open the project in the
/// script editor and select **File > Project properties**.</summary>
[Google.Apis.Util.RequestParameterAttribute("scriptId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string ScriptId { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Script.v1.Data.ExecutionRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "run"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/scripts/{scriptId}:run"; }
}
/// <summary>Initializes Run parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"scriptId", new Google.Apis.Discovery.Parameter
{
Name = "scriptId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.Script.v1.Data
{
/// <summary>An object that provides information about the nature of an error in the Apps Script Execution API. If
/// an `run` call succeeds but the script function (or Apps Script itself) throws an exception, the response body's
/// `error` field contains a `Status` object. The `Status` object's `details` field contains an array with a single
/// one of these `ExecutionError` objects.</summary>
public class ExecutionError : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The error message thrown by Apps Script, usually localized into the user's language.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("errorMessage")]
public virtual string ErrorMessage { get; set; }
/// <summary>The error type, for example `TypeError` or `ReferenceError`. If the error type is unavailable, this
/// field is not included.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("errorType")]
public virtual string ErrorType { get; set; }
/// <summary>An array of objects that provide a stack trace through the script to show where the execution
/// failed, with the deepest call first.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("scriptStackTraceElements")]
public virtual System.Collections.Generic.IList<ScriptStackTraceElement> ScriptStackTraceElements { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A request to run the function in a script. The script is identified by the specified `script_id`.
/// Executing a function on a script returns results based on the implementation of the script.</summary>
public class ExecutionRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>If `true` and the user is an owner of the script, the script runs at the most recently saved
/// version rather than the version deployed for use with the Execution API. Optional; default is
/// `false`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("devMode")]
public virtual System.Nullable<bool> DevMode { get; set; }
/// <summary>The name of the function to execute in the given script. The name does not include parentheses or
/// parameters.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("function")]
public virtual string Function { get; set; }
/// <summary>The parameters to be passed to the function being executed. The object type for each parameter
/// should match the expected type in Apps Script. Parameters cannot be Apps Script-specific object types (such
/// as a `Document` or a `Calendar`); they can only be primitive types such as `string`, `number`, `array`,
/// `object`, or `boolean`. Optional.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parameters")]
public virtual System.Collections.Generic.IList<object> Parameters { get; set; }
/// <summary>For Android add-ons only. An ID that represents the user's current session in the Android app for
/// Google Docs or Sheets, included as extra data in the
/// [`Intent`](https://developer.android.com/guide/components/intents-filters.html) that launches the add-on.
/// When an Android add-on is run with a session state, it gains the privileges of a
/// [bound](https://developers.google.com/apps-script/guides/bound) script that is, it can access information
/// like the user's current cursor position (in Docs) or selected cell (in Sheets). To retrieve the state, call
/// `Intent.getStringExtra("com.google.android.apps.docs.addons.SessionState")`. Optional.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sessionState")]
public virtual string SessionState { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>An object that provides the return value of a function executed through the Apps Script Execution API.
/// If a `run` call succeeds and the script function returns successfully, the response body's `response` field
/// contains this `ExecutionResponse` object.</summary>
public class ExecutionResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The return value of the script function. The type matches the object type returned in Apps Script.
/// Functions called through the Execution API cannot return Apps Script-specific objects (such as a `Document`
/// or a `Calendar`); they can only return primitive types such as a `string`, `number`, `array`, `object`, or
/// `boolean`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("result")]
public virtual object Result { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A request to retrieve the results from a collection of requests, specified by the operation resource
/// names.</summary>
public class JoinAsyncRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>List of operation resource names that we want to join, as returned from a call to
/// RunAsync.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("names")]
public virtual System.Collections.Generic.IList<string> Names { get; set; }
/// <summary>The script id which specifies the script which all processes in the names field must be
/// from.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("scriptId")]
public virtual string ScriptId { get; set; }
/// <summary>Timeout for information retrieval in milliseconds.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("timeout")]
public virtual object Timeout { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>An object that provides the return value for the JoinAsync method.</summary>
public class JoinAsyncResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The return values for each script function, in a map of operation resource names to the Operation
/// containing the result of the process. The response will contain either an error or the result of the script
/// function.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("results")]
public virtual System.Collections.Generic.IDictionary<string,Operation> Results { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response will not arrive until the function finishes executing. The maximum runtime is listed in
/// the guide to [limitations in Apps Script](https://developers.google.com/apps-
/// script/guides/services/quotas#current_limitations). If the script function returns successfully, the `response`
/// field will contain an `ExecutionResponse` object with the function's return value in the object's `result`
/// field. If the script function (or Apps Script itself) throws an exception, the `error` field will contain a
/// `Status` object. The `Status` object's `details` field will contain an array with a single `ExecutionError`
/// object that provides information about the nature of the error. If the `run` call itself fails (for example,
/// because of a malformed request or an authorization error), the method will return an HTTP response code in the
/// 4XX range with a different format for the response body. Client libraries will automatically convert a 4XX
/// response into an exception class.</summary>
public class Operation : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>This field is not used.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("done")]
public virtual System.Nullable<bool> Done { get; set; }
/// <summary>If a `run` call succeeds but the script function (or Apps Script itself) throws an exception, this
/// field will contain a `Status` object. The `Status` object's `details` field will contain an array with a
/// single `ExecutionError` object that provides information about the nature of the error.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("error")]
public virtual Status Error { get; set; }
/// <summary>This field is not used.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual System.Collections.Generic.IDictionary<string,object> Metadata { get; set; }
/// <summary>This field is not used.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>If the script function returns successfully, this field will contain an `ExecutionResponse` object
/// with the function's return value as the object's `result` field.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("response")]
public virtual System.Collections.Generic.IDictionary<string,object> Response { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A stack trace through the script that shows where the execution failed.</summary>
public class ScriptStackTraceElement : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The name of the function that failed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("function")]
public virtual string Function { get; set; }
/// <summary>The line number where the script failed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("lineNumber")]
public virtual System.Nullable<int> LineNumber { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>If a `run` call succeeds but the script function (or Apps Script itself) throws an exception, the
/// response body's `error` field will contain this `Status` object.</summary>
public class Status : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The status code. For this API, this value will always be 3, corresponding to an INVALID_ARGUMENT
/// error.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual System.Nullable<int> Code { get; set; }
/// <summary>An array that contains a single `ExecutionError` object that provides information about the nature
/// of the error.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("details")]
public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string,object>> Details { get; set; }
/// <summary>A developer-facing error message, which is in English. Any user-facing error message is localized
/// and sent in the [`google.rpc.Status.details`](google.rpc.Status.details) field, or localized by the
/// client.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("message")]
public virtual string Message { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
namespace System.Runtime.Serialization
{
using System;
using System.Collections;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using System.Reflection;
using System.Threading;
using System.Xml;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
using System.Security;
using System.Linq;
#if USE_REFEMIT
public sealed class ClassDataContract : DataContract
#else
internal sealed class ClassDataContract : DataContract
#endif
{
/// <SecurityNote>
/// Review - XmlDictionaryString(s) representing the XML namespaces for class members.
/// statically cached and used from IL generated code. should ideally be Critical.
/// marked SecurityRequiresReview to be callable from transparent IL generated code.
/// not changed to property to avoid regressing performance; any changes to initalization should be reviewed.
/// </SecurityNote>
public XmlDictionaryString[] ContractNamespaces;
/// <SecurityNote>
/// Review - XmlDictionaryString(s) representing the XML element names for class members.
/// statically cached and used from IL generated code. should ideally be Critical.
/// marked SecurityRequiresReview to be callable from transparent IL generated code.
/// not changed to property to avoid regressing performance; any changes to initalization should be reviewed.
/// </SecurityNote>
public XmlDictionaryString[] MemberNames;
/// <SecurityNote>
/// Review - XmlDictionaryString(s) representing the XML namespaces for class members.
/// statically cached and used when calling IL generated code. should ideally be Critical.
/// marked SecurityRequiresReview to be callable from transparent code.
/// not changed to property to avoid regressing performance; any changes to initalization should be reviewed.
/// </SecurityNote>
public XmlDictionaryString[] MemberNamespaces;
[SecurityCritical]
/// <SecurityNote>
/// Critical - XmlDictionaryString representing the XML namespaces for members of class.
/// statically cached and used from IL generated code.
/// </SecurityNote>
private XmlDictionaryString[] _childElementNamespaces;
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds instance of CriticalHelper which keeps state that is cached statically for serialization.
/// Static fields are marked SecurityCritical or readonly to prevent
/// data from being modified or leaked to other components in appdomain.
/// </SecurityNote>
private ClassDataContractCriticalHelper _helper;
private bool _isScriptObject;
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
[SecuritySafeCritical]
internal ClassDataContract(Type type) : base(new ClassDataContractCriticalHelper(type))
{
InitClassDataContract();
}
[SecuritySafeCritical]
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
private ClassDataContract(Type type, XmlDictionaryString ns, string[] memberNames) : base(new ClassDataContractCriticalHelper(type, ns, memberNames))
{
InitClassDataContract();
}
[SecurityCritical]
/// <SecurityNote>
/// Critical - initializes SecurityCritical fields; called from all constructors
/// </SecurityNote>
private void InitClassDataContract()
{
_helper = base.Helper as ClassDataContractCriticalHelper;
this.ContractNamespaces = _helper.ContractNamespaces;
this.MemberNames = _helper.MemberNames;
this.MemberNamespaces = _helper.MemberNamespaces;
_isScriptObject = _helper.IsScriptObject;
}
internal ClassDataContract BaseContract
{
/// <SecurityNote>
/// Critical - fetches the critical baseContract property
/// Safe - baseContract only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.BaseContract; }
}
internal List<DataMember> Members
{
/// <SecurityNote>
/// Critical - fetches the critical members property
/// Safe - members only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.Members; }
}
public XmlDictionaryString[] ChildElementNamespaces
{
/// <SecurityNote>
/// Critical - fetches the critical childElementNamespaces property
/// Safe - childElementNamespaces only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_childElementNamespaces == null)
{
lock (this)
{
if (_childElementNamespaces == null)
{
if (_helper.ChildElementNamespaces == null)
{
XmlDictionaryString[] tempChildElementamespaces = CreateChildElementNamespaces();
Interlocked.MemoryBarrier();
_helper.ChildElementNamespaces = tempChildElementamespaces;
}
_childElementNamespaces = _helper.ChildElementNamespaces;
}
}
}
return _childElementNamespaces;
}
}
internal MethodInfo OnSerializing
{
/// <SecurityNote>
/// Critical - fetches the critical onSerializing property
/// Safe - onSerializing only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.OnSerializing; }
}
internal MethodInfo OnSerialized
{
/// <SecurityNote>
/// Critical - fetches the critical onSerialized property
/// Safe - onSerialized only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.OnSerialized; }
}
internal MethodInfo OnDeserializing
{
/// <SecurityNote>
/// Critical - fetches the critical onDeserializing property
/// Safe - onDeserializing only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.OnDeserializing; }
}
internal MethodInfo OnDeserialized
{
/// <SecurityNote>
/// Critical - fetches the critical onDeserialized property
/// Safe - onDeserialized only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.OnDeserialized; }
}
internal override DataContractDictionary KnownDataContracts
{
/// <SecurityNote>
/// Critical - fetches the critical knownDataContracts property
/// Safe - knownDataContracts only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.KnownDataContracts; }
}
internal bool IsNonAttributedType
{
/// <SecurityNote>
/// Critical - fetches the critical IsNonAttributedType property
/// Safe - IsNonAttributedType only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.IsNonAttributedType; }
}
internal bool IsKeyValuePairAdapter
{
[SecuritySafeCritical]
get
{ return _helper.IsKeyValuePairAdapter; }
}
internal Type[] KeyValuePairGenericArguments
{
[SecuritySafeCritical]
get
{ return _helper.KeyValuePairGenericArguments; }
}
internal ConstructorInfo KeyValuePairAdapterConstructorInfo
{
[SecuritySafeCritical]
get
{ return _helper.KeyValuePairAdapterConstructorInfo; }
}
internal MethodInfo GetKeyValuePairMethodInfo
{
[SecuritySafeCritical]
get
{ return _helper.GetKeyValuePairMethodInfo; }
}
/// <SecurityNote>
/// Critical - fetches information about which constructor should be used to initialize non-attributed types that are valid for serialization
/// Safe - only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
internal ConstructorInfo GetNonAttributedTypeConstructor()
{
return _helper.GetNonAttributedTypeConstructor();
}
internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate
{
/// <SecurityNote>
/// Critical - fetches the critical xmlFormatWriterDelegate property
/// Safe - xmlFormatWriterDelegate only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_helper.XmlFormatWriterDelegate == null)
{
lock (this)
{
if (_helper.XmlFormatWriterDelegate == null)
{
XmlFormatClassWriterDelegate tempDelegate = new XmlFormatWriterGenerator().GenerateClassWriter(this);
Interlocked.MemoryBarrier();
_helper.XmlFormatWriterDelegate = tempDelegate;
}
}
}
return _helper.XmlFormatWriterDelegate;
}
}
internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate
{
/// <SecurityNote>
/// Critical - fetches the critical xmlFormatReaderDelegate property
/// Safe - xmlFormatReaderDelegate only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_helper.XmlFormatReaderDelegate == null)
{
lock (this)
{
if (_helper.XmlFormatReaderDelegate == null)
{
XmlFormatClassReaderDelegate tempDelegate = new XmlFormatReaderGenerator().GenerateClassReader(this);
Interlocked.MemoryBarrier();
_helper.XmlFormatReaderDelegate = tempDelegate;
}
}
}
return _helper.XmlFormatReaderDelegate;
}
}
internal static ClassDataContract CreateClassDataContractForKeyValue(Type type, XmlDictionaryString ns, string[] memberNames)
{
return new ClassDataContract(type, ns, memberNames);
}
internal static void CheckAndAddMember(List<DataMember> members, DataMember memberContract, Dictionary<string, DataMember> memberNamesTable)
{
DataMember existingMemberContract;
if (memberNamesTable.TryGetValue(memberContract.Name, out existingMemberContract))
{
Type declaringType = memberContract.MemberInfo.DeclaringType;
DataContract.ThrowInvalidDataContractException(
SR.Format((declaringType.GetTypeInfo().IsEnum ? SR.DupEnumMemberValue : SR.DupMemberName),
existingMemberContract.MemberInfo.Name,
memberContract.MemberInfo.Name,
DataContract.GetClrTypeFullName(declaringType),
memberContract.Name),
declaringType);
}
memberNamesTable.Add(memberContract.Name, memberContract);
members.Add(memberContract);
}
internal static XmlDictionaryString GetChildNamespaceToDeclare(DataContract dataContract, Type childType, XmlDictionary dictionary)
{
childType = DataContract.UnwrapNullableType(childType);
if (!childType.GetTypeInfo().IsEnum && !Globals.TypeOfIXmlSerializable.IsAssignableFrom(childType)
&& DataContract.GetBuiltInDataContract(childType) == null && childType != Globals.TypeOfDBNull)
{
string ns = DataContract.GetStableName(childType).Namespace;
if (ns.Length > 0 && ns != dataContract.Namespace.Value)
return dictionary.Add(ns);
}
return null;
}
private static bool IsArraySegment(Type t)
{
return t.GetTypeInfo().IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>));
}
/// <SecurityNote>
/// RequiresReview - callers may need to depend on isNonAttributedType for a security decision
/// isNonAttributedType must be calculated correctly
/// IsNonAttributedTypeValidForSerialization is used as part of the isNonAttributedType calculation and
/// is therefore marked SRR
/// Safe - does not let caller influence isNonAttributedType calculation; no harm in leaking value
/// </SecurityNote>
static internal bool IsNonAttributedTypeValidForSerialization(Type type)
{
if (type.IsArray)
return false;
if (type.GetTypeInfo().IsEnum)
return false;
if (type.IsGenericParameter)
return false;
if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type))
return false;
if (type.IsPointer)
return false;
if (type.GetTypeInfo().IsDefined(Globals.TypeOfCollectionDataContractAttribute, false))
return false;
Type[] interfaceTypes = type.GetInterfaces();
if (!IsArraySegment(type))
{
foreach (Type interfaceType in interfaceTypes)
{
if (CollectionDataContract.IsCollectionInterface(interfaceType))
return false;
}
}
if (type.GetTypeInfo().IsDefined(Globals.TypeOfDataContractAttribute, false))
return false;
if (type.GetTypeInfo().IsValueType)
{
return type.GetTypeInfo().IsVisible;
}
else
{
return (type.GetTypeInfo().IsVisible &&
type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>()) != null);
}
}
private static string[] s_knownSerializableTypeNames = new string[] {
"System.Tuple`1",
"System.Tuple`2",
"System.Tuple`3",
"System.Tuple`4",
"System.Tuple`5",
"System.Tuple`6",
"System.Tuple`7",
"System.Tuple`8",
"System.Collections.Generic.Queue`1",
"System.Version"
};
internal static bool IsKnownSerializableType(Type type)
{
// Applies to known types that DCS understands how to serialize/deserialize
//
// Ajdust for generic type
if (type.GetTypeInfo().IsGenericType && !type.GetTypeInfo().IsGenericTypeDefinition)
{
type = type.GetGenericTypeDefinition();
}
// Check for known types
if (Enumerable.Contains(s_knownSerializableTypeNames, type.FullName))
{
return true;
}
//Enable ClassDataContract to give support to Exceptions.
if (Globals.TypeOfException.IsAssignableFrom(type))
return true;
return false;
}
private XmlDictionaryString[] CreateChildElementNamespaces()
{
if (Members == null)
return null;
XmlDictionaryString[] baseChildElementNamespaces = null;
if (this.BaseContract != null)
baseChildElementNamespaces = this.BaseContract.ChildElementNamespaces;
int baseChildElementNamespaceCount = (baseChildElementNamespaces != null) ? baseChildElementNamespaces.Length : 0;
XmlDictionaryString[] childElementNamespaces = new XmlDictionaryString[Members.Count + baseChildElementNamespaceCount];
if (baseChildElementNamespaceCount > 0)
Array.Copy(baseChildElementNamespaces, 0, childElementNamespaces, 0, baseChildElementNamespaces.Length);
XmlDictionary dictionary = new XmlDictionary();
for (int i = 0; i < this.Members.Count; i++)
{
childElementNamespaces[i + baseChildElementNamespaceCount] = GetChildNamespaceToDeclare(this, this.Members[i].MemberType, dictionary);
}
return childElementNamespaces;
}
[SecuritySafeCritical]
/// <SecurityNote>
/// Critical - calls critical method on helper
/// Safe - doesn't leak anything
/// </SecurityNote>
private void EnsureMethodsImported()
{
_helper.EnsureMethodsImported();
}
public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
if (_isScriptObject)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType))));
}
XmlFormatWriterDelegate(xmlWriter, obj, context, this);
}
public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
{
if (_isScriptObject)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType))));
}
xmlReader.Read();
object o = XmlFormatReaderDelegate(xmlReader, context, MemberNames, MemberNamespaces);
xmlReader.ReadEndElement();
return o;
}
/// <SecurityNote>
/// Review - calculates whether this class requires MemberAccessPermission for deserialization.
/// since this information is used to determine whether to give the generated code access
/// permissions to private members, any changes to the logic should be reviewed.
/// </SecurityNote>
internal bool RequiresMemberAccessForRead(SecurityException securityException, string[] serializationAssemblyPatterns)
{
EnsureMethodsImported();
if (!IsTypeVisible(UnderlyingType, serializationAssemblyPatterns))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractTypeNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (this.BaseContract != null && this.BaseContract.RequiresMemberAccessForRead(securityException, serializationAssemblyPatterns))
return true;
if (ConstructorRequiresMemberAccess(GetNonAttributedTypeConstructor(), serializationAssemblyPatterns))
{
if (Globals.TypeOfScriptObject_IsAssignableFrom(UnderlyingType))
{
return true;
}
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustNonAttributedSerializableTypeNoPublicConstructor,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (MethodRequiresMemberAccess(this.OnDeserializing, serializationAssemblyPatterns))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractOnDeserializingNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.OnDeserializing.Name),
securityException));
}
return true;
}
if (MethodRequiresMemberAccess(this.OnDeserialized, serializationAssemblyPatterns))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractOnDeserializedNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.OnDeserialized.Name),
securityException));
}
return true;
}
if (this.Members != null)
{
for (int i = 0; i < this.Members.Count; i++)
{
if (this.Members[i].RequiresMemberAccessForSet(serializationAssemblyPatterns))
{
if (securityException != null)
{
if (this.Members[i].MemberInfo is FieldInfo)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractFieldSetNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.Members[i].MemberInfo.Name),
securityException));
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractPropertySetNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.Members[i].MemberInfo.Name),
securityException));
}
}
return true;
}
}
}
return false;
}
/// <SecurityNote>
/// Review - calculates whether this class requires MemberAccessPermission for serialization.
/// since this information is used to determine whether to give the generated code access
/// permissions to private members, any changes to the logic should be reviewed.
/// </SecurityNote>
internal bool RequiresMemberAccessForWrite(SecurityException securityException, string[] serializationAssemblyPatterns)
{
EnsureMethodsImported();
if (!IsTypeVisible(UnderlyingType, serializationAssemblyPatterns))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractTypeNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (this.BaseContract != null && this.BaseContract.RequiresMemberAccessForWrite(securityException, serializationAssemblyPatterns))
return true;
if (MethodRequiresMemberAccess(this.OnSerializing, serializationAssemblyPatterns))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractOnSerializingNotPublic,
DataContract.GetClrTypeFullName(this.UnderlyingType),
this.OnSerializing.Name),
securityException));
}
return true;
}
if (MethodRequiresMemberAccess(this.OnSerialized, serializationAssemblyPatterns))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractOnSerializedNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.OnSerialized.Name),
securityException));
}
return true;
}
if (this.Members != null)
{
for (int i = 0; i < this.Members.Count; i++)
{
if (this.Members[i].RequiresMemberAccessForGet(serializationAssemblyPatterns))
{
if (securityException != null)
{
if (this.Members[i].MemberInfo is FieldInfo)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractFieldGetNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.Members[i].MemberInfo.Name),
securityException));
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractPropertyGetNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.Members[i].MemberInfo.Name),
securityException));
}
}
return true;
}
}
}
return false;
}
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds all state used for (de)serializing classes.
/// since the data is cached statically, we lock down access to it.
/// </SecurityNote>
private class ClassDataContractCriticalHelper : DataContract.DataContractCriticalHelper
{
private ClassDataContract _baseContract;
private List<DataMember> _members;
private MethodInfo _onSerializing, _onSerialized;
private MethodInfo _onDeserializing, _onDeserialized;
private DataContractDictionary _knownDataContracts;
private bool _isKnownTypeAttributeChecked;
private bool _isMethodChecked;
/// <SecurityNote>
/// in serialization/deserialization we base the decision whether to Demand SerializationFormatter permission on this value and hasDataContract
/// </SecurityNote>
private bool _isNonAttributedType;
/// <SecurityNote>
/// in serialization/deserialization we base the decision whether to Demand SerializationFormatter permission on this value and isNonAttributedType
/// </SecurityNote>
private bool _hasDataContract;
private bool _isScriptObject;
private XmlDictionaryString[] _childElementNamespaces;
private XmlFormatClassReaderDelegate _xmlFormatReaderDelegate;
private XmlFormatClassWriterDelegate _xmlFormatWriterDelegate;
public XmlDictionaryString[] ContractNamespaces;
public XmlDictionaryString[] MemberNames;
public XmlDictionaryString[] MemberNamespaces;
internal ClassDataContractCriticalHelper() : base()
{
}
internal ClassDataContractCriticalHelper(Type type) : base(type)
{
XmlQualifiedName stableName = GetStableNameAndSetHasDataContract(type);
if (type == Globals.TypeOfDBNull)
{
this.StableName = stableName;
_members = new List<DataMember>();
XmlDictionary dictionary = new XmlDictionary(2);
this.Name = dictionary.Add(StableName.Name);
this.Namespace = dictionary.Add(StableName.Namespace);
this.ContractNamespaces = this.MemberNames = this.MemberNamespaces = Array.Empty<XmlDictionaryString>();
EnsureMethodsImported();
return;
}
Type baseType = type.GetTypeInfo().BaseType;
SetIsNonAttributedType(type);
SetKeyValuePairAdapterFlags(type);
this.IsValueType = type.GetTypeInfo().IsValueType;
if (baseType != null && baseType != Globals.TypeOfObject && baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri)
{
DataContract baseContract = DataContract.GetDataContract(baseType);
if (baseContract is CollectionDataContract)
this.BaseContract = ((CollectionDataContract)baseContract).SharedTypeContract as ClassDataContract;
else
this.BaseContract = baseContract as ClassDataContract;
if (this.BaseContract != null && this.BaseContract.IsNonAttributedType && !_isNonAttributedType)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError
(new InvalidDataContractException(SR.Format(SR.AttributedTypesCannotInheritFromNonAttributedSerializableTypes,
DataContract.GetClrTypeFullName(type), DataContract.GetClrTypeFullName(baseType))));
}
}
else
this.BaseContract = null;
{
this.StableName = stableName;
ImportDataMembers();
XmlDictionary dictionary = new XmlDictionary(2 + Members.Count);
Name = dictionary.Add(StableName.Name);
Namespace = dictionary.Add(StableName.Namespace);
int baseMemberCount = 0;
int baseContractCount = 0;
if (BaseContract == null)
{
MemberNames = new XmlDictionaryString[Members.Count];
MemberNamespaces = new XmlDictionaryString[Members.Count];
ContractNamespaces = new XmlDictionaryString[1];
}
else
{
baseMemberCount = BaseContract.MemberNames.Length;
MemberNames = new XmlDictionaryString[Members.Count + baseMemberCount];
Array.Copy(BaseContract.MemberNames, MemberNames, baseMemberCount);
MemberNamespaces = new XmlDictionaryString[Members.Count + baseMemberCount];
Array.Copy(BaseContract.MemberNamespaces, MemberNamespaces, baseMemberCount);
baseContractCount = BaseContract.ContractNamespaces.Length;
ContractNamespaces = new XmlDictionaryString[1 + baseContractCount];
Array.Copy(BaseContract.ContractNamespaces, ContractNamespaces, baseContractCount);
}
ContractNamespaces[baseContractCount] = Namespace;
for (int i = 0; i < Members.Count; i++)
{
MemberNames[i + baseMemberCount] = dictionary.Add(Members[i].Name);
MemberNamespaces[i + baseMemberCount] = Namespace;
}
}
EnsureMethodsImported();
_isScriptObject = this.IsNonAttributedType &&
Globals.TypeOfScriptObject_IsAssignableFrom(this.UnderlyingType);
}
internal ClassDataContractCriticalHelper(Type type, XmlDictionaryString ns, string[] memberNames) : base(type)
{
this.StableName = new XmlQualifiedName(GetStableNameAndSetHasDataContract(type).Name, ns.Value);
ImportDataMembers();
XmlDictionary dictionary = new XmlDictionary(1 + Members.Count);
Name = dictionary.Add(StableName.Name);
Namespace = ns;
ContractNamespaces = new XmlDictionaryString[] { Namespace };
MemberNames = new XmlDictionaryString[Members.Count];
MemberNamespaces = new XmlDictionaryString[Members.Count];
for (int i = 0; i < Members.Count; i++)
{
Members[i].Name = memberNames[i];
MemberNames[i] = dictionary.Add(Members[i].Name);
MemberNamespaces[i] = Namespace;
}
EnsureMethodsImported();
}
private void EnsureIsReferenceImported(Type type)
{
DataContractAttribute dataContractAttribute;
bool isReference = false;
bool hasDataContractAttribute = TryGetDCAttribute(type, out dataContractAttribute);
if (BaseContract != null)
{
if (hasDataContractAttribute && dataContractAttribute.IsReferenceSetExplicitly)
{
bool baseIsReference = this.BaseContract.IsReference;
if ((baseIsReference && !dataContractAttribute.IsReference) ||
(!baseIsReference && dataContractAttribute.IsReference))
{
DataContract.ThrowInvalidDataContractException(
SR.Format(SR.InconsistentIsReference,
DataContract.GetClrTypeFullName(type),
dataContractAttribute.IsReference,
DataContract.GetClrTypeFullName(this.BaseContract.UnderlyingType),
this.BaseContract.IsReference),
type);
}
else
{
isReference = dataContractAttribute.IsReference;
}
}
else
{
isReference = this.BaseContract.IsReference;
}
}
else if (hasDataContractAttribute)
{
if (dataContractAttribute.IsReference)
isReference = dataContractAttribute.IsReference;
}
if (isReference && type.GetTypeInfo().IsValueType)
{
DataContract.ThrowInvalidDataContractException(
SR.Format(SR.ValueTypeCannotHaveIsReference,
DataContract.GetClrTypeFullName(type),
true,
false),
type);
return;
}
this.IsReference = isReference;
}
private void ImportDataMembers()
{
Type type = this.UnderlyingType;
EnsureIsReferenceImported(type);
List<DataMember> tempMembers = new List<DataMember>();
Dictionary<string, DataMember> memberNamesTable = new Dictionary<string, DataMember>();
MemberInfo[] memberInfos;
bool isPodSerializable = !_isNonAttributedType || IsKnownSerializableType(type);
if (!isPodSerializable)
{
memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);
}
else
{
memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
}
for (int i = 0; i < memberInfos.Length; i++)
{
MemberInfo member = memberInfos[i];
if (HasDataContract)
{
object[] memberAttributes = member.GetCustomAttributes(typeof(DataMemberAttribute), false).ToArray();
if (memberAttributes != null && memberAttributes.Length > 0)
{
if (memberAttributes.Length > 1)
ThrowInvalidDataContractException(SR.Format(SR.TooManyDataMembers, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name));
DataMember memberContract = new DataMember(member);
if (member is PropertyInfo)
{
PropertyInfo property = (PropertyInfo)member;
MethodInfo getMethod = property.GetMethod;
if (getMethod != null && IsMethodOverriding(getMethod))
continue;
MethodInfo setMethod = property.SetMethod;
if (setMethod != null && IsMethodOverriding(setMethod))
continue;
if (getMethod == null)
ThrowInvalidDataContractException(SR.Format(SR.NoGetMethodForProperty, property.DeclaringType, property.Name));
if (setMethod == null)
{
if (!SetIfGetOnlyCollection(memberContract))
{
ThrowInvalidDataContractException(SR.Format(SR.NoSetMethodForProperty, property.DeclaringType, property.Name));
}
}
if (getMethod.GetParameters().Length > 0)
ThrowInvalidDataContractException(SR.Format(SR.IndexedPropertyCannotBeSerialized, property.DeclaringType, property.Name));
}
else if (!(member is FieldInfo))
ThrowInvalidDataContractException(SR.Format(SR.InvalidMember, DataContract.GetClrTypeFullName(type), member.Name));
DataMemberAttribute memberAttribute = (DataMemberAttribute)memberAttributes[0];
if (memberAttribute.IsNameSetExplicitly)
{
if (memberAttribute.Name == null || memberAttribute.Name.Length == 0)
ThrowInvalidDataContractException(SR.Format(SR.InvalidDataMemberName, member.Name, DataContract.GetClrTypeFullName(type)));
memberContract.Name = memberAttribute.Name;
}
else
memberContract.Name = member.Name;
memberContract.Name = DataContract.EncodeLocalName(memberContract.Name);
memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType);
memberContract.IsRequired = memberAttribute.IsRequired;
if (memberAttribute.IsRequired && this.IsReference)
{
ThrowInvalidDataContractException(
SR.Format(SR.IsRequiredDataMemberOnIsReferenceDataContractType,
DataContract.GetClrTypeFullName(member.DeclaringType),
member.Name, true), type);
}
memberContract.EmitDefaultValue = memberAttribute.EmitDefaultValue;
memberContract.Order = memberAttribute.Order;
CheckAndAddMember(tempMembers, memberContract, memberNamesTable);
}
}
else if (!isPodSerializable)
{
FieldInfo field = member as FieldInfo;
PropertyInfo property = member as PropertyInfo;
if ((field == null && property == null) || (field != null && field.IsInitOnly))
continue;
object[] memberAttributes = member.GetCustomAttributes(typeof(IgnoreDataMemberAttribute), false).ToArray();
if (memberAttributes != null && memberAttributes.Length > 0)
{
if (memberAttributes.Length > 1)
ThrowInvalidDataContractException(SR.Format(SR.TooManyIgnoreDataMemberAttributes, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name));
else
continue;
}
DataMember memberContract = new DataMember(member);
if (property != null)
{
MethodInfo getMethod = property.GetMethod;
if (getMethod == null || IsMethodOverriding(getMethod) || getMethod.GetParameters().Length > 0)
continue;
MethodInfo setMethod = property.SetMethod;
if (setMethod == null)
{
if (!SetIfGetOnlyCollection(memberContract))
continue;
}
else
{
if (!setMethod.IsPublic || IsMethodOverriding(setMethod))
continue;
}
}
memberContract.Name = DataContract.EncodeLocalName(member.Name);
memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType);
CheckAndAddMember(tempMembers, memberContract, memberNamesTable);
}
else
{
// [Serializible] and [NonSerialized] are deprecated on FxCore
// Try to mimic the behavior by allowing certain known types to go through
// POD types are fine also
FieldInfo field = member as FieldInfo;
if (CanSerializeMember(field))
{
DataMember memberContract = new DataMember(member);
memberContract.Name = DataContract.EncodeLocalName(member.Name);
object[] optionalFields = null;
if (optionalFields == null || optionalFields.Length == 0)
{
if (this.IsReference)
{
ThrowInvalidDataContractException(
SR.Format(SR.NonOptionalFieldMemberOnIsReferenceSerializableType,
DataContract.GetClrTypeFullName(member.DeclaringType),
member.Name, true), type);
}
memberContract.IsRequired = true;
}
memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType);
CheckAndAddMember(tempMembers, memberContract, memberNamesTable);
}
}
}
if (tempMembers.Count > 1)
tempMembers.Sort(DataMemberComparer.Singleton);
SetIfMembersHaveConflict(tempMembers);
Interlocked.MemoryBarrier();
_members = tempMembers;
}
private static bool CanSerializeMember(FieldInfo field)
{
return field != null &&
field.FieldType != Globals.TypeOfObject; // Don't really know how to serialize plain System.Object instance
}
private bool SetIfGetOnlyCollection(DataMember memberContract)
{
//OK to call IsCollection here since the use of surrogated collection types is not supported in get-only scenarios
if (CollectionDataContract.IsCollection(memberContract.MemberType, false /*isConstructorRequired*/) && !memberContract.MemberType.GetTypeInfo().IsValueType)
{
memberContract.IsGetOnlyCollection = true;
return true;
}
return false;
}
private void SetIfMembersHaveConflict(List<DataMember> members)
{
if (BaseContract == null)
return;
int baseTypeIndex = 0;
List<Member> membersInHierarchy = new List<Member>();
foreach (DataMember member in members)
{
membersInHierarchy.Add(new Member(member, this.StableName.Namespace, baseTypeIndex));
}
ClassDataContract currContract = BaseContract;
while (currContract != null)
{
baseTypeIndex++;
foreach (DataMember member in currContract.Members)
{
membersInHierarchy.Add(new Member(member, currContract.StableName.Namespace, baseTypeIndex));
}
currContract = currContract.BaseContract;
}
IComparer<Member> comparer = DataMemberConflictComparer.Singleton;
membersInHierarchy.Sort(comparer);
for (int i = 0; i < membersInHierarchy.Count - 1; i++)
{
int startIndex = i;
int endIndex = i;
bool hasConflictingType = false;
while (endIndex < membersInHierarchy.Count - 1
&& String.CompareOrdinal(membersInHierarchy[endIndex].member.Name, membersInHierarchy[endIndex + 1].member.Name) == 0
&& String.CompareOrdinal(membersInHierarchy[endIndex].ns, membersInHierarchy[endIndex + 1].ns) == 0)
{
membersInHierarchy[endIndex].member.ConflictingMember = membersInHierarchy[endIndex + 1].member;
if (!hasConflictingType)
{
if (membersInHierarchy[endIndex + 1].member.HasConflictingNameAndType)
{
hasConflictingType = true;
}
else
{
hasConflictingType = (membersInHierarchy[endIndex].member.MemberType != membersInHierarchy[endIndex + 1].member.MemberType);
}
}
endIndex++;
}
if (hasConflictingType)
{
for (int j = startIndex; j <= endIndex; j++)
{
membersInHierarchy[j].member.HasConflictingNameAndType = true;
}
}
i = endIndex + 1;
}
}
/// <SecurityNote>
/// Critical - sets the critical hasDataContract field
/// Safe - uses a trusted critical API (DataContract.GetStableName) to calculate the value
/// does not accept the value from the caller
/// </SecurityNote>
//CSD16748
//[SecuritySafeCritical]
private XmlQualifiedName GetStableNameAndSetHasDataContract(Type type)
{
return DataContract.GetStableName(type, out _hasDataContract);
}
/// <SecurityNote>
/// RequiresReview - marked SRR because callers may need to depend on isNonAttributedType for a security decision
/// isNonAttributedType must be calculated correctly
/// SetIsNonAttributedType should not be called before GetStableNameAndSetHasDataContract since it
/// is dependent on the correct calculation of hasDataContract
/// Safe - does not let caller influence isNonAttributedType calculation; no harm in leaking value
/// </SecurityNote>
private void SetIsNonAttributedType(Type type)
{
_isNonAttributedType = !_hasDataContract && IsNonAttributedTypeValidForSerialization(type);
}
private static bool IsMethodOverriding(MethodInfo method)
{
return method.IsVirtual && ((method.Attributes & MethodAttributes.NewSlot) == 0);
}
internal void EnsureMethodsImported()
{
if (!_isMethodChecked && UnderlyingType != null)
{
lock (this)
{
if (!_isMethodChecked)
{
Type type = this.UnderlyingType;
MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
for (int i = 0; i < methods.Length; i++)
{
MethodInfo method = methods[i];
Type prevAttributeType = null;
ParameterInfo[] parameters = method.GetParameters();
//THese attributes are cut from mscorlib.
if (IsValidCallback(method, parameters, Globals.TypeOfOnSerializingAttribute, _onSerializing, ref prevAttributeType))
_onSerializing = method;
if (IsValidCallback(method, parameters, Globals.TypeOfOnSerializedAttribute, _onSerialized, ref prevAttributeType))
_onSerialized = method;
if (IsValidCallback(method, parameters, Globals.TypeOfOnDeserializingAttribute, _onDeserializing, ref prevAttributeType))
_onDeserializing = method;
if (IsValidCallback(method, parameters, Globals.TypeOfOnDeserializedAttribute, _onDeserialized, ref prevAttributeType))
_onDeserialized = method;
}
Interlocked.MemoryBarrier();
_isMethodChecked = true;
}
}
}
}
private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType)
{
if (method.IsDefined(attributeType, false))
{
if (currentCallback != null)
DataContract.ThrowInvalidDataContractException(SR.Format(SR.DuplicateCallback, method, currentCallback, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType);
else if (prevAttributeType != null)
DataContract.ThrowInvalidDataContractException(SR.Format(SR.DuplicateAttribute, prevAttributeType, attributeType, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType);
else if (method.IsVirtual)
DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbacksCannotBeVirtualMethods, method, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType);
else
{
if (method.ReturnType != Globals.TypeOfVoid)
DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbackMustReturnVoid, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType);
if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != Globals.TypeOfStreamingContext)
DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbackParameterInvalid, DataContract.GetClrTypeFullName(method.DeclaringType), method, Globals.TypeOfStreamingContext), method.DeclaringType);
prevAttributeType = attributeType;
}
return true;
}
return false;
}
internal ClassDataContract BaseContract
{
get { return _baseContract; }
set
{
_baseContract = value;
if (_baseContract != null && IsValueType)
ThrowInvalidDataContractException(SR.Format(SR.ValueTypeCannotHaveBaseType, StableName.Name, StableName.Namespace, _baseContract.StableName.Name, _baseContract.StableName.Namespace));
}
}
internal List<DataMember> Members
{
get { return _members; }
}
internal MethodInfo OnSerializing
{
get
{
EnsureMethodsImported();
return _onSerializing;
}
}
internal MethodInfo OnSerialized
{
get
{
EnsureMethodsImported();
return _onSerialized;
}
}
internal MethodInfo OnDeserializing
{
get
{
EnsureMethodsImported();
return _onDeserializing;
}
}
internal MethodInfo OnDeserialized
{
get
{
EnsureMethodsImported();
return _onDeserialized;
}
}
internal override DataContractDictionary KnownDataContracts
{
[SecurityCritical]
get
{
if (!_isKnownTypeAttributeChecked && UnderlyingType != null)
{
lock (this)
{
if (!_isKnownTypeAttributeChecked)
{
_knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType);
Interlocked.MemoryBarrier();
_isKnownTypeAttributeChecked = true;
}
}
}
return _knownDataContracts;
}
[SecurityCritical]
set
{ _knownDataContracts = value; }
}
internal bool HasDataContract
{
get { return _hasDataContract; }
}
internal bool IsNonAttributedType
{
get { return _isNonAttributedType; }
}
private void SetKeyValuePairAdapterFlags(Type type)
{
if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePairAdapter)
{
_isKeyValuePairAdapter = true;
_keyValuePairGenericArguments = type.GetGenericArguments();
_keyValuePairCtorInfo = type.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfKeyValuePair.MakeGenericType(_keyValuePairGenericArguments) });
_getKeyValuePairMethodInfo = type.GetMethod("GetKeyValuePair", Globals.ScanAllMembers);
}
}
private bool _isKeyValuePairAdapter;
private Type[] _keyValuePairGenericArguments;
private ConstructorInfo _keyValuePairCtorInfo;
private MethodInfo _getKeyValuePairMethodInfo;
internal bool IsKeyValuePairAdapter
{
get { return _isKeyValuePairAdapter; }
}
internal bool IsScriptObject
{
get { return _isScriptObject; }
}
internal Type[] KeyValuePairGenericArguments
{
get { return _keyValuePairGenericArguments; }
}
internal ConstructorInfo KeyValuePairAdapterConstructorInfo
{
get { return _keyValuePairCtorInfo; }
}
internal MethodInfo GetKeyValuePairMethodInfo
{
get { return _getKeyValuePairMethodInfo; }
}
internal ConstructorInfo GetNonAttributedTypeConstructor()
{
if (!this.IsNonAttributedType)
return null;
Type type = UnderlyingType;
if (type.GetTypeInfo().IsValueType)
return null;
ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>());
if (ctor == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.NonAttributedSerializableTypesMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type))));
return ctor;
}
internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate
{
get { return _xmlFormatWriterDelegate; }
set { _xmlFormatWriterDelegate = value; }
}
internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate
{
get { return _xmlFormatReaderDelegate; }
set { _xmlFormatReaderDelegate = value; }
}
public XmlDictionaryString[] ChildElementNamespaces
{
get { return _childElementNamespaces; }
set { _childElementNamespaces = value; }
}
internal struct Member
{
internal Member(DataMember member, string ns, int baseTypeIndex)
{
this.member = member;
this.ns = ns;
this.baseTypeIndex = baseTypeIndex;
}
internal DataMember member;
internal string ns;
internal int baseTypeIndex;
}
internal class DataMemberConflictComparer : IComparer<Member>
{
[SecuritySafeCritical]
public int Compare(Member x, Member y)
{
int nsCompare = String.CompareOrdinal(x.ns, y.ns);
if (nsCompare != 0)
return nsCompare;
int nameCompare = String.CompareOrdinal(x.member.Name, y.member.Name);
if (nameCompare != 0)
return nameCompare;
return x.baseTypeIndex - y.baseTypeIndex;
}
internal static DataMemberConflictComparer Singleton = new DataMemberConflictComparer();
}
}
internal class DataMemberComparer : IComparer<DataMember>
{
public int Compare(DataMember x, DataMember y)
{
int orderCompare = x.Order - y.Order;
if (orderCompare != 0)
return orderCompare;
return String.CompareOrdinal(x.Name, y.Name);
}
internal static DataMemberComparer Singleton = new DataMemberComparer();
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.ServiceModel.Activation;
using System.Collections.Generic;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Security.Authentication.ExtendedProtection;
using System.Xml;
using System.ComponentModel;
public class TcpTransportBindingElement : ConnectionOrientedTransportBindingElement
{
int listenBacklog;
bool portSharingEnabled;
bool teredoEnabled;
TcpConnectionPoolSettings connectionPoolSettings;
ExtendedProtectionPolicy extendedProtectionPolicy;
bool isListenBacklogSet;
public TcpTransportBindingElement()
: base()
{
this.listenBacklog = TcpTransportDefaults.GetListenBacklog();
this.portSharingEnabled = TcpTransportDefaults.PortSharingEnabled;
this.teredoEnabled = TcpTransportDefaults.TeredoEnabled;
this.connectionPoolSettings = new TcpConnectionPoolSettings();
this.extendedProtectionPolicy = ChannelBindingUtility.DefaultPolicy;
}
protected TcpTransportBindingElement(TcpTransportBindingElement elementToBeCloned)
: base(elementToBeCloned)
{
this.listenBacklog = elementToBeCloned.listenBacklog;
this.isListenBacklogSet = elementToBeCloned.isListenBacklogSet;
this.portSharingEnabled = elementToBeCloned.portSharingEnabled;
this.teredoEnabled = elementToBeCloned.teredoEnabled;
this.connectionPoolSettings = elementToBeCloned.connectionPoolSettings.Clone();
this.extendedProtectionPolicy = elementToBeCloned.ExtendedProtectionPolicy;
}
public TcpConnectionPoolSettings ConnectionPoolSettings
{
get { return this.connectionPoolSettings; }
}
public int ListenBacklog
{
get
{
return this.listenBacklog;
}
set
{
if (value <= 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value",
SR.GetString(SR.ValueMustBePositive)));
}
this.listenBacklog = value;
this.isListenBacklogSet = true;
}
}
internal bool IsListenBacklogSet
{
get { return this.isListenBacklogSet; }
}
// server
[DefaultValue(TcpTransportDefaults.PortSharingEnabled)]
public bool PortSharingEnabled
{
get
{
return this.portSharingEnabled;
}
set
{
this.portSharingEnabled = value;
}
}
public override string Scheme
{
get { return "net.tcp"; }
}
// server
[DefaultValue(TcpTransportDefaults.TeredoEnabled)]
public bool TeredoEnabled
{
get
{
return this.teredoEnabled;
}
set
{
this.teredoEnabled = value;
}
}
public ExtendedProtectionPolicy ExtendedProtectionPolicy
{
get
{
return this.extendedProtectionPolicy;
}
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
if (value.PolicyEnforcement == PolicyEnforcement.Always &&
!System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy.OSSupportsExtendedProtection)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new PlatformNotSupportedException(SR.GetString(SR.ExtendedProtectionNotSupported)));
}
this.extendedProtectionPolicy = value;
}
}
internal override string WsdlTransportUri
{
get
{
return TransportPolicyConstants.TcpTransportUri;
}
}
public override BindingElement Clone()
{
return new TcpTransportBindingElement(this);
}
public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
if (!this.CanBuildChannelFactory<TChannel>(context))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("TChannel", SR.GetString(SR.ChannelTypeNotSupported, typeof(TChannel)));
}
return (IChannelFactory<TChannel>)(object)new TcpChannelFactory<TChannel>(this, context);
}
public override IChannelListener<TChannel> BuildChannelListener<TChannel>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
if (!this.CanBuildChannelListener<TChannel>(context))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("TChannel", SR.GetString(SR.ChannelTypeNotSupported, typeof(TChannel)));
}
TcpChannelListener listener;
if (typeof(TChannel) == typeof(IReplyChannel))
{
listener = new TcpReplyChannelListener(this, context);
}
else if (typeof(TChannel) == typeof(IDuplexSessionChannel))
{
listener = new TcpDuplexChannelListener(this, context);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("TChannel", SR.GetString(SR.ChannelTypeNotSupported, typeof(TChannel)));
}
AspNetEnvironment.Current.ApplyHostedContext(listener, context);
return (IChannelListener<TChannel>)(object)listener;
}
public override T GetProperty<T>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
if (typeof(T) == typeof(IBindingDeliveryCapabilities))
{
return (T)(object)new BindingDeliveryCapabilitiesHelper();
}
else if (typeof(T) == typeof(ExtendedProtectionPolicy))
{
return (T)(object)this.ExtendedProtectionPolicy;
}
else if (typeof(T) == typeof(ITransportCompressionSupport))
{
return (T)(object)new TransportCompressionSupportHelper();
}
else
{
return base.GetProperty<T>(context);
}
}
internal override bool IsMatch(BindingElement b)
{
if (!base.IsMatch(b))
{
return false;
}
TcpTransportBindingElement tcp = b as TcpTransportBindingElement;
if (tcp == null)
{
return false;
}
if (this.listenBacklog != tcp.listenBacklog)
{
return false;
}
if (this.portSharingEnabled != tcp.portSharingEnabled)
{
return false;
}
if (this.teredoEnabled != tcp.teredoEnabled)
{
return false;
}
if (!this.connectionPoolSettings.IsMatch(tcp.connectionPoolSettings))
{
return false;
}
if (!ChannelBindingUtility.AreEqual(this.ExtendedProtectionPolicy, tcp.ExtendedProtectionPolicy))
{
return false;
}
return true;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeExtendedProtectionPolicy()
{
return !ChannelBindingUtility.AreEqual(this.ExtendedProtectionPolicy, ChannelBindingUtility.DefaultPolicy);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeListenBacklog()
{
return this.isListenBacklogSet;
}
class BindingDeliveryCapabilitiesHelper : IBindingDeliveryCapabilities
{
internal BindingDeliveryCapabilitiesHelper()
{
}
bool IBindingDeliveryCapabilities.AssuresOrderedDelivery
{
get { return true; }
}
bool IBindingDeliveryCapabilities.QueuedDelivery
{
get { return false; }
}
}
class TransportCompressionSupportHelper : ITransportCompressionSupport
{
public bool IsCompressionFormatSupported(CompressionFormat compressionFormat)
{
return true;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Design;
using System.Windows.Forms;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms.VisualStyles;
// Taken from http://www.codeproject.com/Articles/23746/TreeView-with-Columns with minor tweaks
// and fixes for my purposes.
namespace TreelistView
{
[Designer(typeof(TreeListViewDesigner))]
public class TreeListView : Control, ISupportInitialize
{
public event TreeViewEventHandler AfterSelect;
protected virtual void OnAfterSelect(Node node)
{
raiseAfterSelect(node);
}
protected virtual void raiseAfterSelect(Node node)
{
if (AfterSelect != null && node != null)
AfterSelect(this, new TreeViewEventArgs(null));
}
public delegate void NotifyBeforeExpandHandler(Node node, bool isExpanding);
public event NotifyBeforeExpandHandler NotifyBeforeExpand;
public virtual void OnNotifyBeforeExpand(Node node, bool isExpanding)
{
raiseNotifyBeforeExpand(node, isExpanding);
}
protected virtual void raiseNotifyBeforeExpand(Node node, bool isExpanding)
{
if (NotifyBeforeExpand != null)
NotifyBeforeExpand(node, isExpanding);
}
public delegate void NotifyAfterHandler(Node node, bool isExpanding);
public event NotifyAfterHandler NotifyAfterExpand;
public virtual void OnNotifyAfterExpand(Node node, bool isExpanded)
{
raiseNotifyAfterExpand(node, isExpanded);
}
protected virtual void raiseNotifyAfterExpand(Node node, bool isExpanded)
{
if (NotifyAfterExpand != null)
NotifyAfterExpand(node, isExpanded);
}
public delegate void NodeDoubleClickedHandler(Node node);
public event NodeDoubleClickedHandler NodeDoubleClicked;
public virtual void OnNodeDoubleClicked(Node node)
{
raiseNodeDoubleClicked(node);
}
protected virtual void raiseNodeDoubleClicked(Node node)
{
if (NodeDoubleClicked != null)
NodeDoubleClicked(node);
}
public delegate void NodeClickedHandler(Node node);
public event NodeClickedHandler NodeClicked;
public virtual void OnNodeClicked(Node node)
{
raiseNodeClicked(node);
}
protected virtual void raiseNodeClicked(Node node)
{
if (NodeClicked != null)
NodeClicked(node);
}
TreeListViewNodes m_nodes;
TreeListColumnCollection m_columns;
TreeList.RowSetting m_rowSetting;
TreeList.ViewSetting m_viewSetting;
Color m_GridLineColour = SystemColors.Control;
Image m_SelectedImage = null;
[Category("Columns")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public TreeListColumnCollection Columns
{
get { return m_columns; }
}
[Category("Options")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public TreeList.CollumnSetting ColumnsOptions
{
get { return m_columns.Options; }
}
[Category("Options")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public TreeList.RowSetting RowOptions
{
get { return m_rowSetting; }
}
[Category("Options")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public TreeList.ViewSetting ViewOptions
{
get { return m_viewSetting; }
}
[Category("Behavior")]
[DefaultValue(typeof(bool), "True")]
public bool MultiSelect
{
get { return m_multiSelect; }
set { m_multiSelect = value; }
}
[Category("Behavior")]
[DefaultValue(typeof(int), "0")]
public int TreeColumn
{
get { return m_treeColumn; }
set
{
m_treeColumn = value;
if(value >= m_columns.Count)
throw new ArgumentOutOfRangeException("Tree column index invalid");
}
}
private int GetTreeColumn(Node n)
{
if (n != null && n.TreeColumn >= 0)
return n.TreeColumn;
return m_treeColumn;
}
[Category("Behavior")]
[DefaultValue(typeof(bool), "False")]
public bool AlwaysDisplayVScroll
{
get { return m_vScrollAlways; }
set { m_vScrollAlways = value; }
}
[Category("Behavior")]
[DefaultValue(typeof(bool), "False")]
public bool AlwaysDisplayHScroll
{
get { return m_hScrollAlways; }
set { m_hScrollAlways = value; }
}
[Category("Appearance")]
[DefaultValue(typeof(Image), null)]
public Image SelectedImage
{
get { return m_SelectedImage; }
set { m_SelectedImage = value; }
}
[DefaultValue(typeof(Color), "Window")]
public new Color BackColor
{
get { return base.BackColor; }
set { base.BackColor = value; }
}
[Category("Appearance")]
[DefaultValue(typeof(Color), "Control")]
public Color GridLineColour
{
get { return m_GridLineColour; }
set { m_GridLineColour = value; }
}
//[Browsable(false)]
public TreeListViewNodes Nodes
{
get { return m_nodes; }
}
public TreeListView()
{
this.DoubleBuffered = true;
this.BackColor = SystemColors.Window;
this.TabStop = true;
m_tooltip = new ToolTip();
m_tooltipVisible = false;
m_tooltip.InitialDelay = 0;
m_tooltip.UseAnimation = false;
m_tooltip.UseFading = false;
m_tooltipNode = null;
m_tooltipTimer = new Timer();
m_tooltipTimer.Stop();
m_tooltipTimer.Interval = 500;
m_tooltipTimer.Tick += new EventHandler(tooltipTick);
m_rowPainter = new RowPainter();
m_cellPainter = new CellPainter(this);
m_nodes = new TreeListViewNodes(this);
m_rowSetting = new TreeList.RowSetting(this);
m_viewSetting = new TreeList.ViewSetting(this);
m_columns = new TreeListColumnCollection(this);
AddScrollBars();
}
protected override void Dispose(bool disposing)
{
m_tooltipTimer.Stop();
if(m_tooltipVisible)
m_tooltip.Hide(this);
m_tooltip.Dispose();
base.Dispose(disposing);
}
void tooltipTick(object sender, EventArgs e)
{
m_tooltipTimer.Stop();
if (m_tooltipNode == null)
{
m_tooltip.Hide(this);
m_tooltipVisible = false;
return;
}
Node node = m_tooltipNode;
Point p = PointToClient(Cursor.Position);
if (!ClientRectangle.Contains(p))
{
m_tooltip.Hide(this);
m_tooltipVisible = false;
return;
}
int visibleRowIndex = CalcHitRow(PointToClient(Cursor.Position));
Rectangle rowRect = CalcRowRectangle(visibleRowIndex);
rowRect.X = RowHeaderWidth() - HScrollValue();
rowRect.Width = Columns.ColumnsWidth;
// draw the current node
foreach (TreeListColumn col in Columns.VisibleColumns)
{
if (col.Index == GetTreeColumn(node))
{
Rectangle cellRect = rowRect;
cellRect.X = col.CalculatedRect.X - HScrollValue();
int lineindet = 10;
// add left margin
cellRect.X += Columns.Options.LeftMargin;
// add indent size
cellRect.X += GetIndentSize(node) + 5;
cellRect.X += lineindet;
Rectangle plusminusRect = GetPlusMinusRectangle(node, col, visibleRowIndex);
if (!ViewOptions.ShowLine && (!ViewOptions.ShowPlusMinus || (!ViewOptions.PadForPlusMinus && plusminusRect == Rectangle.Empty)))
cellRect.X -= (lineindet + 5);
if (SelectedImage != null && (NodesSelection.Contains(node) || FocusedNode == node))
cellRect.X += (SelectedImage.Width + 2);
Image icon = GetHoverNodeBitmap(node);
if (icon != null)
cellRect.X += (icon.Width + 2);
string datastring = "";
object data = GetData(node, col);
if(data == null)
data = "";
if (CellPainter.CellDataConverter != null)
datastring = CellPainter.CellDataConverter(col, data);
else
datastring = data.ToString();
if(datastring.Length > 0)
{
m_tooltip.Show(datastring, this, cellRect.X, cellRect.Y);
m_tooltipVisible = true;
}
}
}
}
public void RecalcLayout()
{
if (m_firstVisibleNode == null)
m_firstVisibleNode = Nodes.FirstNode;
if (Nodes.Count == 0)
m_firstVisibleNode = null;
UpdateScrollBars();
m_columns.RecalcVisibleColumsRect();
UpdateScrollBars();
m_columns.RecalcVisibleColumsRect();
int vscroll = VScrollValue();
if (vscroll == 0)
m_firstVisibleNode = Nodes.FirstNode;
else
m_firstVisibleNode = NodeCollection.GetNextNode(Nodes.FirstNode, vscroll);
Invalidate();
}
void AddScrollBars()
{
// I was not able to get the wanted behavior by using ScrollableControl with AutoScroll enabled.
// horizontal scrolling is ok to do it by pixels, but for vertical I want to maintain the headers
// and only scroll the rows.
// I was not able to manually overwrite the vscroll bar handling to get this behavior, instead I opted for
// custom implementation of scrollbars
// to get the 'filler' between hscroll and vscroll I dock scroll + filler in a panel
m_hScroll = new HScrollBar();
m_hScroll.Scroll += new ScrollEventHandler(OnHScroll);
m_hScroll.Dock = DockStyle.Fill;
m_vScroll = new VScrollBar();
m_vScroll.Scroll += new ScrollEventHandler(OnVScroll);
m_vScroll.Dock = DockStyle.Right;
m_hScrollFiller = new Panel();
m_hScrollFiller.BackColor = Color.Transparent;
m_hScrollFiller.Size = new Size(m_vScroll.Width-1, m_hScroll.Height);
m_hScrollFiller.Dock = DockStyle.Right;
Controls.Add(m_vScroll);
m_hScrollPanel = new Panel();
m_hScrollPanel.Height = m_hScroll.Height;
m_hScrollPanel.Dock = DockStyle.Bottom;
m_hScrollPanel.Controls.Add(m_hScroll);
m_hScrollPanel.Controls.Add(m_hScrollFiller);
Controls.Add(m_hScrollPanel);
// try and force handle creation here, as it can fail randomly
// at runtime with weird side-effects (See github #202).
bool handlesCreated = false;
handlesCreated |= m_hScroll.Handle.ToInt64() > 0;
handlesCreated |= m_vScroll.Handle.ToInt64() > 0;
handlesCreated |= m_hScrollFiller.Handle.ToInt64() > 0;
handlesCreated |= m_hScrollPanel.Handle.ToInt64() > 0;
if (!handlesCreated)
renderdoc.StaticExports.LogText("Couldn't create any handles!");
}
ToolTip m_tooltip;
Node m_tooltipNode;
Timer m_tooltipTimer;
bool m_tooltipVisible;
VScrollBar m_vScroll;
HScrollBar m_hScroll;
Panel m_hScrollFiller;
Panel m_hScrollPanel;
bool m_multiSelect = true;
int m_treeColumn = 0;
bool m_vScrollAlways = false;
bool m_hScrollAlways = false;
Node m_firstVisibleNode = null;
RowPainter m_rowPainter;
CellPainter m_cellPainter;
[Browsable(false)]
public CellPainter CellPainter
{
get { return m_cellPainter; }
set { m_cellPainter = value; }
}
TreeListColumn m_resizingColumn;
int m_resizingColumnScrollOffset;
int m_resizingColumnLeft;
TreeListColumn m_movingColumn;
NodesSelection m_nodesSelection = new NodesSelection();
Node m_focusedNode = null;
[Browsable(false)]
public NodesSelection NodesSelection
{
get { return m_nodesSelection; }
}
public void SortNodesSelection()
{
m_nodesSelection.Sort();
}
public void SelectAll()
{
FocusedNode = null;
NodesSelection.Clear();
foreach (Node node in NodeCollection.ForwardNodeIterator(m_firstVisibleNode, true))
{
NodesSelection.Add(node);
}
Invalidate();
}
[Browsable(false)]
public Node SelectedNode
{
get { return m_nodesSelection.Count == 0 ? FocusedNode : m_nodesSelection[0]; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Node FocusedNode
{
get { return m_focusedNode; }
set
{
Node curNode = FocusedNode;
if (object.ReferenceEquals(curNode, value))
return;
if (MultiSelect == false)
NodesSelection.Clear();
int oldrow = NodeCollection.GetVisibleNodeIndex(curNode);
int newrow = NodeCollection.GetVisibleNodeIndex(value);
m_focusedNode = value;
OnAfterSelect(value);
InvalidateRow(oldrow);
InvalidateRow(newrow);
EnsureVisible(m_focusedNode);
}
}
public void EnsureVisible(Node node)
{
int screenvisible = MaxVisibleRows() - 1;
int visibleIndex = NodeCollection.GetVisibleNodeIndex(node);
if (visibleIndex < VScrollValue())
{
SetVScrollValue(visibleIndex);
}
if (visibleIndex > VScrollValue() + screenvisible)
{
SetVScrollValue(visibleIndex - screenvisible);
}
}
public Node CalcHitNode(Point mousepoint)
{
if (!ClientRectangle.Contains(mousepoint))
return null;
int hitrow = CalcHitRow(mousepoint);
if (hitrow < 0)
return null;
return NodeCollection.GetNextNode(m_firstVisibleNode, hitrow);
}
public Node GetHitNode()
{
return CalcHitNode(PointToClient(Control.MousePosition));
}
public TreelistView.HitInfo CalcColumnHit(Point mousepoint)
{
return Columns.CalcHitInfo(mousepoint, HScrollValue());
}
public bool HitTestScrollbar(Point mousepoint)
{
if (m_hScroll.Visible && mousepoint.Y >= ClientRectangle.Height - m_hScroll.Height)
return true;
return false;
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
if (ClientRectangle.Width > 0 && ClientRectangle.Height > 0)
{
Columns.RecalcVisibleColumsRect();
UpdateScrollBars();
Columns.RecalcVisibleColumsRect();
}
}
protected override void OnVisibleChanged(EventArgs e)
{
base.OnVisibleChanged(e);
RecalcLayout();
}
protected virtual void BeforeShowContextMenu()
{
}
protected void InvalidateRow(int absoluteRowIndex)
{
int visibleRowIndex = absoluteRowIndex - VScrollValue();
Rectangle r = CalcRowRectangle(visibleRowIndex);
if (r != Rectangle.Empty)
{
r.Inflate(1,1);
Invalidate(r);
}
}
void OnVScroll(object sender, ScrollEventArgs e)
{
int diff = e.NewValue - e.OldValue;
//assumedScrollPos += diff;
if (e.NewValue == 0)
{
m_firstVisibleNode = Nodes.FirstNode;
diff = 0;
}
m_firstVisibleNode = NodeCollection.GetNextNode(m_firstVisibleNode, diff);
Invalidate();
}
void OnHScroll(object sender, ScrollEventArgs e)
{
Invalidate();
}
public void SetVScrollValue(int value)
{
if (value < 0)
value = 0;
int max = m_vScroll.Maximum - m_vScroll.LargeChange + 1;
if (value > max)
value = max;
if ((value >= 0 && value <= max) && (value != m_vScroll.Value))
{
ScrollEventArgs e = new ScrollEventArgs(ScrollEventType.ThumbPosition, m_vScroll.Value, value, ScrollOrientation.VerticalScroll);
// setting the scroll value does not cause a Scroll event
m_vScroll.Value = value;
// so we have to fake it
OnVScroll(m_vScroll, e);
}
}
public int VScrollValue()
{
if (m_vScroll.Visible == false)
return 0;
return m_vScroll.Value;
}
int HScrollValue()
{
if (m_hScroll.Visible == false)
return 0;
return m_hScroll.Value;
}
void UpdateScrollBars()
{
if (ClientRectangle.Width < 0)
return;
int maxvisiblerows = MaxVisibleRows();
int totalrows = Nodes.VisibleNodeCount;
m_vScroll.SmallChange = 1;
m_vScroll.LargeChange = Math.Max(1, maxvisiblerows);
m_vScroll.Enabled = true;
m_vScroll.Minimum = 0;
m_vScroll.Maximum = Math.Max(1,totalrows - 1);
if (maxvisiblerows >= totalrows)
{
m_vScroll.Visible = false;
SetVScrollValue(0);
if (m_vScrollAlways)
{
m_vScroll.Visible = true;
m_vScroll.Enabled = false;
}
}
else
{
m_vScroll.Visible = true;
int maxscrollvalue = m_vScroll.Maximum - m_vScroll.LargeChange;
if (maxscrollvalue < m_vScroll.Value)
SetVScrollValue(maxscrollvalue);
}
m_hScroll.Enabled = true;
if (ClientRectangle.Width > MinWidth())
{
m_hScrollPanel.Visible = false;
m_hScroll.Value = 0;
if (m_hScrollAlways)
{
m_hScroll.Enabled = false;
m_hScrollPanel.Visible = true;
m_hScroll.Minimum = 0;
m_hScroll.Maximum = 0;
m_hScroll.SmallChange = 1;
m_hScroll.LargeChange = 1;
m_hScrollFiller.Visible = m_vScroll.Visible;
}
}
else
{
m_hScroll.Minimum = 0;
m_hScroll.Maximum = Math.Max(1, MinWidth());
m_hScroll.SmallChange = 5;
m_hScroll.LargeChange = Math.Max(1, ClientRectangle.Width);
m_hScrollFiller.Visible = m_vScroll.Visible;
m_hScrollPanel.Visible = true;
}
}
int m_hotrow = -1;
int CalcHitRow(Point mousepoint)
{
if (mousepoint.Y <= Columns.Options.HeaderHeight)
return -1;
return (mousepoint.Y - Columns.Options.HeaderHeight) / RowOptions.ItemHeight;
}
int VisibleRowToYPoint(int visibleRowIndex)
{
return Columns.Options.HeaderHeight + (visibleRowIndex * RowOptions.ItemHeight);
}
Rectangle CalcRowRectangle(int visibleRowIndex)
{
Rectangle r = ClientRectangle;
r.Y = VisibleRowToYPoint(visibleRowIndex);
if (r.Top < Columns.Options.HeaderHeight || r.Top > ClientRectangle.Height)
return Rectangle.Empty;
r.Height = RowOptions.ItemHeight;
return r;
}
void MultiSelectAdd(Node clickedNode, Keys modifierKeys)
{
if (Control.ModifierKeys == Keys.None)
{
foreach (Node node in NodesSelection)
{
int newrow = NodeCollection.GetVisibleNodeIndex(node);
InvalidateRow(newrow);
}
NodesSelection.Clear();
NodesSelection.Add(clickedNode);
}
if (Control.ModifierKeys == Keys.Shift)
{
if (NodesSelection.Count == 0)
NodesSelection.Add(clickedNode);
else
{
int startrow = NodeCollection.GetVisibleNodeIndex(NodesSelection[0]);
int currow = NodeCollection.GetVisibleNodeIndex(clickedNode);
if (currow > startrow)
{
Node startingNode = NodesSelection[0];
NodesSelection.Clear();
foreach (Node node in NodeCollection.ForwardNodeIterator(startingNode, clickedNode, true))
NodesSelection.Add(node);
Invalidate();
}
if (currow < startrow)
{
Node startingNode = NodesSelection[0];
NodesSelection.Clear();
foreach (Node node in NodeCollection.ReverseNodeIterator(startingNode, clickedNode, true))
NodesSelection.Add(node);
Invalidate();
}
}
}
if (Control.ModifierKeys == Keys.Control)
{
if (NodesSelection.Contains(clickedNode))
NodesSelection.Remove(clickedNode);
else
NodesSelection.Add(clickedNode);
}
InvalidateRow(NodeCollection.GetVisibleNodeIndex(clickedNode));
FocusedNode = clickedNode;
}
internal event MouseEventHandler AfterResizingColumn;
protected override void OnMouseClick(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Point mousePoint = new Point(e.X, e.Y);
Node clickedNode = CalcHitNode(mousePoint);
if (clickedNode != null && Columns.Count > 0)
{
int clickedRow = CalcHitRow(mousePoint);
Rectangle glyphRect = Rectangle.Empty;
int treeColumn = GetTreeColumn(clickedNode);
if (treeColumn >= 0)
glyphRect = GetPlusMinusRectangle(clickedNode, Columns[treeColumn], clickedRow);
if (clickedNode.HasChildren && glyphRect != Rectangle.Empty && glyphRect.Contains(mousePoint))
clickedNode.Expanded = !clickedNode.Expanded;
var columnHit = CalcColumnHit(mousePoint);
if (glyphRect == Rectangle.Empty && columnHit.Column != null &&
columnHit.Column.Index == treeColumn && GetNodeBitmap(clickedNode) != null)
{
OnNodeClicked(clickedNode);
}
if (MultiSelect)
{
MultiSelectAdd(clickedNode, Control.ModifierKeys);
}
else
FocusedNode = clickedNode;
}
/*
else
{
FocusedNode = null;
NodesSelection.Clear();
}*/
}
base.OnMouseClick(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (m_movingColumn != null)
{
m_movingColumn.Moving = true;
Cursor = Cursors.SizeAll;
var idx = m_movingColumn.VisibleIndex;
if (idx + 1 < Columns.VisibleColumns.Length)
{
var nextcol = Columns.VisibleColumns[idx + 1];
if (nextcol.CalculatedRect.X + (nextcol.CalculatedRect.Width * 3) / 4 < e.X)
{
Columns.SetVisibleIndex(m_movingColumn, idx + 1);
}
}
if (idx - 1 >= 0)
{
var prevcol = Columns.VisibleColumns[idx - 1];
if (prevcol.CalculatedRect.Right - (prevcol.CalculatedRect.Width * 3) / 4 > e.X)
{
Columns.SetVisibleIndex(m_movingColumn, idx - 1);
}
}
Columns.RecalcVisibleColumsRect(true);
Invalidate();
return;
}
if (m_resizingColumn != null)
{
// if we've clicked on an autosize column, actually resize the next one along.
if (m_resizingColumn.AutoSize)
{
if (Columns.VisibleColumns.Length > m_resizingColumn.VisibleIndex + 1)
{
TreeListColumn realResizeColumn = Columns.VisibleColumns[m_resizingColumn.VisibleIndex + 1];
int right = realResizeColumn.CalculatedRect.Right - m_resizingColumnScrollOffset;
int width = right - e.X;
if (width < 10)
width = 10;
bool resize = true;
if (Columns.VisibleColumns.Length > realResizeColumn.VisibleIndex + 1)
if (Columns.VisibleColumns[realResizeColumn.VisibleIndex + 1].CalculatedRect.Width <= 10 && m_resizingColumn.Width < width)
resize = false;
if (realResizeColumn.VisibleIndex > 1)
if (Columns.VisibleColumns[realResizeColumn.VisibleIndex - 1].CalculatedRect.Width <= 10 && m_resizingColumn.Width < width)
resize = false;
if (resize)
{
realResizeColumn.Width = width;
}
}
}
else
{
int left = m_resizingColumnLeft;
int width = e.X - left;
if (width < 10)
width = 10;
bool resize = true;
if (Columns.VisibleColumns.Length > m_resizingColumn.VisibleIndex + 1)
if (Columns.VisibleColumns[m_resizingColumn.VisibleIndex + 1].CalculatedRect.Width <= 10 && m_resizingColumn.Width < width)
resize = false;
if (m_resizingColumn.internalIndex > 1)
if (Columns.VisibleColumns[m_resizingColumn.VisibleIndex - 1].CalculatedRect.Width <= 10 && m_resizingColumn.Width < width)
resize = false;
if (resize)
m_resizingColumn.Width = width;
}
Columns.RecalcVisibleColumsRect(true);
Invalidate();
return;
}
TreeListColumn hotcol = null;
TreelistView.HitInfo info = Columns.CalcHitInfo(new Point(e.X, e.Y), HScrollValue());
if ((int)(info.HitType & HitInfo.eHitType.kColumnHeader) > 0)
hotcol = info.Column;
Node clickedNode = CalcHitNode(new Point(e.X, e.Y));
if ((int)(info.HitType & HitInfo.eHitType.kColumnHeaderResize) > 0)
Cursor = Cursors.VSplit;
else if (info.Column != null &&
info.Column.Index == GetTreeColumn(clickedNode) &&
GetNodeBitmap(clickedNode) != null &&
m_viewSetting.HoverHandTreeColumn)
Cursor = Cursors.Hand;
else
Cursor = Cursors.Arrow;
if (!this.DesignMode && clickedNode != null && clickedNode.ClippedText)
{
m_tooltipNode = clickedNode;
m_tooltipTimer.Start();
}
else
{
m_tooltipNode = null;
m_tooltip.Hide(this);
m_tooltipVisible = false;
m_tooltipTimer.Stop();
}
if (GetHoverNodeBitmap(clickedNode) != null &&
GetNodeBitmap(clickedNode) != GetHoverNodeBitmap(clickedNode))
Invalidate();
SetHotColumn(hotcol, true);
int vScrollOffset = VScrollValue();
int newhotrow = -1;
if (hotcol == null)
{
int row = (e.Y - Columns.Options.HeaderHeight) / RowOptions.ItemHeight;
newhotrow = row + vScrollOffset;
}
if (newhotrow != m_hotrow)
{
InvalidateRow(m_hotrow);
m_hotrow = newhotrow;
InvalidateRow(m_hotrow);
}
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
SetHotColumn(null, false);
Cursor = Cursors.Arrow;
Invalidate();
}
protected override void OnMouseWheel(MouseEventArgs e)
{
m_tooltip.Hide(this);
m_tooltipVisible = false;
m_tooltipTimer.Stop();
int value = m_vScroll.Value - (e.Delta * SystemInformation.MouseWheelScrollLines / 120);
if (m_vScroll.Visible)
SetVScrollValue(value);
base.OnMouseWheel(e);
}
protected override void OnMouseDown(MouseEventArgs e)
{
m_tooltip.Hide(this);
m_tooltipVisible = false;
m_tooltipTimer.Stop();
this.Focus();
if (e.Button == MouseButtons.Right)
{
Point mousePoint = new Point(e.X, e.Y);
Node clickedNode = CalcHitNode(mousePoint);
if (clickedNode != null)
{
// if multi select the selection is cleard if clicked node is not in selection
if (MultiSelect)
{
if (NodesSelection.Contains(clickedNode) == false)
MultiSelectAdd(clickedNode, Control.ModifierKeys);
}
FocusedNode = clickedNode;
Invalidate();
}
BeforeShowContextMenu();
}
if (e.Button == MouseButtons.Left)
{
TreelistView.HitInfo info = Columns.CalcHitInfo(new Point(e.X, e.Y), HScrollValue());
if ((int)(info.HitType & HitInfo.eHitType.kColumnHeaderResize) > 0)
{
m_resizingColumn = info.Column;
m_resizingColumnScrollOffset = HScrollValue();
m_resizingColumnLeft = m_resizingColumn.CalculatedRect.Left - m_resizingColumnScrollOffset;
return;
}
if ((int)(info.HitType & HitInfo.eHitType.kColumnHeader) > 0 && m_viewSetting.UserRearrangeableColumns)
{
m_movingColumn = info.Column;
return;
}
}
base.OnMouseDown(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
if (m_resizingColumn != null)
{
m_resizingColumn = null;
Columns.RecalcVisibleColumsRect();
UpdateScrollBars();
Invalidate();
if (AfterResizingColumn != null)
AfterResizingColumn(this, e);
}
if (m_movingColumn != null)
{
m_movingColumn.Moving = false;
m_movingColumn = null;
Cursor = Cursors.Arrow;
Columns.RecalcVisibleColumsRect();
UpdateScrollBars();
Invalidate();
}
base.OnMouseUp(e);
}
protected override void OnMouseDoubleClick(MouseEventArgs e)
{
base.OnMouseDoubleClick(e);
Point mousePoint = new Point(e.X, e.Y);
Node clickedNode = CalcHitNode(mousePoint);
if (clickedNode != null && clickedNode.HasChildren)
clickedNode.Expanded = !clickedNode.Expanded;
if (clickedNode != null)
OnNodeDoubleClicked(clickedNode);
}
// Somewhere I read that it could be risky to do any handling in GetFocus / LostFocus.
// The reason is that it will throw exception incase you make a call which recreates the windows handle (e.g.
// change the border style. Instead one should always use OnEnter and OnLeave instead. That is why I'm using
// OnEnter and OnLeave instead, even though I'm only doing Invalidate.
protected override void OnEnter(EventArgs e)
{
base.OnEnter(e);
Invalidate();
}
protected override void OnLeave(EventArgs e)
{
m_tooltipNode = null;
m_tooltip.Hide(this);
m_tooltipVisible = false;
m_tooltipTimer.Stop();
base.OnLeave(e);
Invalidate();
}
protected override void OnLostFocus(EventArgs e)
{
m_tooltipNode = null;
m_tooltip.Hide(this);
m_tooltipVisible = false;
m_tooltipTimer.Stop();
base.OnLostFocus(e);
Invalidate();
}
void SetHotColumn(TreeListColumn col, bool ishot)
{
int scrolloffset = HScrollValue();
if (col != m_hotColumn)
{
if (m_hotColumn != null)
{
m_hotColumn.ishot = false;
Rectangle r = m_hotColumn.CalculatedRect;
r.X -= scrolloffset;
Invalidate(r);
}
m_hotColumn = col;
if (m_hotColumn != null)
{
m_hotColumn.ishot = ishot;
Rectangle r = m_hotColumn.CalculatedRect;
r.X -= scrolloffset;
Invalidate(r);
}
}
}
internal int RowHeaderWidth()
{
if (RowOptions.ShowHeader)
return RowOptions.HeaderWidth;
return 0;
}
int MinWidth()
{
return RowHeaderWidth() + Columns.ColumnsWidth;
}
int MaxVisibleRows(out int remainder)
{
remainder = 0;
if (ClientRectangle.Height < 0)
return 0;
int height = ClientRectangle.Height - Columns.Options.HeaderHeight;
//return (int) Math.Ceiling((double)(ClientRectangle.Height - Columns.HeaderHeight) / (double)Nodes.ItemHeight);
remainder = (ClientRectangle.Height - Columns.Options.HeaderHeight) % RowOptions.ItemHeight ;
return Math.Max(0, (ClientRectangle.Height - Columns.Options.HeaderHeight) / RowOptions.ItemHeight);
}
int MaxVisibleRows()
{
int unused;
return MaxVisibleRows(out unused);
}
public void BeginUpdate()
{
m_nodes.BeginUpdate();
}
public void EndUpdate()
{
m_nodes.EndUpdate();
RecalcLayout();
Invalidate();
}
protected override CreateParams CreateParams
{
get
{
const int WS_BORDER = 0x00800000;
const int WS_EX_CLIENTEDGE = 0x00000200;
CreateParams p = base.CreateParams;
p.Style &= ~(int)WS_BORDER;
p.ExStyle &= ~(int)WS_EX_CLIENTEDGE;
switch (ViewOptions.BorderStyle)
{
case BorderStyle.Fixed3D:
p.ExStyle |= (int)WS_EX_CLIENTEDGE;
break;
case BorderStyle.FixedSingle:
p.Style |= (int)WS_BORDER;
break;
default:
break;
}
return p;
}
}
TreeListColumn m_hotColumn = null;
object GetDataDesignMode(Node node, TreeListColumn column)
{
string id = string.Empty;
while (node != null)
{
id = node.Owner.GetNodeIndex(node).ToString() + ":" + id;
node = node.Parent;
}
return "<temp>" + id;
}
protected virtual object GetData(Node node, TreeListColumn column)
{
if (node[column.Index] != null)
return node[column.Index];
return null;
}
public new Rectangle ClientRectangle
{
get
{
Rectangle r = base.ClientRectangle;
if (m_vScroll.Visible)
r.Width -= m_vScroll.Width+1;
if (m_hScroll.Visible)
r.Height -= m_hScroll.Height+1;
return r;
}
}
protected virtual TreelistView.TreeList.TextFormatting GetFormatting(TreelistView.Node node, TreelistView.TreeListColumn column)
{
return column.CellFormat;
}
protected virtual void PaintCellPlusMinus(Graphics dc, Rectangle glyphRect, Node node, TreeListColumn column)
{
CellPainter.PaintCellPlusMinus(dc, glyphRect, node, column, GetFormatting(node, column));
}
protected virtual void PaintCellBackground(Graphics dc, Rectangle cellRect, Node node, TreeListColumn column)
{
if (this.DesignMode)
CellPainter.PaintCellBackground(dc, cellRect, node, column, GetFormatting(node, column), GetDataDesignMode(node, column));
else
CellPainter.PaintCellBackground(dc, cellRect, node, column, GetFormatting(node, column), GetData(node, column));
}
protected virtual void PaintCellText(Graphics dc, Rectangle cellRect, Node node, TreeListColumn column)
{
if (this.DesignMode)
CellPainter.PaintCellText(dc, cellRect, node, column, GetFormatting(node, column), GetDataDesignMode(node, column));
else
CellPainter.PaintCellText(dc, cellRect, node, column, GetFormatting(node, column), GetData(node, column));
}
protected virtual void PaintImage(Graphics dc, Rectangle imageRect, Node node, Image image)
{
if (image != null)
dc.DrawImage(image, imageRect.X, imageRect.Y, imageRect.Width, imageRect.Height);
}
protected virtual void PaintNode(Graphics dc, Rectangle rowRect, Node node, TreeListColumn[] visibleColumns, int visibleRowIndex)
{
CellPainter.DrawSelectionBackground(dc, rowRect, node);
foreach (TreeListColumn col in visibleColumns)
{
if (col.CalculatedRect.Right - HScrollValue() < RowHeaderWidth())
continue;
Rectangle cellRect = rowRect;
cellRect.X = col.CalculatedRect.X - HScrollValue();
cellRect.Width = col.CalculatedRect.Width;
dc.SetClip(cellRect);
if (col.Index == GetTreeColumn(node))
{
int lineindet = 10;
// add left margin
cellRect.X += Columns.Options.LeftMargin;
cellRect.Width -= Columns.Options.LeftMargin;
// add indent size
int indentSize = GetIndentSize(node) + 5;
cellRect.X += indentSize;
cellRect.Width -= indentSize;
// save rectangle for line drawing below
Rectangle lineCellRect = cellRect;
cellRect.X += lineindet;
cellRect.Width -= lineindet;
Rectangle glyphRect = GetPlusMinusRectangle(node, col, visibleRowIndex);
Rectangle plusminusRect = glyphRect;
if (!ViewOptions.ShowLine && (!ViewOptions.ShowPlusMinus || (!ViewOptions.PadForPlusMinus && plusminusRect == Rectangle.Empty)))
{
cellRect.X -= (lineindet + 5);
cellRect.Width += (lineindet + 5);
}
Point mousePoint = PointToClient(Cursor.Position);
Node hoverNode = CalcHitNode(mousePoint);
Image icon = hoverNode != null && hoverNode == node ? GetHoverNodeBitmap(node) : GetNodeBitmap(node);
PaintCellBackground(dc, cellRect, node, col);
if (ViewOptions.ShowLine)
PaintLines(dc, lineCellRect, node);
if (SelectedImage != null && (NodesSelection.Contains(node) || FocusedNode == node))
{
// center the image vertically
glyphRect.Y = cellRect.Y + (cellRect.Height / 2) - (SelectedImage.Height / 2);
glyphRect.X = cellRect.X;
glyphRect.Width = SelectedImage.Width;
glyphRect.Height = SelectedImage.Height;
PaintImage(dc, glyphRect, node, SelectedImage);
cellRect.X += (glyphRect.Width + 2);
cellRect.Width -= (glyphRect.Width + 2);
}
if (icon != null)
{
// center the image vertically
glyphRect.Y = cellRect.Y + (cellRect.Height / 2) - (icon.Height / 2);
glyphRect.X = cellRect.X;
glyphRect.Width = icon.Width;
glyphRect.Height = icon.Height;
PaintImage(dc, glyphRect, node, icon);
cellRect.X += (glyphRect.Width + 2);
cellRect.Width -= (glyphRect.Width + 2);
}
PaintCellText(dc, cellRect, node, col);
if (plusminusRect != Rectangle.Empty && ViewOptions.ShowPlusMinus)
PaintCellPlusMinus(dc, plusminusRect, node, col);
}
else
{
PaintCellBackground(dc, cellRect, node, col);
PaintCellText(dc, cellRect, node, col);
}
dc.ResetClip();
}
}
protected virtual void PaintLines(Graphics dc, Rectangle cellRect, Node node)
{
Pen pen = new Pen(Color.Gray);
pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
int halfPoint = cellRect.Top + (cellRect.Height / 2);
// line should start from center at first root node
if (node.Parent == null && node.PrevSibling == null)
{
cellRect.Y += (cellRect.Height / 2);
cellRect.Height -= (cellRect.Height / 2);
}
if (node.NextSibling != null || node.HasChildren) // draw full height line
dc.DrawLine(pen, cellRect.X, cellRect.Top, cellRect.X, cellRect.Bottom);
else
dc.DrawLine(pen, cellRect.X, cellRect.Top, cellRect.X, halfPoint);
dc.DrawLine(pen, cellRect.X, halfPoint, cellRect.X + 10, halfPoint);
// now draw the lines for the parents sibling
Node parent = node.Parent;
while (parent != null)
{
Pen linePen = null;
if (parent.TreeLineColor != Color.Transparent || parent.TreeLineWidth > 0.0f)
linePen = new Pen(parent.TreeLineColor, parent.TreeLineWidth);
cellRect.X -= ViewOptions.Indent;
dc.DrawLine(linePen != null ? linePen : pen, cellRect.X, cellRect.Top, cellRect.X, cellRect.Bottom);
parent = parent.Parent;
if (linePen != null)
linePen.Dispose();
}
pen.Dispose();
}
protected virtual int GetIndentSize(Node node)
{
int indent = 0;
Node parent = node.Parent;
while (parent != null)
{
indent += ViewOptions.Indent;
parent = parent.Parent;
}
return indent;
}
protected virtual Rectangle GetPlusMinusRectangle(Node node, TreeListColumn firstColumn, int visibleRowIndex)
{
if (node.HasChildren == false)
return Rectangle.Empty;
int hScrollOffset = HScrollValue();
if (firstColumn.CalculatedRect.Right - hScrollOffset < RowHeaderWidth())
return Rectangle.Empty;
//System.Diagnostics.Debug.Assert(firstColumn.VisibleIndex == 0);
Rectangle glyphRect = firstColumn.CalculatedRect;
glyphRect.X -= hScrollOffset;
glyphRect.X += GetIndentSize(node);
glyphRect.X += Columns.Options.LeftMargin;
glyphRect.Width = 10;
glyphRect.Y = VisibleRowToYPoint(visibleRowIndex);
glyphRect.Height = RowOptions.ItemHeight;
return glyphRect;
}
protected virtual Image GetNodeBitmap(Node node)
{
if (node != null)
return node.Image;
return null;
}
protected virtual Image GetHoverNodeBitmap(Node node)
{
if (node != null)
return node.HoverImage;
return null;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
int hScrollOffset = HScrollValue();
int remainder = 0;
int visiblerows = MaxVisibleRows(out remainder);
if (remainder > 0)
visiblerows++;
bool drawColumnHeaders = true;
// draw columns
if (drawColumnHeaders)
{
Rectangle headerRect = e.ClipRectangle;
Columns.Draw(e.Graphics, headerRect, hScrollOffset);
}
int visibleRowIndex = 0;
TreeListColumn[] visibleColumns = this.Columns.VisibleColumns;
int columnsWidth = Columns.ColumnsWidth;
foreach (Node node in NodeCollection.ForwardNodeIterator(m_firstVisibleNode, true))
{
Rectangle rowRect = CalcRowRectangle(visibleRowIndex);
if (rowRect == Rectangle.Empty || rowRect.Bottom <= e.ClipRectangle.Top || rowRect.Top >= e.ClipRectangle.Bottom)
{
if (visibleRowIndex > visiblerows)
break;
visibleRowIndex++;
continue;
}
rowRect.X = RowHeaderWidth() - hScrollOffset;
rowRect.Width = columnsWidth;
// draw the current node
PaintNode(e.Graphics, rowRect, node, visibleColumns, visibleRowIndex);
// drow row header for current node
Rectangle headerRect = rowRect;
headerRect.X = 0;
headerRect.Width = RowHeaderWidth();
int absoluteRowIndex = visibleRowIndex + VScrollValue();
headerRect.Width = RowHeaderWidth();
m_rowPainter.DrawHeader(e.Graphics, headerRect, absoluteRowIndex == m_hotrow);
visibleRowIndex++;
}
visibleRowIndex = 0;
foreach (Node node in NodeCollection.ForwardNodeIterator(m_firstVisibleNode, true))
{
Rectangle rowRect = CalcRowRectangle(visibleRowIndex);
// draw horizontal grid line for current node
if (ViewOptions.ShowGridLines)
{
Rectangle r = rowRect;
r.X = RowHeaderWidth();
r.Width = columnsWidth - hScrollOffset;
m_rowPainter.DrawHorizontalGridLine(e.Graphics, r, GridLineColour);
}
visibleRowIndex++;
}
// draw vertical grid lines
if (ViewOptions.ShowGridLines)
{
// visible row count
int remainRows = Nodes.VisibleNodeCount - m_vScroll.Value;
if (visiblerows > remainRows)
visiblerows = remainRows;
Rectangle fullRect = ClientRectangle;
if (drawColumnHeaders)
fullRect.Y += Columns.Options.HeaderHeight;
fullRect.Height = visiblerows * RowOptions.ItemHeight;
Columns.Painter.DrawVerticalGridLines(Columns, e.Graphics, fullRect, hScrollOffset);
}
}
protected override bool IsInputKey(Keys keyData)
{
if ((int)(keyData & Keys.Shift) > 0)
return true;
switch (keyData)
{
case Keys.Left:
case Keys.Right:
case Keys.Down:
case Keys.Up:
case Keys.PageUp:
case Keys.PageDown:
case Keys.Home:
case Keys.End:
return true;
}
return false;
}
protected override void OnKeyDown(KeyEventArgs e)
{
Node newnode = null;
if (e.KeyCode == Keys.PageUp)
{
int remainder = 0;
int diff = MaxVisibleRows(out remainder)-1;
newnode = NodeCollection.GetNextNode(FocusedNode, -diff);
if (newnode == null)
newnode = Nodes.FirstVisibleNode();
}
if (e.KeyCode == Keys.PageDown)
{
int remainder = 0;
int diff = MaxVisibleRows(out remainder)-1;
newnode = NodeCollection.GetNextNode(FocusedNode, diff);
if (newnode == null)
newnode = Nodes.LastVisibleNode(true);
}
if (e.KeyCode == Keys.Down)
{
newnode = NodeCollection.GetNextNode(FocusedNode, 1);
}
if (e.KeyCode == Keys.Up)
{
newnode = NodeCollection.GetNextNode(FocusedNode, -1);
}
if (e.KeyCode == Keys.Home)
{
newnode = Nodes.FirstNode;
}
if (e.KeyCode == Keys.End)
{
newnode = Nodes.LastVisibleNode(true);
}
if (e.KeyCode == Keys.Left)
{
if (FocusedNode != null)
{
if (FocusedNode.Expanded)
{
FocusedNode.Collapse();
EnsureVisible(FocusedNode);
return;
}
if (FocusedNode.Parent != null)
{
FocusedNode = FocusedNode.Parent;
EnsureVisible(FocusedNode);
}
}
}
if (e.KeyCode == Keys.Right)
{
if (FocusedNode != null)
{
if (FocusedNode.Expanded == false && FocusedNode.HasChildren)
{
FocusedNode.Expand();
EnsureVisible(FocusedNode);
return;
}
if (FocusedNode.Expanded == true && FocusedNode.HasChildren)
{
FocusedNode = FocusedNode.Nodes.FirstNode;
EnsureVisible(FocusedNode);
}
}
}
if (newnode != null)
{
if (MultiSelect)
{
// tree behavior is
// keys none, the selected node is added as the focused and selected node
// keys control, only focused node is moved, the selected nodes collection is not modified
// keys shift, selection from first selected node to current node is done
if (Control.ModifierKeys == Keys.Control)
FocusedNode = newnode;
else
MultiSelectAdd(newnode, Control.ModifierKeys);
}
else
FocusedNode = newnode;
EnsureVisible(FocusedNode);
}
base.OnKeyDown(e);
}
internal void internalUpdateStyles()
{
base.UpdateStyles();
}
#region ISupportInitialize Members
public void BeginInit()
{
Columns.BeginInit();
}
public void EndInit()
{
Columns.EndInit();
}
#endregion
internal new bool DesignMode
{
get { return base.DesignMode; }
}
}
public class TreeListViewNodes : NodeCollection
{
TreeListView m_tree;
bool m_isUpdating = false;
public void BeginUpdate()
{
m_isUpdating = true;
}
public void EndUpdate()
{
m_isUpdating = false;
}
public TreeListViewNodes(TreeListView owner) : base(null)
{
m_tree = owner;
OwnerView = owner;
}
protected override void UpdateNodeCount(int oldvalue, int newvalue)
{
base.UpdateNodeCount(oldvalue, newvalue);
if (!m_isUpdating)
m_tree.RecalcLayout();
}
public override void Clear()
{
base.Clear();
m_tree.RecalcLayout();
}
public override void NodetifyBeforeExpand(Node nodeToExpand, bool expanding)
{
if (!m_tree.DesignMode)
m_tree.OnNotifyBeforeExpand(nodeToExpand, expanding);
}
public override void NodetifyAfterExpand(Node nodeToExpand, bool expanded)
{
m_tree.OnNotifyAfterExpand(nodeToExpand, expanded);
}
protected override int GetFieldIndex(string fieldname)
{
TreeListColumn col = m_tree.Columns[fieldname];
if (col != null)
return col.Index;
return -1;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Numerics;
using TensorFlow;
using System.Text;
using Xunit;
using Learn.Mnist;
namespace TensorFlowSharp.Tests.CSharp
{
public class TensorTests
{
private static IEnumerable<object []> jaggedData ()
{
yield return new object [] {
new double [][] { new [] { 1.0, 2.0 }, new [] { 3.0, 4.0 } },
new double [,] { { 1.0, 2.0}, { 3.0, 4.0 } },
true
};
yield return new object [] {
new double [][] { new [] { 1.0, 2.0 }, new [] { 1.0, 4.0 } },
new double [,] { { 1.0, 2.0}, { 3.0, 4.0 } },
false
};
yield return new object [] {
new double [][][] { new [] { new [] { 1.0 }, new[] { 2.0 } }, new [] { new [] { 3.0 }, new [] { 4.0 } } },
new double [,,] { { { 1.0 }, { 2.0 } }, { { 3.0 }, { 4.0 } } },
true
};
yield return new object [] {
new double [][][] { new [] { new [] { 1.0 }, new[] { 2.0 } }, new [] { new [] { 1.0 }, new [] { 4.0 } } },
new double [,,] { { { 1.0 }, { 2.0 } }, { { 3.0 }, { 4.0 } } },
false
};
}
[Theory]
[MemberData (nameof (jaggedData))]
public void Should_MultidimensionalAndJaggedBeEqual (Array jagged, Array multidimensional, bool expected)
{
using (var graph = new TFGraph ())
using (var session = new TFSession (graph)) {
var tjagged = graph.Const (new TFTensor (jagged));
var tmultidimensional = graph.Const (new TFTensor (multidimensional));
TFOutput y = graph.Equal (tjagged, tmultidimensional);
TFOutput r;
if (multidimensional.Rank == 2)
r = graph.All (y, graph.Const (new [] { 0, 1 }));
else if (multidimensional.Rank == 3)
r = graph.All (y, graph.Const (new [] { 0, 1, 2 }));
else
throw new System.Exception ("If you want to test Ranks > 3 please handle this extra case manually.");
TFTensor [] result = session.Run (new TFOutput [] { }, new TFTensor [] { }, new [] { r });
bool actual = (bool)result [0].GetValue ();
Assert.Equal (expected, actual);
}
}
[Fact]
public void StringTestWithMultiDimStringTensorAsInputOutput ()
{
using (var graph = new TFGraph ())
using (var session = new TFSession (graph))
{
var W = graph.Placeholder (TFDataType.String, new TFShape (-1, 2));
var identityW = graph.Identity (W);
var dataW = new string [,] { { "This is fine.", "That's ok." }, { "This is fine.", "That's ok." } };
var bytes = new byte [2 * 2] [];
bytes [0] = Encoding.UTF8.GetBytes (dataW [0, 0]);
bytes [1] = Encoding.UTF8.GetBytes (dataW [0, 1]);
bytes [2] = Encoding.UTF8.GetBytes (dataW [1, 0]);
bytes [3] = Encoding.UTF8.GetBytes (dataW [1, 1]);
var tensorW = TFTensor.CreateString (bytes, new TFShape (2, 2));
var outputTensor = session.Run (new TFOutput [] { W }, new TFTensor [] { tensorW }, new [] { identityW });
var outputW = TFTensor.DecodeMultiDimensionString (outputTensor [0]);
Assert.Equal (dataW [0, 0], Encoding.UTF8.GetString (outputW [0]));
Assert.Equal (dataW [0, 1], Encoding.UTF8.GetString (outputW [1]));
Assert.Equal (dataW [1, 0], Encoding.UTF8.GetString (outputW [2]));
Assert.Equal (dataW [1, 1], Encoding.UTF8.GetString (outputW [3]));
}
}
[Fact]
public void StringTestWithMultiDimStringTensorAsInputAndScalarStringAsOutput ()
{
using (var graph = new TFGraph ())
using (var session = new TFSession (graph))
{
var X = graph.Placeholder (TFDataType.String, new TFShape (-1));
var delimiter = graph.Const (TFTensor.CreateString (Encoding.UTF8.GetBytes ("/")));
var indices = graph.Const (0);
var Y = graph.ReduceJoin (graph.StringSplit (X, delimiter).values, indices, separator: " ");
var dataX = new string [] { "Thank/you/very/much!.", "I/am/grateful/to/you.", "So/nice/of/you." };
var bytes = new byte [dataX.Length] [];
bytes [0] = Encoding.UTF8.GetBytes (dataX [0]);
bytes [1] = Encoding.UTF8.GetBytes (dataX [1]);
bytes [2] = Encoding.UTF8.GetBytes (dataX [2]);
var tensorX = TFTensor.CreateString (bytes, new TFShape (3));
var outputTensors = session.Run (new TFOutput [] { X }, new TFTensor [] { tensorX }, new [] { Y });
var outputY = Encoding.UTF8.GetString (TFTensor.DecodeString (outputTensors [0]));
Assert.Equal (string.Join (" ", dataX).Replace ("/", " "), outputY);
}
}
[Fact (Skip = "Disabled because it requires GPUs and need to set numGPUs to available GPUs on system." +
" It has been tested on GPU machine with 4 GPUs and it passed there.")]
public void DevicePlacementTest ()
{
using (var graph = new TFGraph ())
using (var session = new TFSession (graph))
{
var X = graph.Placeholder (TFDataType.Float, new TFShape (-1, 784));
var Y = graph.Placeholder (TFDataType.Float, new TFShape (-1, 10));
int numGPUs = 4;
var Xs = graph.Split (graph.Const (0), X, numGPUs);
var Ys = graph.Split (graph.Const (0), Y, numGPUs);
var products = new TFOutput [numGPUs];
for (int i = 0; i < numGPUs; i++)
{
using (var device = graph.WithDevice ("/device:GPU:" + i))
{
var W = graph.Constant (0.1f, new TFShape (784, 500), TFDataType.Float);
var b = graph.Constant (0.1f, new TFShape (500), TFDataType.Float);
products [i] = graph.Add (graph.MatMul (Xs [i], W), b);
}
}
var stacked = graph.Concat (graph.Const (0), products);
Mnist mnist = new Mnist ();
mnist.ReadDataSets ("/tmp");
int batchSize = 1000;
for (int i = 0; i < 100; i++)
{
var reader = mnist.GetTrainReader ();
(var trainX, var trainY) = reader.NextBatch (batchSize);
var outputTensors = session.Run (new TFOutput [] { X }, new TFTensor [] { new TFTensor (trainX) }, new TFOutput [] { stacked });
Assert.Equal (1000, outputTensors [0].Shape [0]);
Assert.Equal (500, outputTensors [0].Shape [1]);
}
}
}
[Fact]
public void ConstructBoolTensor ()
{
bool value = true;
using (var tensor = new TFTensor (value))
{
Assert.Equal (TFDataType.Bool, tensor.TensorType);
Assert.Equal (0, tensor.NumDims);
Assert.Equal (new long [0], tensor.Shape);
Assert.Equal ((uint)sizeof (bool), tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (value, tensor.GetValue ());
}
}
[Fact]
public void ConstructByteTensor ()
{
byte value = 123;
using (var tensor = new TFTensor (value))
{
Assert.Equal (TFDataType.UInt8, tensor.TensorType);
Assert.Equal (0, tensor.NumDims);
Assert.Equal (new long [0], tensor.Shape);
Assert.Equal ((uint)sizeof (byte), tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (value, tensor.GetValue ());
}
}
[Fact]
public void ConstructSignedByteTensor ()
{
sbyte value = 123;
using (var tensor = new TFTensor (value))
{
Assert.Equal (TFDataType.Int8, tensor.TensorType);
Assert.Equal (0, tensor.NumDims);
Assert.Equal (new long [0], tensor.Shape);
Assert.Equal ((uint)sizeof (sbyte), tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (value, tensor.GetValue ());
}
}
[Fact]
public void ConstructShortTensor ()
{
short value = 123;
using (var tensor = new TFTensor (value))
{
Assert.Equal (TFDataType.Int16, tensor.TensorType);
Assert.Equal (0, tensor.NumDims);
Assert.Equal (new long [0], tensor.Shape);
Assert.Equal ((uint)sizeof (short), tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (value, tensor.GetValue ());
}
}
[Fact]
public void ConstructUnsignedShortTensor ()
{
ushort value = 123;
using (var tensor = new TFTensor (value))
{
Assert.Equal (TFDataType.UInt16, tensor.TensorType);
Assert.Equal (0, tensor.NumDims);
Assert.Equal (new long [0], tensor.Shape);
Assert.Equal ((uint)sizeof (ushort), tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (value, tensor.GetValue ());
}
}
[Fact]
public void ConstructIntTensor ()
{
int value = 123;
using (var tensor = new TFTensor (value))
{
Assert.Equal (TFDataType.Int32, tensor.TensorType);
Assert.Equal (0, tensor.NumDims);
Assert.Equal (new long [0], tensor.Shape);
Assert.Equal ((uint)sizeof (int), tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (value, tensor.GetValue ());
}
}
[Fact]
public void ConstructLongTensor ()
{
long value = 123L;
using (var tensor = new TFTensor (value))
{
Assert.Equal (TFDataType.Int64, tensor.TensorType);
Assert.Equal (0, tensor.NumDims);
Assert.Equal (new long [0], tensor.Shape);
Assert.Equal ((uint)sizeof (long), tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (value, tensor.GetValue ());
}
}
[Fact]
public void ConstructComplexTensor ()
{
Complex value = new Complex (1, 2);
using (var tensor = new TFTensor (value))
{
Assert.Equal (TFDataType.Complex128, tensor.TensorType);
Assert.Equal (0, tensor.NumDims);
Assert.Equal (new long [0], tensor.Shape);
Assert.Equal (16u, tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (value, tensor.GetValue ());
}
}
[Fact]
public void ConstructFloatTensor ()
{
float value = 123.456f;
using (var tensor = new TFTensor (value))
{
Assert.Equal (TFDataType.Float, tensor.TensorType);
Assert.Equal (0, tensor.NumDims);
Assert.Equal (new long [0], tensor.Shape);
Assert.Equal ((uint)sizeof (float), tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (value, tensor.GetValue ());
}
}
[Fact]
public void ConstructDoubleTensor ()
{
double value = 123.456;
using (var tensor = new TFTensor (value))
{
Assert.Equal (TFDataType.Double, tensor.TensorType);
Assert.Equal (0, tensor.NumDims);
Assert.Equal (new long [0], tensor.Shape);
Assert.Equal ((uint)sizeof (double), tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (value, tensor.GetValue ());
}
}
[Fact]
public void ConstructBoolArrayTensor ()
{
var array = new [] { true, false };
using (var tensor = new TFTensor (array))
{
Assert.Equal (TFDataType.Bool, tensor.TensorType);
Assert.Equal (array.Rank, tensor.NumDims);
Assert.Equal (array.Length, tensor.GetTensorDimension (0));
Assert.Equal (new long [] { array.Length }, tensor.Shape);
Assert.Equal ((uint)sizeof (bool) * array.Length, tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (array, tensor.GetValue ());
}
}
[Fact]
public void ConstructByteArrayTensor ()
{
var array = new byte [] { 123, 234 };
using (var tensor = new TFTensor (array))
{
Assert.Equal (TFDataType.UInt8, tensor.TensorType);
Assert.Equal (array.Rank, tensor.NumDims);
Assert.Equal (array.Length, tensor.GetTensorDimension (0));
Assert.Equal (new long [] { array.Length }, tensor.Shape);
Assert.Equal ((uint)sizeof (byte) * array.Length, tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (array, tensor.GetValue ());
}
}
[Fact]
public void ConstructSignedByteArrayTensor ()
{
var array = new sbyte [] { 123, -123 };
using (var tensor = new TFTensor (array))
{
Assert.Equal (TFDataType.Int8, tensor.TensorType);
Assert.Equal (array.Rank, tensor.NumDims);
Assert.Equal (array.Length, tensor.GetTensorDimension (0));
Assert.Equal (new long [] { array.Length }, tensor.Shape);
Assert.Equal ((uint)sizeof (sbyte) * array.Length, tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (array, tensor.GetValue ());
}
}
[Fact]
public void ConstructShortArrayTensor ()
{
var array = new short [] { 123, 234 };
using (var tensor = new TFTensor (array))
{
Assert.Equal (TFDataType.Int16, tensor.TensorType);
Assert.Equal (array.Rank, tensor.NumDims);
Assert.Equal (array.Length, tensor.GetTensorDimension (0));
Assert.Equal (new long [] { array.Length }, tensor.Shape);
Assert.Equal ((uint)sizeof (short) * array.Length, tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (array, tensor.GetValue ());
}
}
[Fact]
public void ConstructUnsignedShortArrayTensor ()
{
var array = new ushort [] { 123, 234 };
using (var tensor = new TFTensor (array))
{
Assert.Equal (TFDataType.UInt16, tensor.TensorType);
Assert.Equal (array.Rank, tensor.NumDims);
Assert.Equal (array.Length, tensor.GetTensorDimension (0));
Assert.Equal (new long [] { array.Length }, tensor.Shape);
Assert.Equal ((uint)sizeof (ushort) * array.Length, tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (array, tensor.GetValue ());
}
}
[Fact]
public void ConstructIntArrayTensor ()
{
var array = new [] { 123, 234 };
using (var tensor = new TFTensor (array))
{
Assert.Equal (TFDataType.Int32, tensor.TensorType);
Assert.Equal (array.Rank, tensor.NumDims);
Assert.Equal (array.Length, tensor.GetTensorDimension (0));
Assert.Equal (new long [] { array.Length }, tensor.Shape);
Assert.Equal ((uint)sizeof (int) * array.Length, tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (array, tensor.GetValue ());
}
}
[Fact]
public void ConstructMultiDimIntArrayTensor ()
{
var array = new [,] { { 123, 456 } };
using (var tensor = new TFTensor (array))
{
Assert.Equal (TFDataType.Int32, tensor.TensorType);
Assert.Equal (array.Rank, tensor.NumDims);
Assert.Equal (array.GetLength (0), tensor.GetTensorDimension (0));
Assert.Equal (array.GetLength (1), tensor.GetTensorDimension (1));
Assert.Equal (new long [] { array.GetLength (0), array.GetLength (1) }, tensor.Shape);
Assert.Equal ((uint)sizeof (int) * array.Length, tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (array, tensor.GetValue ());
}
}
[Fact]
public void ConstructJaggedIntArrayTensor ()
{
var jagged = new [] { new [] { 123, 456 } };
var array = new [,] { { 123, 456 } };
using (var tensor = new TFTensor (jagged))
{
Assert.Equal (TFDataType.Int32, tensor.TensorType);
Assert.Equal (2, tensor.NumDims);
Assert.Equal (array.GetLength (0), tensor.GetTensorDimension (0));
Assert.Equal (array.GetLength (1), tensor.GetTensorDimension (1));
Assert.Equal (new long [] { array.GetLength (0), array.GetLength (1) }, tensor.Shape);
Assert.Equal ((uint)sizeof (int) * array.Length, tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (array, tensor.GetValue ());
}
}
[Fact]
public void ConstructLongArrayTensor ()
{
var array = new [] { 123L, 234L };
using (var tensor = new TFTensor (array))
{
Assert.Equal (TFDataType.Int64, tensor.TensorType);
Assert.Equal (array.Rank, tensor.NumDims);
Assert.Equal (array.Length, tensor.GetTensorDimension (0));
Assert.Equal (new long [] { array.Length }, tensor.Shape);
Assert.Equal ((uint)sizeof (long) * array.Length, tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (array, tensor.GetValue ());
}
}
[Fact]
public void ConstrucComplexArrayTensor ()
{
var array = new [] { new Complex (1, 2), new Complex (2, -1) };
using (var tensor = new TFTensor (array))
{
Assert.Equal (TFDataType.Complex128, tensor.TensorType);
Assert.Equal (array.Rank, tensor.NumDims);
Assert.Equal (array.Length, tensor.GetTensorDimension (0));
Assert.Equal (new long [] { array.Length }, tensor.Shape);
Assert.Equal (16u * array.Length, tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (array, tensor.GetValue ());
}
}
[Fact]
public void ConstructFloatArrayTensor ()
{
var array = new [] { 123.456f, 234.567f };
using (var tensor = new TFTensor (array))
{
Assert.Equal (TFDataType.Float, tensor.TensorType);
Assert.Equal (array.Rank, tensor.NumDims);
Assert.Equal (array.Length, tensor.GetTensorDimension (0));
Assert.Equal (new long [] { array.Length }, tensor.Shape);
Assert.Equal ((uint)sizeof (float) * array.Length, tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (array, tensor.GetValue ());
}
}
[Fact]
public void ConstructDoubleArrayTensor ()
{
var array = new [] { 123.456, 234.567 };
using (var tensor = new TFTensor (array))
{
Assert.Equal (TFDataType.Double, tensor.TensorType);
Assert.Equal (array.Rank, tensor.NumDims);
Assert.Equal (array.Length, tensor.GetTensorDimension (0));
Assert.Equal (new long [] { array.Length }, tensor.Shape);
Assert.Equal ((uint)sizeof (double) * array.Length, tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (array, tensor.GetValue ());
}
}
[Fact]
public void SetArrayTensor ()
{
using (var tensor = new TFTensor (new [] { 123, 456 }))
{
tensor.SetValue (new [] { 234, 567 });
Assert.Equal ((uint)sizeof (int) * 2, tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (new [] { 234, 567 }, tensor.GetValue ());
}
}
[Fact]
public void SetMultiDimArrayTensor ()
{
using (var tensor = new TFTensor (new [,] { { 123, 456 } }))
{
tensor.SetValue (new [,] { { 234, 567 } });
Assert.Equal ((uint)sizeof (int) * 2, tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (new [,] { { 234, 567 } }, tensor.GetValue ());
}
}
[Fact]
public void SetMultiDimArrayTensorWithJagged ()
{
using (var tensor = new TFTensor (new [,] { { 123, 456 } }))
{
tensor.SetValue (new [] { new [] { 234, 567 } });
Assert.Equal ((uint)sizeof (int) * 2, tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (new [,] { { 234, 567 } }, tensor.GetValue ());
}
}
[Fact]
public void SetJaggedArrayTensor ()
{
using (var tensor = new TFTensor (new [] { new [] { 123, 456 } }))
{
tensor.SetValue (new [] { new [] { 234, 567 } });
Assert.Equal ((uint)sizeof (int) * 2, tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (new [,] { { 234, 567 } }, tensor.GetValue ());
}
}
[Fact]
public void SetBoolTensor ()
{
using (var tensor = new TFTensor (true))
{
tensor.SetValue (false);
Assert.Equal ((uint)sizeof (bool), tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (false, tensor.GetValue ());
}
}
[Fact]
public void SetByteTensor ()
{
using (var tensor = new TFTensor ((byte)123))
{
tensor.SetValue ((byte)234);
Assert.Equal ((uint)sizeof (byte), tensor.TensorByteSize.ToUInt32 ());
Assert.Equal ((byte)234, tensor.GetValue ());
}
}
[Fact]
public void SetSignedByteTensor ()
{
using (var tensor = new TFTensor ((sbyte)123))
{
tensor.SetValue ((sbyte)-123);
Assert.Equal ((uint)sizeof (sbyte), tensor.TensorByteSize.ToUInt32 ());
Assert.Equal ((sbyte)-123, tensor.GetValue ());
}
}
[Fact]
public void SetShortTensor ()
{
using (var tensor = new TFTensor ((short)123))
{
tensor.SetValue ((short)234);
Assert.Equal ((uint)sizeof (short), tensor.TensorByteSize.ToUInt32 ());
Assert.Equal ((short)234, tensor.GetValue ());
}
}
[Fact]
public void SetUnsignedShortTensor ()
{
using (var tensor = new TFTensor ((ushort)123))
{
tensor.SetValue ((ushort)234);
Assert.Equal ((uint)sizeof (ushort), tensor.TensorByteSize.ToUInt32 ());
Assert.Equal ((ushort)234, tensor.GetValue ());
}
}
[Fact]
public void SetIntTensor ()
{
using (var tensor = new TFTensor (123))
{
tensor.SetValue (234);
Assert.Equal ((uint)sizeof (int), tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (234, tensor.GetValue ());
}
}
[Fact]
public void SetLongTensor ()
{
using (var tensor = new TFTensor (123L))
{
tensor.SetValue (234L);
Assert.Equal ((uint)sizeof (long), tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (234L, tensor.GetValue ());
}
}
[Fact]
public void SetComplexTensor ()
{
using (var tensor = new TFTensor (new Complex (1, 2)))
{
tensor.SetValue (new Complex (2, -1));
Assert.Equal ((uint)16, tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (new Complex (2, -1), tensor.GetValue ());
}
}
[Fact]
public void SetFloatTensor ()
{
using (var tensor = new TFTensor (123.456f))
{
tensor.SetValue (234.567f);
Assert.Equal ((uint)sizeof (float), tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (234.567f, tensor.GetValue ());
}
}
[Fact]
public void SetDoubleTensor ()
{
using (var tensor = new TFTensor (123.456))
{
tensor.SetValue (234.567);
Assert.Equal ((uint)sizeof (double), tensor.TensorByteSize.ToUInt32 ());
Assert.Equal (234.567, tensor.GetValue ());
}
}
[Fact]
public void SetTensorWithWrongType ()
{
using (var tensor = new TFTensor (123))
{
var exception = Assert.Throws<ArgumentException> (() => tensor.SetValue ((ushort)234));
Assert.Equal ("The tensor is of type Int32, not UInt16", exception.Message);
}
}
[Fact]
public void SetArrayTensorWithSimple ()
{
using (var tensor = new TFTensor (new [] { 123 }))
{
var exception = Assert.Throws<ArgumentException> (() => tensor.SetValue (234));
Assert.Equal ("This tensor is an array tensor, not a simple tensor", exception.Message);
}
}
[Fact]
public void SetArrayTensorWithWrongDimensions ()
{
using (var tensor = new TFTensor (new [,] { { 123 } }))
{
var exception = Assert.Throws<ArgumentException> (() => tensor.SetValue (new [] { 234 }));
Assert.Equal ("This tensor has 2 dimensions, the given array has 1", exception.Message);
}
}
[Fact]
public void SetArrayTensorWithWrongLength ()
{
using (var tensor = new TFTensor (new [,] { { 123 } }))
{
var exception = Assert.Throws<ArgumentException> (() => tensor.SetValue (new [,] { { 234, 567 } }));
Assert.Equal ("This tensor has shape [1,1], the given array has shape [1,2]", exception.Message);
}
}
[Fact]
public void SetJaggedArrayTensorWithWrongDimensions ()
{
using (var tensor = new TFTensor (new [] { new [] { 123 } }))
{
var exception = Assert.Throws<ArgumentException> (() => tensor.SetValue (new [] { new [] { new [] { 234 } } }));
Assert.Equal ("This tensor has 2 dimensions, the given array has 3", exception.Message);
}
}
[Fact]
public void SetJaggedArrayTensorWithWrongLength ()
{
using (var tensor = new TFTensor (new [] { new [] { 123 } }))
{
var exception = Assert.Throws<ArgumentException> (() => tensor.SetValue (new [] { new [] { 234, 567 } }));
Assert.Equal ("This tensor has shape [1,1], given array has shape [1,2]", exception.Message);
}
}
public static IEnumerable<object []> GetArrayValueInPlaceData => new List<object []>
{
new [] { new [] { 123 } },
new [] { new [,] { { 123, 456 } } },
new [] { new [,,] { { { 123, 456, 789 } } } },
new [] { new [,] { { 123, 456 }, { 789, 012 } } }
};
[Theory]
[MemberData(nameof(GetArrayValueInPlaceData))]
public void GetArrayValueInPlace (Array array)
{
using (var tensor = new TFTensor (array))
{
var type = array.GetType ().GetElementType ();
var value = Array.CreateInstance (type, tensor.Shape);
Assert.NotEqual (array, value);
tensor.GetValue (value);
Assert.Equal (array, value);
}
}
private static IEnumerable<object []> checkShapeData ()
{
yield return new object [] { new [] { 123 }, new [] { 234 }, null };
yield return new object [] { new [] { 123 }, new [,] { { 234 } }, "This tensor has 1 dimensions, the given array has 2" };
yield return new object [] { new [] { 123 }, new [] { 234, 567 }, "This tensor has shape [1], the given array has shape [2]" };
yield return new object [] { new [] { 123, 456 }, new [] { 234, 567 }, null };
yield return new object [] { new [] { 123, 456 }, new [,] { { 234, 567 } }, "This tensor has 1 dimensions, the given array has 2" };
yield return new object [] { new [] { 123, 456 }, new [] { 234 }, "This tensor has shape [2], the given array has shape [1]" };
yield return new object [] { new [,] { { 123 } }, new [,] { { 234 } }, null };
yield return new object [] { new [,] { { 123 } }, new [] { 234 }, "This tensor has 2 dimensions, the given array has 1" };
yield return new object [] { new [,] { { 123 } }, new [,] { { 234, 567 } }, "This tensor has shape [1,1], the given array has shape [1,2]" };
yield return new object [] { new [,] { { 123, 456 }, { 789, 012 } }, new [,] { { 234, 567 }, { 890, 123 } }, null };
yield return new object [] { new [,] { { 123, 456 }, { 789, 012 } }, new [] { 234, 567 }, "This tensor has 2 dimensions, the given array has 1" };
yield return new object [] { new [,] { { 123, 456 }, { 789, 012 } }, new [,] { { 234 }, { 890 } }, "This tensor has shape [2,2], the given array has shape [2,1]" };
}
[Theory]
[MemberData (nameof (checkShapeData))]
public void CheckShape (Array tensorArray, Array checkArray, String expected)
{
using (var tensor = new TFTensor (tensorArray))
AssertCheck (() => tensor.CheckShape (checkArray), expected);
}
[Fact]
public void CheckShapeOnSimpleTensor ()
{
using (var tensor = new TFTensor (123))
{
var exception = Assert.Throws<ArgumentException> (() => tensor.CheckShape (new [] { 123 }));
Assert.Equal ("This tensor has 0 dimensions, the given array has 1", exception.Message);
}
}
private static IEnumerable<object []> checkSimpleDataTypeData ()
{
yield return new object [] { typeof (int), null };
yield return new object [] { typeof (short), "The tensor is of type Int32, not Int16" };
yield return new object [] { typeof (byte), "The tensor is of type Int32, not UInt8" };
}
[Theory]
[MemberData (nameof (checkSimpleDataTypeData))]
public void CheckSimpleDataType (Type type, String expected)
{
using (var tensor = new TFTensor (123))
AssertCheck(() => tensor.CheckSimpleDataType (type), expected);
}
[Fact]
public void CheckSimpleDataTypeWithArray ()
{
using (var tensor = new TFTensor (123))
{
var exception = Assert.Throws<InvalidOperationException> (() => tensor.CheckSimpleDataType (typeof (Array)));
Assert.Equal ("An array is not a simple type, use CheckDataTypeAndSize(Type type, long length)", exception.Message);
}
}
[Fact]
public void CheckSimpleDataTypeOnArrayTensor ()
{
using (var tensor = new TFTensor (new [] { 123 }))
{
var exception = Assert.Throws<ArgumentException> (() => tensor.CheckSimpleDataType (typeof (int)));
Assert.Equal ("This tensor is an array tensor, not a simple tensor", exception.Message);
}
}
private static IEnumerable<object []> checkDataTypeAndSizeData ()
{
yield return new object [] { new TFTensor (123), typeof (int), 1, null };
yield return new object [] { new TFTensor (123), typeof (short), 1, "The tensor is of type Int32, not Int16" };
yield return new object [] { new TFTensor (123), typeof (byte), 1, "The tensor is of type Int32, not UInt8" };
yield return new object [] { new TFTensor (new [] { 123 }), typeof (int), 1, null };
yield return new object [] { new TFTensor (new [] { 123, 456 }), typeof (int), 2, null };
yield return new object [] { new TFTensor (new [] { 123, 456, 789 }), typeof (int), 2, "The tensor is of size 12, not 8" };
yield return new object [] { new TFTensor (new short [] { 123 }), typeof (ushort), 1, "The tensor is of type Int16, not UInt16" };
}
[Theory]
[MemberData (nameof (checkDataTypeAndSizeData))]
public void CheckDataTypeAndSize (TFTensor tensor, Type type, long length, String expected)
{
using (tensor)
AssertCheck(() => tensor.CheckDataTypeAndSize(type, length), expected);
}
public void AssertCheck (Action check, string expected)
{
if (expected == null)
{
check ();
}
else
{
var exception = Assert.Throws<ArgumentException> (check);
Assert.Equal (expected, exception.Message);
}
}
}
}
| |
// 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 RoundToZeroDouble()
{
var test = new SimpleUnaryOpTest__RoundToZeroDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.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 (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.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 (Sse2.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 (Sse2.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 (Sse2.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 SimpleUnaryOpTest__RoundToZeroDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.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<Double> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__RoundToZeroDouble testClass)
{
var result = Sse41.RoundToZero(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__RoundToZeroDouble testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
{
var result = Sse41.RoundToZero(
Sse2.LoadVector128((Double*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Vector128<Double> _clsVar1;
private Vector128<Double> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__RoundToZeroDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleUnaryOpTest__RoundToZeroDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.RoundToZero(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.RoundToZero(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.RoundToZero(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToZero), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToZero), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToZero), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.RoundToZero(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
{
var result = Sse41.RoundToZero(
Sse2.LoadVector128((Double*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var result = Sse41.RoundToZero(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var result = Sse41.RoundToZero(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var result = Sse41.RoundToZero(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__RoundToZeroDouble();
var result = Sse41.RoundToZero(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__RoundToZeroDouble();
fixed (Vector128<Double>* pFld1 = &test._fld1)
{
var result = Sse41.RoundToZero(
Sse2.LoadVector128((Double*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.RoundToZero(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
{
var result = Sse41.RoundToZero(
Sse2.LoadVector128((Double*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.RoundToZero(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse41.RoundToZero(
Sse2.LoadVector128((Double*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _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<Double> op1, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits((firstOp[0] > 0) ? Math.Floor(firstOp[0]) : Math.Ceiling(firstOp[0])))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits((firstOp[i] > 0) ? Math.Floor(firstOp[i]) : Math.Ceiling(firstOp[i])))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.RoundToZero)}<Double>(Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using System.IO;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using Xunit;
namespace Microsoft.Framework.WebEncoders
{
public class JavaScriptStringEncoderTests
{
[Fact]
public void TestSurrogate()
{
Assert.Equal("\\uD83D\\uDCA9", System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode("\U0001f4a9"));
using (var writer = new StringWriter())
{
System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode(writer, "\U0001f4a9");
Assert.Equal("\\uD83D\\uDCA9", writer.GetStringBuilder().ToString());
}
}
[Fact]
public void Ctor_WithTextEncoderSettings()
{
// Arrange
var filter = new TextEncoderSettings();
filter.AllowCharacters('a', 'b');
filter.AllowCharacters('\0', '&', '\uFFFF', 'd');
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(filter);
// Act & assert
Assert.Equal("a", encoder.JavaScriptStringEncode("a"));
Assert.Equal("b", encoder.JavaScriptStringEncode("b"));
Assert.Equal(@"\u0063", encoder.JavaScriptStringEncode("c"));
Assert.Equal("d", encoder.JavaScriptStringEncode("d"));
Assert.Equal(@"\u0000", encoder.JavaScriptStringEncode("\0")); // we still always encode control chars
Assert.Equal(@"\u0026", encoder.JavaScriptStringEncode("&")); // we still always encode HTML-special chars
Assert.Equal(@"\uFFFF", encoder.JavaScriptStringEncode("\uFFFF")); // we still always encode non-chars and other forbidden chars
}
[Fact]
public void Ctor_WithUnicodeRanges()
{
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(UnicodeRanges.Latin1Supplement, UnicodeRanges.MiscellaneousSymbols);
// Act & assert
Assert.Equal(@"\u0061", encoder.JavaScriptStringEncode("a"));
Assert.Equal("\u00E9", encoder.JavaScriptStringEncode("\u00E9" /* LATIN SMALL LETTER E WITH ACUTE */));
Assert.Equal("\u2601", encoder.JavaScriptStringEncode("\u2601" /* CLOUD */));
}
[Fact]
public void Ctor_WithNoParameters_DefaultsToBasicLatin()
{
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder();
// Act & assert
Assert.Equal("a", encoder.JavaScriptStringEncode("a"));
Assert.Equal(@"\u00E9", encoder.JavaScriptStringEncode("\u00E9" /* LATIN SMALL LETTER E WITH ACUTE */));
Assert.Equal(@"\u2601", encoder.JavaScriptStringEncode("\u2601" /* CLOUD */));
}
[Fact]
public void Default_EquivalentToBasicLatin()
{
// Arrange
JavaScriptStringEncoder controlEncoder = new JavaScriptStringEncoder(UnicodeRanges.BasicLatin);
JavaScriptStringEncoder testEncoder = JavaScriptStringEncoder.Default;
// Act & assert
for (int i = 0; i <= Char.MaxValue; i++)
{
if (!IsSurrogateCodePoint(i))
{
string input = new String((char)i, 1);
Assert.Equal(controlEncoder.JavaScriptStringEncode(input), testEncoder.JavaScriptStringEncode(input));
}
}
}
[Fact]
public void JavaScriptStringEncode_AllRangesAllowed_StillEncodesForbiddenChars_Simple_Escaping() {
// The following two calls could be simply InlineData to the Theory below
// Unfortunately, the xUnit logger fails to escape the inputs when logging the test results,
// and so the suite fails despite all tests passing.
// TODO: I will try to fix it in xUnit, but for now this is a workaround to enable these tests.
JavaScriptStringEncode_AllRangesAllowed_StillEncodesForbiddenChars_Simple("\b", @"\b");
JavaScriptStringEncode_AllRangesAllowed_StillEncodesForbiddenChars_Simple("\f", @"\f");
}
[Theory]
[InlineData("<", @"\u003C")]
[InlineData(">", @"\u003E")]
[InlineData("&", @"\u0026")]
[InlineData("'", @"\u0027")]
[InlineData("\"", @"\u0022")]
[InlineData("+", @"\u002B")]
[InlineData("\\", @"\\")]
[InlineData("/", @"\/")]
[InlineData("\n", @"\n")]
[InlineData("\t", @"\t")]
[InlineData("\r", @"\r")]
public void JavaScriptStringEncode_AllRangesAllowed_StillEncodesForbiddenChars_Simple(string input, string expected)
{
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(UnicodeRanges.All);
// Act
string retVal = encoder.JavaScriptStringEncode(input);
// Assert
Assert.Equal(expected, retVal);
}
[Fact]
public void JavaScriptStringEncode_AllRangesAllowed_StillEncodesForbiddenChars_Extended()
{
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(UnicodeRanges.All);
// Act & assert - BMP chars
for (int i = 0; i <= 0xFFFF; i++)
{
string input = new String((char)i, 1);
string expected;
if (IsSurrogateCodePoint(i))
{
expected = "\uFFFD"; // unpaired surrogate -> Unicode replacement char
}
else
{
if (input == "\b") { expected = @"\b"; }
else if (input == "\t") { expected = @"\t"; }
else if (input == "\n") { expected = @"\n"; }
else if (input == "\f") { expected = @"\f"; }
else if (input == "\r") { expected = @"\r"; }
else if (input == "\\") { expected = @"\\"; }
else if (input == "/") { expected = @"\/"; }
else if (input == "`") { expected = @"\u0060"; }
else
{
bool mustEncode = false;
switch (i)
{
case '<':
case '>':
case '&':
case '\"':
case '\'':
case '+':
mustEncode = true;
break;
}
if (i <= 0x001F || (0x007F <= i && i <= 0x9F))
{
mustEncode = true; // control char
}
else if (!UnicodeHelpers.IsCharacterDefined((char)i))
{
mustEncode = true; // undefined (or otherwise disallowed) char
}
if (mustEncode)
{
expected = String.Format(CultureInfo.InvariantCulture, @"\u{0:X4}", i);
}
else
{
expected = input; // no encoding
}
}
}
string retVal = encoder.JavaScriptStringEncode(input);
Assert.Equal(expected, retVal);
}
// Act & assert - astral chars
for (int i = 0x10000; i <= 0x10FFFF; i++)
{
string input = Char.ConvertFromUtf32(i);
string expected = String.Format(CultureInfo.InvariantCulture, @"\u{0:X4}\u{1:X4}", (uint)input[0], (uint)input[1]);
string retVal = encoder.JavaScriptStringEncode(input);
Assert.Equal(expected, retVal);
}
}
[Fact]
public void JavaScriptStringEncode_BadSurrogates_ReturnsUnicodeReplacementChar()
{
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(UnicodeRanges.All); // allow all codepoints
// "a<unpaired leading>b<unpaired trailing>c<trailing before leading>d<unpaired trailing><valid>e<high at end of string>"
const string input = "a\uD800b\uDFFFc\uDFFF\uD800d\uDFFF\uD800\uDFFFe\uD800";
const string expected = "a\uFFFDb\uFFFDc\uFFFD\uFFFDd\uFFFD\\uD800\\uDFFFe\uFFFD"; // 'D800' 'DFFF' was preserved since it's valid
// Act
string retVal = encoder.JavaScriptStringEncode(input);
// Assert
Assert.Equal(expected, retVal);
}
[Fact]
public void JavaScriptStringEncode_EmptyStringInput_ReturnsEmptyString()
{
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder();
// Act & assert
Assert.Equal("", encoder.JavaScriptStringEncode(""));
}
[Fact]
public void JavaScriptStringEncode_InputDoesNotRequireEncoding_ReturnsOriginalStringInstance()
{
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder();
string input = "Hello, there!";
// Act & assert
Assert.Same(input, encoder.JavaScriptStringEncode(input));
}
[Fact]
public void JavaScriptStringEncode_NullInput_Throws()
{
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder();
Assert.Throws<ArgumentNullException>(() => { encoder.JavaScriptStringEncode(null); });
}
[Fact]
public void JavaScriptStringEncode_WithCharsRequiringEncodingAtBeginning()
{
Assert.Equal(@"\u0026Hello, there!", new JavaScriptStringEncoder().JavaScriptStringEncode("&Hello, there!"));
}
[Fact]
public void JavaScriptStringEncode_WithCharsRequiringEncodingAtEnd()
{
Assert.Equal(@"Hello, there!\u0026", new JavaScriptStringEncoder().JavaScriptStringEncode("Hello, there!&"));
}
[Fact]
public void JavaScriptStringEncode_WithCharsRequiringEncodingInMiddle()
{
Assert.Equal(@"Hello, \u0026there!", new JavaScriptStringEncoder().JavaScriptStringEncode("Hello, &there!"));
}
[Fact]
public void JavaScriptStringEncode_WithCharsRequiringEncodingInterspersed()
{
Assert.Equal(@"Hello, \u003Cthere\u003E!", new JavaScriptStringEncoder().JavaScriptStringEncode("Hello, <there>!"));
}
[Fact]
public void JavaScriptStringEncode_CharArray()
{
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder();
var output = new StringWriter();
// Act
encoder.JavaScriptStringEncode("Hello+world!".ToCharArray(), 3, 5, output);
// Assert
Assert.Equal(@"lo\u002Bwo", output.ToString());
}
[Fact]
public void JavaScriptStringEncode_StringSubstring()
{
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder();
var output = new StringWriter();
// Act
encoder.JavaScriptStringEncode("Hello+world!", 3, 5, output);
// Assert
Assert.Equal(@"lo\u002Bwo", output.ToString());
}
[Theory]
[InlineData("\"", @"\u0022")]
[InlineData("'", @"\u0027")]
public void JavaScriptStringEncode_Quotes(string input, string expected)
{
// Per the design document, we provide additional defense-in-depth
// against breaking out of HTML attributes by having the encoders
// never emit the ' or " characters. This means that we want to
// \u-escape these characters instead of using \' and \".
// Arrange
JavaScriptStringEncoder encoder = new JavaScriptStringEncoder(UnicodeRanges.All);
// Act
string retVal = encoder.JavaScriptStringEncode(input);
// Assert
Assert.Equal(expected, retVal);
}
[Fact]
public void JavaScriptStringEncode_DoesNotOutputHtmlSensitiveCharacters()
{
// Per the design document, we provide additional defense-in-depth
// by never emitting HTML-sensitive characters unescaped.
// Arrange
JavaScriptStringEncoder javaScriptStringEncoder = new JavaScriptStringEncoder(UnicodeRanges.All);
HtmlEncoder htmlEncoder = new HtmlEncoder(UnicodeRanges.All);
// Act & assert
for (int i = 0; i <= 0x10FFFF; i++)
{
if (IsSurrogateCodePoint(i))
{
continue; // surrogates don't matter here
}
string javaScriptStringEncoded = javaScriptStringEncoder.JavaScriptStringEncode(Char.ConvertFromUtf32(i));
string thenHtmlEncoded = htmlEncoder.HtmlEncode(javaScriptStringEncoded);
Assert.Equal(javaScriptStringEncoded, thenHtmlEncoded); // should have contained no HTML-sensitive characters
}
}
private static bool IsSurrogateCodePoint(int codePoint)
{
return (0xD800 <= codePoint && codePoint <= 0xDFFF);
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// this file contains the data structures for the in memory database
// containing display and formatting information
using System.Collections.Generic;
using Microsoft.PowerShell.Commands;
using Microsoft.PowerShell.Commands.Internal.Format;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
#region Table View Definitions
/// <summary>
/// Alignment values
/// NOTE: we do not use an enum because this will have to be
/// serialized and ERS/serialization do not support enumerations.
/// </summary>
internal static class TextAlignment
{
internal const int Undefined = 0;
internal const int Left = 1;
internal const int Center = 2;
internal const int Right = 3;
}
/// <summary>
/// Definition of a table control.
/// </summary>
internal sealed class TableControlBody : ControlBody
{
/// <summary>
/// Optional, if not present, use data off the default table row definition.
/// </summary>
internal TableHeaderDefinition header = new TableHeaderDefinition();
/// <summary>
/// Default row definition
/// It's mandatory.
/// </summary>
internal TableRowDefinition defaultDefinition;
/// <summary>
/// Optional list of row definition overrides. It can be empty if there are no overrides.
/// </summary>
internal List<TableRowDefinition> optionalDefinitionList = new List<TableRowDefinition>();
internal override ControlBase Copy()
{
TableControlBody result = new TableControlBody
{
autosize = this.autosize,
header = this.header.Copy()
};
if (defaultDefinition != null)
{
result.defaultDefinition = this.defaultDefinition.Copy();
}
foreach (TableRowDefinition trd in this.optionalDefinitionList)
{
result.optionalDefinitionList.Add(trd);
}
return result;
}
}
/// <summary>
/// Information about the table header
/// NOTE: if an instance of this class is present, the list must not be empty.
/// </summary>
internal sealed class TableHeaderDefinition
{
/// <summary>
/// If true, direct the outputter to suppress table header printing.
/// </summary>
internal bool hideHeader;
/// <summary>
/// Mandatory list of column header definitions.
/// </summary>
internal List<TableColumnHeaderDefinition> columnHeaderDefinitionList =
new List<TableColumnHeaderDefinition>();
/// <summary>
/// Returns a Shallow Copy of the current object.
/// </summary>
/// <returns></returns>
internal TableHeaderDefinition Copy()
{
TableHeaderDefinition result = new TableHeaderDefinition { hideHeader = this.hideHeader };
foreach (TableColumnHeaderDefinition tchd in this.columnHeaderDefinitionList)
{
result.columnHeaderDefinitionList.Add(tchd);
}
return result;
}
}
internal sealed class TableColumnHeaderDefinition
{
/// <summary>
/// Optional label
/// If not present, use the name of the property from the matching
/// mandatory row description.
/// </summary>
internal TextToken label = null;
/// <summary>
/// General alignment for the column
/// If not present, either use the one from the row definition
/// or the data driven heuristics.
/// </summary>
internal int alignment = TextAlignment.Undefined;
/// <summary>
/// Width of the column.
/// </summary>
internal int width = 0; // undefined
}
/// <summary>
/// Definition of the data to be displayed in a table row.
/// </summary>
internal sealed class TableRowDefinition
{
/// <summary>
/// Applicability clause
/// Only valid if not the default definition.
/// </summary>
internal AppliesTo appliesTo;
/// <summary>
/// If true, the current table row should be allowed
/// to wrap to multiple lines, else truncated.
/// </summary>
internal bool multiLine;
/// <summary>
/// Mandatory list of column items.
/// It cannot be empty.
/// </summary>
internal List<TableRowItemDefinition> rowItemDefinitionList = new List<TableRowItemDefinition>();
/// <summary>
/// Returns a Shallow Copy of the current object.
/// </summary>
/// <returns></returns>
internal TableRowDefinition Copy()
{
TableRowDefinition result = new TableRowDefinition
{
appliesTo = this.appliesTo,
multiLine = this.multiLine
};
foreach (TableRowItemDefinition trid in this.rowItemDefinitionList)
{
result.rowItemDefinitionList.Add(trid);
}
return result;
}
}
/// <summary>
/// Cell definition inside a row.
/// </summary>
internal sealed class TableRowItemDefinition
{
/// <summary>
/// Optional alignment to override the default one at the header level.
/// </summary>
internal int alignment = TextAlignment.Undefined;
/// <summary>
/// Format directive body telling how to format the cell
/// RULE: the body can only contain
/// * TextToken
/// * PropertyToken
/// * NOTHING (provide an empty cell)
/// </summary>
internal List<FormatToken> formatTokenList = new List<FormatToken>();
}
#endregion
}
namespace System.Management.Automation
{
/// <summary>
/// Defines a table control.
/// </summary>
public sealed class TableControl : PSControl
{
/// <summary>Collection of column header definitions for this table control</summary>
public List<TableControlColumnHeader> Headers { get; set; }
/// <summary>Collection of row definitions for this table control</summary>
public List<TableControlRow> Rows { get; set; }
/// <summary>When true, column widths are calculated based on more than the first object.</summary>
public bool AutoSize { get; set; }
/// <summary>When true, table headers are not displayed</summary>
public bool HideTableHeaders { get; set; }
/// <summary>Create a default TableControl</summary>
public static TableControlBuilder Create(bool outOfBand = false, bool autoSize = false, bool hideTableHeaders = false)
{
var table = new TableControl { OutOfBand = outOfBand, AutoSize = autoSize, HideTableHeaders = hideTableHeaders };
return new TableControlBuilder(table);
}
/// <summary>Public default constructor for TableControl</summary>
public TableControl()
{
Headers = new List<TableControlColumnHeader>();
Rows = new List<TableControlRow>();
}
internal override void WriteToXml(FormatXmlWriter writer)
{
writer.WriteTableControl(this);
}
/// <summary>
/// Determines if this object is safe to be written.
/// </summary>
/// <returns>True if safe, false otherwise.</returns>
internal override bool SafeForExport()
{
if (!base.SafeForExport())
return false;
foreach (var row in Rows)
{
if (!row.SafeForExport())
return false;
}
return true;
}
internal override bool CompatibleWithOldPowerShell()
{
if (!base.CompatibleWithOldPowerShell())
return false;
foreach (var row in Rows)
{
if (!row.CompatibleWithOldPowerShell())
return false;
}
return true;
}
internal TableControl(TableControlBody tcb, ViewDefinition viewDefinition) : this()
{
this.OutOfBand = viewDefinition.outOfBand;
this.GroupBy = PSControlGroupBy.Get(viewDefinition.groupBy);
this.AutoSize = tcb.autosize.GetValueOrDefault();
this.HideTableHeaders = tcb.header.hideHeader;
TableControlRow row = new TableControlRow(tcb.defaultDefinition);
Rows.Add(row);
foreach (TableRowDefinition rd in tcb.optionalDefinitionList)
{
row = new TableControlRow(rd);
Rows.Add(row);
}
foreach (TableColumnHeaderDefinition hd in tcb.header.columnHeaderDefinitionList)
{
TableControlColumnHeader header = new TableControlColumnHeader(hd);
Headers.Add(header);
}
}
/// <summary>
/// Public constructor for TableControl that only takes 'tableControlRows'.
/// </summary>
/// <param name="tableControlRow"></param>
public TableControl(TableControlRow tableControlRow) : this()
{
if (tableControlRow == null)
throw PSTraceSource.NewArgumentNullException("tableControlRows");
this.Rows.Add(tableControlRow);
}
/// <summary>
/// Public constructor for TableControl that takes both 'tableControlRows' and 'tableControlColumnHeaders'.
/// </summary>
/// <param name="tableControlRow"></param>
/// <param name="tableControlColumnHeaders"></param>
public TableControl(TableControlRow tableControlRow, IEnumerable<TableControlColumnHeader> tableControlColumnHeaders) : this()
{
if (tableControlRow == null)
throw PSTraceSource.NewArgumentNullException("tableControlRows");
if (tableControlColumnHeaders == null)
throw PSTraceSource.NewArgumentNullException(nameof(tableControlColumnHeaders));
this.Rows.Add(tableControlRow);
foreach (TableControlColumnHeader header in tableControlColumnHeaders)
{
this.Headers.Add(header);
}
}
}
/// <summary>
/// Defines the header for a particular column in a table control.
/// </summary>
public sealed class TableControlColumnHeader
{
/// <summary>Label for the column</summary>
public string Label { get; set; }
/// <summary>Alignment of the string within the column</summary>
public Alignment Alignment { get; set; }
/// <summary>Width of the column - in number of display cells</summary>
public int Width { get; set; }
internal TableControlColumnHeader(TableColumnHeaderDefinition colheaderdefinition)
{
if (colheaderdefinition.label != null)
{
Label = colheaderdefinition.label.text;
}
Alignment = (Alignment)colheaderdefinition.alignment;
Width = colheaderdefinition.width;
}
/// <summary>Default constructor</summary>
public TableControlColumnHeader()
{
}
/// <summary>
/// Public constructor for TableControlColumnHeader.
/// </summary>
/// <param name="label">Could be null if no label to specify.</param>
/// <param name="width">The Value should be non-negative.</param>
/// <param name="alignment">The default value is Alignment.Undefined.</param>
public TableControlColumnHeader(string label, int width, Alignment alignment)
{
if (width < 0)
throw PSTraceSource.NewArgumentOutOfRangeException(nameof(width), width);
this.Label = label;
this.Width = width;
this.Alignment = alignment;
}
}
/// <summary>
/// Defines a particular column within a row
/// in a table control.
/// </summary>
public sealed class TableControlColumn
{
/// <summary>Alignment of the particular column</summary>
public Alignment Alignment { get; set; }
/// <summary>Display Entry</summary>
public DisplayEntry DisplayEntry { get; set; }
/// <summary>Format string to apply</summary>
public string FormatString { get; internal set; }
/// <summary>
/// Returns the value of the entry.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return DisplayEntry.Value;
}
/// <summary>Default constructor</summary>
public TableControlColumn()
{
}
internal TableControlColumn(string text, int alignment, bool isscriptblock, string formatString)
{
Alignment = (Alignment)alignment;
DisplayEntry = new DisplayEntry(text, isscriptblock ? DisplayEntryValueType.ScriptBlock : DisplayEntryValueType.Property);
FormatString = formatString;
}
/// <summary>
/// Public constructor for TableControlColumn.
/// </summary>
/// <param name="alignment"></param>
/// <param name="entry"></param>
public TableControlColumn(Alignment alignment, DisplayEntry entry)
{
this.Alignment = alignment;
this.DisplayEntry = entry;
}
internal bool SafeForExport()
{
return DisplayEntry.SafeForExport();
}
}
/// <summary>
/// Defines a single row in a table control.
/// </summary>
public sealed class TableControlRow
{
/// <summary>Collection of column definitions for this row</summary>
public List<TableControlColumn> Columns { get; set; }
/// <summary>List of typenames which select this entry</summary>
public EntrySelectedBy SelectedBy { get; internal set; }
/// <summary>When true, instead of truncating to the column width, use multiple lines.</summary>
public bool Wrap { get; set; }
/// <summary>Public constructor for TableControlRow</summary>
public TableControlRow()
{
Columns = new List<TableControlColumn>();
}
internal TableControlRow(TableRowDefinition rowdefinition) : this()
{
Wrap = rowdefinition.multiLine;
if (rowdefinition.appliesTo != null)
{
SelectedBy = EntrySelectedBy.Get(rowdefinition.appliesTo.referenceList);
}
foreach (TableRowItemDefinition itemdef in rowdefinition.rowItemDefinitionList)
{
FieldPropertyToken fpt = itemdef.formatTokenList[0] as FieldPropertyToken;
TableControlColumn column;
if (fpt != null)
{
column = new TableControlColumn(fpt.expression.expressionValue, itemdef.alignment,
fpt.expression.isScriptBlock, fpt.fieldFormattingDirective.formatString);
}
else
{
column = new TableControlColumn();
}
Columns.Add(column);
}
}
/// <summary>Public constructor for TableControlRow.</summary>
public TableControlRow(IEnumerable<TableControlColumn> columns) : this()
{
if (columns == null)
throw PSTraceSource.NewArgumentNullException(nameof(columns));
foreach (TableControlColumn column in columns)
{
Columns.Add(column);
}
}
internal bool SafeForExport()
{
foreach (var column in Columns)
{
if (!column.SafeForExport())
return false;
}
return SelectedBy != null && SelectedBy.SafeForExport();
}
internal bool CompatibleWithOldPowerShell()
{
// Old versions of PowerShell don't support multiple row definitions.
return SelectedBy == null;
}
}
/// <summary>A helper class for defining table controls</summary>
public sealed class TableRowDefinitionBuilder
{
internal readonly TableControlBuilder _tcb;
internal readonly TableControlRow _tcr;
internal TableRowDefinitionBuilder(TableControlBuilder tcb, TableControlRow tcr)
{
_tcb = tcb;
_tcr = tcr;
}
private TableRowDefinitionBuilder AddItem(string value, DisplayEntryValueType entryType, Alignment alignment, string format)
{
if (string.IsNullOrEmpty(value))
throw PSTraceSource.NewArgumentException(nameof(value));
var tableControlColumn = new TableControlColumn(alignment, new DisplayEntry(value, entryType))
{
FormatString = format
};
_tcr.Columns.Add(tableControlColumn);
return this;
}
/// <summary>
/// Add a column to the current row definition that calls a script block.
/// </summary>
public TableRowDefinitionBuilder AddScriptBlockColumn(string scriptBlock, Alignment alignment = Alignment.Undefined, string format = null)
{
return AddItem(scriptBlock, DisplayEntryValueType.ScriptBlock, alignment, format);
}
/// <summary>
/// Add a column to the current row definition that references a property.
/// </summary>
public TableRowDefinitionBuilder AddPropertyColumn(string propertyName, Alignment alignment = Alignment.Undefined, string format = null)
{
return AddItem(propertyName, DisplayEntryValueType.Property, alignment, format);
}
/// <summary>
/// Complete a row definition.
/// </summary>
public TableControlBuilder EndRowDefinition()
{
return _tcb;
}
}
/// <summary>A helper class for defining table controls</summary>
public sealed class TableControlBuilder
{
internal readonly TableControl _table;
internal TableControlBuilder(TableControl table)
{
_table = table;
}
/// <summary>Group instances by the property name with an optional label.</summary>
public TableControlBuilder GroupByProperty(string property, CustomControl customControl = null, string label = null)
{
_table.GroupBy = new PSControlGroupBy
{
Expression = new DisplayEntry(property, DisplayEntryValueType.Property),
CustomControl = customControl,
Label = label
};
return this;
}
/// <summary>Group instances by the script block expression with an optional label.</summary>
public TableControlBuilder GroupByScriptBlock(string scriptBlock, CustomControl customControl = null, string label = null)
{
_table.GroupBy = new PSControlGroupBy
{
Expression = new DisplayEntry(scriptBlock, DisplayEntryValueType.ScriptBlock),
CustomControl = customControl,
Label = label
};
return this;
}
/// <summary>Add a header</summary>
public TableControlBuilder AddHeader(Alignment alignment = Alignment.Undefined, int width = 0, string label = null)
{
_table.Headers.Add(new TableControlColumnHeader(label, width, alignment));
return this;
}
/// <summary>Add a header</summary>
public TableRowDefinitionBuilder StartRowDefinition(bool wrap = false, IEnumerable<string> entrySelectedByType = null, IEnumerable<DisplayEntry> entrySelectedByCondition = null)
{
var row = new TableControlRow { Wrap = wrap };
if (entrySelectedByType != null || entrySelectedByCondition != null)
{
row.SelectedBy = new EntrySelectedBy();
if (entrySelectedByType != null)
{
row.SelectedBy.TypeNames = new List<string>(entrySelectedByType);
}
if (entrySelectedByCondition != null)
{
row.SelectedBy.SelectionCondition = new List<DisplayEntry>(entrySelectedByCondition);
}
}
_table.Rows.Add(row);
return new TableRowDefinitionBuilder(this, row);
}
/// <summary>Complete a table definition</summary>
public TableControl EndTable()
{
return _table;
}
}
}
| |
using System;
using System.Diagnostics;
/*
* 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 Lucene.Net.Util
{
using Lucene.Net.Support;
using DocIdSet = Lucene.Net.Search.DocIdSet;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
/// <summary>
/// An "open" BitSet implementation that allows direct access to the array of words
/// storing the bits.
/// <p/>
/// Unlike java.util.bitset, the fact that bits are packed into an array of longs
/// is part of the interface. this allows efficient implementation of other algorithms
/// by someone other than the author. It also allows one to efficiently implement
/// alternate serialization or interchange formats.
/// <p/>
/// <code>OpenBitSet</code> is faster than <code>java.util.BitSet</code> in most operations
/// and *much* faster at calculating cardinality of sets and results of set operations.
/// It can also handle sets of larger cardinality (up to 64 * 2**32-1)
/// <p/>
/// The goals of <code>OpenBitSet</code> are the fastest implementation possible, and
/// maximum code reuse. Extra safety and encapsulation
/// may always be built on top, but if that's built in, the cost can never be removed (and
/// hence people re-implement their own version in order to get better performance).
/// If you want a "safe", totally encapsulated (and slower and limited) BitSet
/// class, use <code>java.util.BitSet</code>.
/// <p/>
/// <h3>Performance Results</h3>
///
/// Test system: Pentium 4, Sun Java 1.5_06 -server -Xbatch -Xmx64M
/// <br/>BitSet size = 1,000,000
/// <br/>Results are java.util.BitSet time divided by OpenBitSet time.
/// <table border="1">
/// <tr>
/// <th></th> <th>cardinality</th> <th>intersect_count</th> <th>union</th> <th>nextSetBit</th> <th>get</th> <th>iterator</th>
/// </tr>
/// <tr>
/// <th>50% full</th> <td>3.36</td> <td>3.96</td> <td>1.44</td> <td>1.46</td> <td>1.99</td> <td>1.58</td>
/// </tr>
/// <tr>
/// <th>1% full</th> <td>3.31</td> <td>3.90</td> <td> </td> <td>1.04</td> <td> </td> <td>0.99</td>
/// </tr>
/// </table>
/// <br/>
/// Test system: AMD Opteron, 64 bit linux, Sun Java 1.5_06 -server -Xbatch -Xmx64M
/// <br/>BitSet size = 1,000,000
/// <br/>Results are java.util.BitSet time divided by OpenBitSet time.
/// <table border="1">
/// <tr>
/// <th></th> <th>cardinality</th> <th>intersect_count</th> <th>union</th> <th>nextSetBit</th> <th>get</th> <th>iterator</th>
/// </tr>
/// <tr>
/// <th>50% full</th> <td>2.50</td> <td>3.50</td> <td>1.00</td> <td>1.03</td> <td>1.12</td> <td>1.25</td>
/// </tr>
/// <tr>
/// <th>1% full</th> <td>2.51</td> <td>3.49</td> <td> </td> <td>1.00</td> <td> </td> <td>1.02</td>
/// </tr>
/// </table>
/// </summary>
public class OpenBitSet : DocIdSet, Bits, ICloneable
{
protected internal long[] bits;
protected internal int Wlen; // number of words (elements) used in the array
// Used only for assert:
private long NumBits;
/// <summary>
/// Constructs an OpenBitSet large enough to hold {@code numBits}. </summary>
public OpenBitSet(long numBits)
{
this.NumBits = numBits;
bits = new long[Bits2words(numBits)];
Wlen = bits.Length;
}
/// <summary>
/// Constructor: allocates enough space for 64 bits. </summary>
public OpenBitSet()
: this(64)
{
}
/// <summary>
/// Constructs an OpenBitSet from an existing long[].
/// <p>
/// The first 64 bits are in long[0], with bit index 0 at the least significant
/// bit, and bit index 63 at the most significant. Given a bit index, the word
/// containing it is long[index/64], and it is at bit number index%64 within
/// that word.
/// <p>
/// numWords are the number of elements in the array that contain set bits
/// (non-zero longs). numWords should be <= bits.length, and any existing
/// words in the array at position >= numWords should be zero.
///
/// </summary>
public OpenBitSet(long[] bits, int numWords)
{
if (numWords > bits.Length)
{
throw new System.ArgumentException("numWords cannot exceed bits.length");
}
this.bits = bits;
this.Wlen = numWords;
this.NumBits = Wlen * 64;
}
public override DocIdSetIterator GetIterator()
{
return new OpenBitSetIterator(bits, Wlen);
}
public override Bits GetBits()
{
return this;
}
/// <summary>
/// this DocIdSet implementation is cacheable. </summary>
public override bool Cacheable
{
get
{
return true;
}
}
/// <summary>
/// Returns the current capacity in bits (1 greater than the index of the last bit) </summary>
public virtual long Capacity()
{
return bits.Length << 6;
}
/// <summary>
/// Returns the current capacity of this set. Included for
/// compatibility. this is *not* equal to <seealso cref="#cardinality"/>
/// </summary>
public virtual long Size()
{
return Capacity();
}
public virtual int Length()
{
return bits.Length << 6;
}
/// <summary>
/// Returns true if there are no set bits </summary>
public virtual bool Empty
{
get
{
return Cardinality() == 0;
}
}
/// <summary>
/// Expert: returns the long[] storing the bits </summary>
public virtual long[] Bits
{
get
{
return bits;
}
}
/// <summary>
/// Expert: gets the number of longs in the array that are in use </summary>
public virtual int NumWords
{
get
{
return Wlen;
}
}
/// <summary>
/// Returns true or false for the specified bit index. </summary>
public virtual bool Get(int index)
{
int i = index >> 6; // div 64
// signed shift will keep a negative index and force an
// array-index-out-of-bounds-exception, removing the need for an explicit check.
if (i >= bits.Length)
{
return false;
}
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
return (bits[i] & bitmask) != 0;
}
/// <summary>
/// Returns true or false for the specified bit index.
/// The index should be less than the OpenBitSet size
/// </summary>
public virtual bool FastGet(int index)
{
Debug.Assert(index >= 0 && index < NumBits);
int i = index >> 6; // div 64
// signed shift will keep a negative index and force an
// array-index-out-of-bounds-exception, removing the need for an explicit check.
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
return (bits[i] & bitmask) != 0;
}
/// <summary>
/// Returns true or false for the specified bit index
/// </summary>
public virtual bool Get(long index)
{
int i = (int)(index >> 6); // div 64
if (i >= bits.Length)
{
return false;
}
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
return (bits[i] & bitmask) != 0;
}
/// <summary>
/// Returns true or false for the specified bit index.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual bool FastGet(long index)
{
Debug.Assert(index >= 0 && index < NumBits);
int i = (int)(index >> 6); // div 64
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
return (bits[i] & bitmask) != 0;
}
/*
// alternate implementation of get()
public boolean get1(int index) {
int i = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
return ((bits[i]>>>bit) & 0x01) != 0;
// this does a long shift and a bittest (on x86) vs
// a long shift, and a long AND, (the test for zero is prob a no-op)
// testing on a P4 indicates this is slower than (bits[i] & bitmask) != 0;
}
*/
/// <summary>
/// returns 1 if the bit is set, 0 if not.
/// The index should be less than the OpenBitSet size
/// </summary>
public virtual int GetBit(int index)
{
Debug.Assert(index >= 0 && index < NumBits);
int i = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
return ((int)((long)((ulong)bits[i] >> bit))) & 0x01;
}
/*
public boolean get2(int index) {
int word = index >> 6; // div 64
int bit = index & 0x0000003f; // mod 64
return (bits[word] << bit) < 0; // hmmm, this would work if bit order were reversed
// we could right shift and check for parity bit, if it was available to us.
}
*/
/// <summary>
/// sets a bit, expanding the set size if necessary </summary>
public virtual void Set(long index)
{
int wordNum = ExpandingWordNum(index);
int bit = (int)index & 0x3f;
long bitmask = 1L << bit;
bits[wordNum] |= bitmask;
}
/// <summary>
/// Sets the bit at the specified index.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual void FastSet(int index)
{
Debug.Assert(index >= 0 && index < NumBits);
int wordNum = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] |= bitmask;
}
/// <summary>
/// Sets the bit at the specified index.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual void FastSet(long index)
{
Debug.Assert(index >= 0 && index < NumBits);
int wordNum = (int)(index >> 6);
int bit = (int)index & 0x3f;
long bitmask = 1L << bit;
bits[wordNum] |= bitmask;
}
/// <summary>
/// Sets a range of bits, expanding the set size if necessary
/// </summary>
/// <param name="startIndex"> lower index </param>
/// <param name="endIndex"> one-past the last bit to set </param>
public virtual void Set(long startIndex, long endIndex)
{
if (endIndex <= startIndex)
{
return;
}
int startWord = (int)(startIndex >> 6);
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = ExpandingWordNum(endIndex - 1);
long startmask = -1L << (int)startIndex;
long endmask = (long)(0xffffffffffffffffUL >> (int)-endIndex); // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
if (startWord == endWord)
{
bits[startWord] |= (startmask & endmask);
return;
}
bits[startWord] |= startmask;
Arrays.Fill(bits, startWord + 1, endWord, -1L);
bits[endWord] |= endmask;
}
protected internal virtual int ExpandingWordNum(long index)
{
int wordNum = (int)(index >> 6);
if (wordNum >= Wlen)
{
EnsureCapacity(index + 1);
}
return wordNum;
}
/// <summary>
/// clears a bit.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual void FastClear(int index)
{
Debug.Assert(index >= 0 && index < NumBits);
int wordNum = index >> 6;
int bit = index & 0x03f;
long bitmask = 1L << bit;
bits[wordNum] &= ~bitmask;
// hmmm, it takes one more instruction to clear than it does to set... any
// way to work around this? If there were only 63 bits per word, we could
// use a right shift of 10111111...111 in binary to position the 0 in the
// correct place (using sign extension).
// Could also use Long.rotateRight() or rotateLeft() *if* they were converted
// by the JVM into a native instruction.
// bits[word] &= Long.rotateLeft(0xfffffffe,bit);
}
/// <summary>
/// clears a bit.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual void FastClear(long index)
{
Debug.Assert(index >= 0 && index < NumBits);
int wordNum = (int)(index >> 6); // div 64
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] &= ~bitmask;
}
/// <summary>
/// clears a bit, allowing access beyond the current set size without changing the size. </summary>
public virtual void Clear(long index)
{
int wordNum = (int)(index >> 6); // div 64
if (wordNum >= Wlen)
{
return;
}
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] &= ~bitmask;
}
/// <summary>
/// Clears a range of bits. Clearing past the end does not change the size of the set.
/// </summary>
/// <param name="startIndex"> lower index </param>
/// <param name="endIndex"> one-past the last bit to clear </param>
public virtual void Clear(int startIndex, int endIndex)
{
if (endIndex <= startIndex)
{
return;
}
int startWord = (startIndex >> 6);
if (startWord >= Wlen)
{
return;
}
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = ((endIndex - 1) >> 6);
long startmask = (-1L) << startIndex; // -1 << (startIndex mod 64)
long endmask = (-1L) << endIndex; // -1 << (endIndex mod 64)
if ((endIndex & 0x3f) == 0)
{
endmask = 0;
}
startmask = ~startmask;
if (startWord == endWord)
{
bits[startWord] &= (startmask | endmask);
return;
}
bits[startWord] &= startmask;
int middle = Math.Min(Wlen, endWord);
Arrays.Fill(bits, startWord + 1, middle, 0L);
if (endWord < Wlen)
{
bits[endWord] &= endmask;
}
}
/// <summary>
/// Clears a range of bits. Clearing past the end does not change the size of the set.
/// </summary>
/// <param name="startIndex"> lower index </param>
/// <param name="endIndex"> one-past the last bit to clear </param>
public virtual void Clear(long startIndex, long endIndex)
{
if (endIndex <= startIndex)
{
return;
}
int startWord = (int)(startIndex >> 6);
if (startWord >= Wlen)
{
return;
}
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = (int)((endIndex - 1) >> 6);
//LUCENE TO-DO
long startmask = -1L << (int)startIndex;
long endmask = -(int)((uint)1L >> (int)-endIndex); // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
// invert masks since we are clearing
startmask = ~startmask;
endmask = ~endmask;
if (startWord == endWord)
{
bits[startWord] &= (startmask | endmask);
return;
}
bits[startWord] &= startmask;
int middle = Math.Min(Wlen, endWord);
Arrays.Fill(bits, startWord + 1, middle, 0L);
if (endWord < Wlen)
{
bits[endWord] &= endmask;
}
}
/// <summary>
/// Sets a bit and returns the previous value.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual bool GetAndSet(int index)
{
Debug.Assert(index >= 0 && index < NumBits);
int wordNum = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
bool val = (bits[wordNum] & bitmask) != 0;
bits[wordNum] |= bitmask;
return val;
}
/// <summary>
/// Sets a bit and returns the previous value.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual bool GetAndSet(long index)
{
Debug.Assert(index >= 0 && index < NumBits);
int wordNum = (int)(index >> 6); // div 64
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bool val = (bits[wordNum] & bitmask) != 0;
bits[wordNum] |= bitmask;
return val;
}
/// <summary>
/// flips a bit.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual void FastFlip(int index)
{
Debug.Assert(index >= 0 && index < NumBits);
int wordNum = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] ^= bitmask;
}
/// <summary>
/// flips a bit.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual void FastFlip(long index)
{
Debug.Assert(index >= 0 && index < NumBits);
int wordNum = (int)(index >> 6); // div 64
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] ^= bitmask;
}
/// <summary>
/// flips a bit, expanding the set size if necessary </summary>
public virtual void Flip(long index)
{
int wordNum = ExpandingWordNum(index);
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] ^= bitmask;
}
/// <summary>
/// flips a bit and returns the resulting bit value.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual bool FlipAndGet(int index)
{
Debug.Assert(index >= 0 && index < NumBits);
int wordNum = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] ^= bitmask;
return (bits[wordNum] & bitmask) != 0;
}
/// <summary>
/// flips a bit and returns the resulting bit value.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual bool FlipAndGet(long index)
{
Debug.Assert(index >= 0 && index < NumBits);
int wordNum = (int)(index >> 6); // div 64
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] ^= bitmask;
return (bits[wordNum] & bitmask) != 0;
}
/// <summary>
/// Flips a range of bits, expanding the set size if necessary
/// </summary>
/// <param name="startIndex"> lower index </param>
/// <param name="endIndex"> one-past the last bit to flip </param>
public virtual void Flip(long startIndex, long endIndex)
{
if (endIndex <= startIndex)
{
return;
}
int startWord = (int)(startIndex >> 6);
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = ExpandingWordNum(endIndex - 1);
/// <summary>
///* Grrr, java shifting wraps around so -1L>>>64 == -1
/// for that reason, make sure not to use endmask if the bits to flip will
/// be zero in the last word (redefine endWord to be the last changed...)
/// long startmask = -1L << (startIndex & 0x3f); // example: 11111...111000
/// long endmask = -1L >>> (64-(endIndex & 0x3f)); // example: 00111...111111
/// **
/// </summary>
//LUCENE TO-DO
long startmask = -1L << (int)startIndex;
long endmask = (long)(0xffffffffffffffffUL >> (int)-endIndex); // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
if (startWord == endWord)
{
bits[startWord] ^= (startmask & endmask);
return;
}
bits[startWord] ^= startmask;
for (int i = startWord + 1; i < endWord; i++)
{
bits[i] = ~bits[i];
}
bits[endWord] ^= endmask;
}
/*
public static int pop(long v0, long v1, long v2, long v3) {
// derived from pop_array by setting last four elems to 0.
// exchanges one pop() call for 10 elementary operations
// saving about 7 instructions... is there a better way?
long twosA=v0 & v1;
long ones=v0^v1;
long u2=ones^v2;
long twosB =(ones&v2)|(u2&v3);
ones=u2^v3;
long fours=(twosA&twosB);
long twos=twosA^twosB;
return (pop(fours)<<2)
+ (pop(twos)<<1)
+ pop(ones);
}
*/
/// <returns> the number of set bits </returns>
public virtual long Cardinality()
{
return BitUtil.Pop_array(bits, 0, Wlen);
}
/// <summary>
/// Returns the popcount or cardinality of the intersection of the two sets.
/// Neither set is modified.
/// </summary>
public static long IntersectionCount(OpenBitSet a, OpenBitSet b)
{
return BitUtil.Pop_intersect(a.bits, b.bits, 0, Math.Min(a.Wlen, b.Wlen));
}
/// <summary>
/// Returns the popcount or cardinality of the union of the two sets.
/// Neither set is modified.
/// </summary>
public static long UnionCount(OpenBitSet a, OpenBitSet b)
{
long tot = BitUtil.Pop_union(a.bits, b.bits, 0, Math.Min(a.Wlen, b.Wlen));
if (a.Wlen < b.Wlen)
{
tot += BitUtil.Pop_array(b.bits, a.Wlen, b.Wlen - a.Wlen);
}
else if (a.Wlen > b.Wlen)
{
tot += BitUtil.Pop_array(a.bits, b.Wlen, a.Wlen - b.Wlen);
}
return tot;
}
/// <summary>
/// Returns the popcount or cardinality of "a and not b"
/// or "intersection(a, not(b))".
/// Neither set is modified.
/// </summary>
public static long AndNotCount(OpenBitSet a, OpenBitSet b)
{
long tot = BitUtil.Pop_andnot(a.bits, b.bits, 0, Math.Min(a.Wlen, b.Wlen));
if (a.Wlen > b.Wlen)
{
tot += BitUtil.Pop_array(a.bits, b.Wlen, a.Wlen - b.Wlen);
}
return tot;
}
/// <summary>
/// Returns the popcount or cardinality of the exclusive-or of the two sets.
/// Neither set is modified.
/// </summary>
public static long XorCount(OpenBitSet a, OpenBitSet b)
{
long tot = BitUtil.Pop_xor(a.bits, b.bits, 0, Math.Min(a.Wlen, b.Wlen));
if (a.Wlen < b.Wlen)
{
tot += BitUtil.Pop_array(b.bits, a.Wlen, b.Wlen - a.Wlen);
}
else if (a.Wlen > b.Wlen)
{
tot += BitUtil.Pop_array(a.bits, b.Wlen, a.Wlen - b.Wlen);
}
return tot;
}
/// <summary>
/// Returns the index of the first set bit starting at the index specified.
/// -1 is returned if there are no more set bits.
/// </summary>
public virtual int NextSetBit(int index)
{
int i = index >> 6;
if (i >= Wlen)
{
return -1;
}
int subIndex = index & 0x3f; // index within the word
long word = bits[i] >> subIndex; // skip all the bits to the right of index
if (word != 0)
{
return (i << 6) + subIndex + Number.NumberOfTrailingZeros(word);
}
while (++i < Wlen)
{
word = bits[i];
if (word != 0)
{
return (i << 6) + Number.NumberOfTrailingZeros(word);
}
}
return -1;
}
/// <summary>
/// Returns the index of the first set bit starting at the index specified.
/// -1 is returned if there are no more set bits.
/// </summary>
public virtual long NextSetBit(long index)
{
int i = (int)((long)((ulong)index >> 6));
if (i >= Wlen)
{
return -1;
}
int subIndex = (int)index & 0x3f; // index within the word
long word = (long)((ulong)bits[i] >> subIndex); // skip all the bits to the right of index
if (word != 0)
{
return (((long)i) << 6) + (subIndex + Number.NumberOfTrailingZeros(word));
}
while (++i < Wlen)
{
word = bits[i];
if (word != 0)
{
return (((long)i) << 6) + Number.NumberOfTrailingZeros(word);
}
}
return -1;
}
/// <summary>
/// Returns the index of the first set bit starting downwards at
/// the index specified.
/// -1 is returned if there are no more set bits.
/// </summary>
public virtual int PrevSetBit(int index)
{
int i = index >> 6;
int subIndex;
long word;
if (i >= Wlen)
{
i = Wlen - 1;
if (i < 0)
{
return -1;
}
subIndex = 63; // last possible bit
word = bits[i];
}
else
{
if (i < 0)
{
return -1;
}
subIndex = index & 0x3f; // index within the word
word = (bits[i] << (63 - subIndex)); // skip all the bits to the left of index
}
if (word != 0)
{
return (i << 6) + subIndex - Number.NumberOfLeadingZeros(word); // See LUCENE-3197
}
while (--i >= 0)
{
word = bits[i];
if (word != 0)
{
return (i << 6) + 63 - Number.NumberOfLeadingZeros(word);
}
}
return -1;
}
/// <summary>
/// Returns the index of the first set bit starting downwards at
/// the index specified.
/// -1 is returned if there are no more set bits.
/// </summary>
public virtual long PrevSetBit(long index)
{
int i = (int)(index >> 6);
int subIndex;
long word;
if (i >= Wlen)
{
i = Wlen - 1;
if (i < 0)
{
return -1;
}
subIndex = 63; // last possible bit
word = bits[i];
}
else
{
if (i < 0)
{
return -1;
}
subIndex = (int)index & 0x3f; // index within the word
word = (bits[i] << (63 - subIndex)); // skip all the bits to the left of index
}
if (word != 0)
{
return (((long)i) << 6) + subIndex - Number.NumberOfLeadingZeros(word); // See LUCENE-3197
}
while (--i >= 0)
{
word = bits[i];
if (word != 0)
{
return (((long)i) << 6) + 63 - Number.NumberOfLeadingZeros(word);
}
}
return -1;
}
public object Clone()
{
try
{
//OpenBitSet obs = (OpenBitSet)base.Clone();
//obs.bits = (long[])obs.bits.Clone(); // hopefully an array clone is as fast(er) than arraycopy
OpenBitSet obs = new OpenBitSet((long[])bits.Clone(), Wlen);
return obs;
}
catch (Exception e)
{
throw new SystemException(e.Message, e);
}
}
/// <summary>
/// this = this AND other </summary>
public virtual void Intersect(OpenBitSet other)
{
int newLen = Math.Min(this.Wlen, other.Wlen);
long[] thisArr = this.bits;
long[] otherArr = other.bits;
// testing against zero can be more efficient
int pos = newLen;
while (--pos >= 0)
{
thisArr[pos] &= otherArr[pos];
}
if (this.Wlen > newLen)
{
// fill zeros from the new shorter length to the old length
Arrays.Fill(bits, newLen, this.Wlen, 0);
}
this.Wlen = newLen;
}
/// <summary>
/// this = this OR other </summary>
public virtual void Union(OpenBitSet other)
{
int newLen = Math.Max(Wlen, other.Wlen);
EnsureCapacityWords(newLen);
Debug.Assert((NumBits = Math.Max(other.NumBits, NumBits)) >= 0);
long[] thisArr = this.bits;
long[] otherArr = other.bits;
int pos = Math.Min(Wlen, other.Wlen);
while (--pos >= 0)
{
thisArr[pos] |= otherArr[pos];
}
if (this.Wlen < newLen)
{
Array.Copy(otherArr, this.Wlen, thisArr, this.Wlen, newLen - this.Wlen);
}
this.Wlen = newLen;
}
/// <summary>
/// Remove all elements set in other. this = this AND_NOT other </summary>
public virtual void Remove(OpenBitSet other)
{
int idx = Math.Min(Wlen, other.Wlen);
long[] thisArr = this.bits;
long[] otherArr = other.bits;
while (--idx >= 0)
{
thisArr[idx] &= ~otherArr[idx];
}
}
/// <summary>
/// this = this XOR other </summary>
public virtual void Xor(OpenBitSet other)
{
int newLen = Math.Max(Wlen, other.Wlen);
EnsureCapacityWords(newLen);
Debug.Assert((NumBits = Math.Max(other.NumBits, NumBits)) >= 0);
long[] thisArr = this.bits;
long[] otherArr = other.bits;
int pos = Math.Min(Wlen, other.Wlen);
while (--pos >= 0)
{
thisArr[pos] ^= otherArr[pos];
}
if (this.Wlen < newLen)
{
Array.Copy(otherArr, this.Wlen, thisArr, this.Wlen, newLen - this.Wlen);
}
this.Wlen = newLen;
}
// some BitSet compatability methods
//** see {@link intersect} */
public virtual void And(OpenBitSet other)
{
Intersect(other);
}
//** see {@link union} */
public virtual void Or(OpenBitSet other)
{
Union(other);
}
//** see {@link andNot} */
public virtual void AndNot(OpenBitSet other)
{
Remove(other);
}
/// <summary>
/// returns true if the sets have any elements in common </summary>
public virtual bool Intersects(OpenBitSet other)
{
int pos = Math.Min(this.Wlen, other.Wlen);
long[] thisArr = this.bits;
long[] otherArr = other.bits;
while (--pos >= 0)
{
if ((thisArr[pos] & otherArr[pos]) != 0)
{
return true;
}
}
return false;
}
/// <summary>
/// Expand the long[] with the size given as a number of words (64 bit longs). </summary>
public virtual void EnsureCapacityWords(int numWords)
{
bits = ArrayUtil.Grow(bits, numWords);
Wlen = numWords;
Debug.Assert((this.NumBits = Math.Max(this.NumBits, numWords << 6)) >= 0);
}
/// <summary>
/// Ensure that the long[] is big enough to hold numBits, expanding it if
/// necessary.
/// </summary>
public virtual void EnsureCapacity(long numBits)
{
EnsureCapacityWords(Bits2words(numBits));
// ensureCapacityWords sets numBits to a multiple of 64, but we want to set
// it to exactly what the app asked.
Debug.Assert((this.NumBits = Math.Max(this.NumBits, numBits)) >= 0);
}
/// <summary>
/// Lowers numWords, the number of words in use,
/// by checking for trailing zero words.
/// </summary>
public virtual void TrimTrailingZeros()
{
int idx = Wlen - 1;
while (idx >= 0 && bits[idx] == 0)
{
idx--;
}
Wlen = idx + 1;
}
/// <summary>
/// returns the number of 64 bit words it would take to hold numBits </summary>
public static int Bits2words(long numBits)
{
return (int)(((numBits - 1) >> 6) + 1);
}
/// <summary>
/// returns true if both sets have the same bits set </summary>
public override bool Equals(object o)
{
if (this == o)
{
return true;
}
if (!(o is OpenBitSet))
{
return false;
}
OpenBitSet a;
OpenBitSet b = (OpenBitSet)o;
// make a the larger set.
if (b.Wlen > this.Wlen)
{
a = b;
b = this;
}
else
{
a = this;
}
// check for any set bits out of the range of b
for (int i = a.Wlen - 1; i >= b.Wlen; i--)
{
if (a.bits[i] != 0)
{
return false;
}
}
for (int i = b.Wlen - 1; i >= 0; i--)
{
if (a.bits[i] != b.bits[i])
{
return false;
}
}
return true;
}
public override int GetHashCode()
{
// Start with a zero hash and use a mix that results in zero if the input is zero.
// this effectively truncates trailing zeros without an explicit check.
long h = 0;
for (int i = bits.Length; --i >= 0; )
{
h ^= bits[i];
h = (h << 1) | ((long)((ulong)h >> 63)); // rotate left
}
// fold leftmost bits into right and add a constant to prevent
// empty sets from returning 0, which is too common.
return (int)((h >> 32) ^ h) + unchecked((int)0x98761234);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Elasticsearch.Net.Integration.Yaml.Search1
{
public partial class Search1YamlTests
{
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class SourceFiltering1Tests : YamlTestsBase
{
[Test]
public void SourceFiltering1Test()
{
//do index
_body = new {
include= new {
field1= "v1",
field2= "v2"
},
count= "1"
};
this.Do(()=> _client.Index("test_1", "test", "1", _body));
//do indices.refresh
this.Do(()=> _client.IndicesRefreshForAll());
//do search
_body = @"{ _source: true, query: { match_all: {} } }";
this.Do(()=> _client.Search(_body));
//length _response.hits.hits: 1;
this.IsLength(_response.hits.hits, 1);
//match _response.hits.hits[0]._source.count:
this.IsMatch(_response.hits.hits[0]._source.count, 1);
//do search
_body = @"{ _source: false, query: { match_all: {} } }";
this.Do(()=> _client.Search(_body));
//length _response.hits.hits: 1;
this.IsLength(_response.hits.hits, 1);
//is_false _response.hits.hits[0]._source;
this.IsFalse(_response.hits.hits[0]._source);
//do search
_body = new {
query= new {
match_all= new {}
}
};
this.Do(()=> _client.Search(_body));
//length _response.hits.hits: 1;
this.IsLength(_response.hits.hits, 1);
//match _response.hits.hits[0]._source.count:
this.IsMatch(_response.hits.hits[0]._source.count, 1);
//do search
_body = new {
_source= "include.field1",
query= new {
match_all= new {}
}
};
this.Do(()=> _client.Search(_body));
//match _response.hits.hits[0]._source.include.field1:
this.IsMatch(_response.hits.hits[0]._source.include.field1, @"v1");
//is_false _response.hits.hits[0]._source.include.field2;
this.IsFalse(_response.hits.hits[0]._source.include.field2);
//do search
_body = new {
_source= "include.field2",
query= new {
match_all= new {}
}
};
this.Do(()=> _client.Search(_body, nv=>nv
.AddQueryString("_source_include", @"include.field1")
));
//match _response.hits.hits[0]._source.include.field1:
this.IsMatch(_response.hits.hits[0]._source.include.field1, @"v1");
//is_false _response.hits.hits[0]._source.include.field2;
this.IsFalse(_response.hits.hits[0]._source.include.field2);
//do search
_body = new {
query= new {
match_all= new {}
}
};
this.Do(()=> _client.Search(_body, nv=>nv
.AddQueryString("_source_include", @"include.field1")
));
//match _response.hits.hits[0]._source.include.field1:
this.IsMatch(_response.hits.hits[0]._source.include.field1, @"v1");
//is_false _response.hits.hits[0]._source.include.field2;
this.IsFalse(_response.hits.hits[0]._source.include.field2);
//do search
_body = new {
query= new {
match_all= new {}
}
};
this.Do(()=> _client.Search(_body, nv=>nv
.AddQueryString("_source_exclude", @"count")
));
//match _response.hits.hits[0]._source.include:
this.IsMatch(_response.hits.hits[0]._source.include, new {
field1= "v1",
field2= "v2"
});
//is_false _response.hits.hits[0]._source.count;
this.IsFalse(_response.hits.hits[0]._source.count);
//do search
_body = new {
_source= new [] {
"include.field1",
"include.field2"
},
query= new {
match_all= new {}
}
};
this.Do(()=> _client.Search(_body));
//match _response.hits.hits[0]._source.include.field1:
this.IsMatch(_response.hits.hits[0]._source.include.field1, @"v1");
//match _response.hits.hits[0]._source.include.field2:
this.IsMatch(_response.hits.hits[0]._source.include.field2, @"v2");
//is_false _response.hits.hits[0]._source.count;
this.IsFalse(_response.hits.hits[0]._source.count);
//do search
_body = new {
_source= new {
include= new [] {
"include.field1",
"include.field2"
}
},
query= new {
match_all= new {}
}
};
this.Do(()=> _client.Search(_body));
//match _response.hits.hits[0]._source.include.field1:
this.IsMatch(_response.hits.hits[0]._source.include.field1, @"v1");
//match _response.hits.hits[0]._source.include.field2:
this.IsMatch(_response.hits.hits[0]._source.include.field2, @"v2");
//is_false _response.hits.hits[0]._source.count;
this.IsFalse(_response.hits.hits[0]._source.count);
//do search
_body = new {
_source= new {
includes= "include",
excludes= "*.field2"
},
query= new {
match_all= new {}
}
};
this.Do(()=> _client.Search(_body));
//match _response.hits.hits[0]._source.include.field1:
this.IsMatch(_response.hits.hits[0]._source.include.field1, @"v1");
//is_false _response.hits.hits[0]._source.include.field2;
this.IsFalse(_response.hits.hits[0]._source.include.field2);
//do search
_body = new {
fields= new [] {
"include.field2"
},
query= new {
match_all= new {}
}
};
this.Do(()=> _client.Search(_body));
//match _response.hits.hits[0].fields:
this.IsMatch(_response.hits.hits[0].fields, new Dictionary<string, object> {
{ @"include.field2", new [] {"v2"} }
});
//is_false _response.hits.hits[0]._source;
this.IsFalse(_response.hits.hits[0]._source);
//do search
_body = new {
fields= new [] {
"include.field2",
"_source"
},
query= new {
match_all= new {}
}
};
this.Do(()=> _client.Search(_body));
//match _response.hits.hits[0].fields:
this.IsMatch(_response.hits.hits[0].fields, new Dictionary<string, object> {
{ @"include.field2", new [] {"v2"} }
});
//is_true _response.hits.hits[0]._source;
this.IsTrue(_response.hits.hits[0]._source);
}
}
}
}
| |
// Zlib.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009-2011 Dino Chiesa and Microsoft Corporation.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// Last Saved: <2011-August-03 19:52:28>
//
// ------------------------------------------------------------------
//
// This module defines classes for ZLIB compression and
// decompression. This code is derived from the jzlib implementation of
// zlib, but significantly modified. The object model is not the same,
// and many of the behaviors are new or different. Nonetheless, in
// keeping with the license for jzlib, the copyright to that code is
// included below.
//
// ------------------------------------------------------------------
//
// The following notice applies to jzlib:
//
// Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the distribution.
//
// 3. The names of the authors may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
// INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// -----------------------------------------------------------------------
//
// jzlib is based on zlib-1.1.3.
//
// The following notice applies to zlib:
//
// -----------------------------------------------------------------------
//
// Copyright (C) 1995-2004 Jean-loup Gailly and Mark Adler
//
// The ZLIB software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
// Jean-loup Gailly jloup@gzip.org
// Mark Adler madler@alumni.caltech.edu
//
// -----------------------------------------------------------------------
using System;
using Interop=System.Runtime.InteropServices;
namespace Ionic.Zlib
{
/// <summary>
/// Describes how to flush the current deflate operation.
/// </summary>
/// <remarks>
/// The different FlushType values are useful when using a Deflate in a streaming application.
/// </remarks>
public enum FlushType
{
/// <summary>No flush at all.</summary>
None = 0,
/// <summary>Closes the current block, but doesn't flush it to
/// the output. Used internally only in hypothetical
/// scenarios. This was supposed to be removed by Zlib, but it is
/// still in use in some edge cases.
/// </summary>
Partial,
/// <summary>
/// Use this during compression to specify that all pending output should be
/// flushed to the output buffer and the output should be aligned on a byte
/// boundary. You might use this in a streaming communication scenario, so that
/// the decompressor can get all input data available so far. When using this
/// with a ZlibCodec, <c>AvailableBytesIn</c> will be zero after the call if
/// enough output space has been provided before the call. Flushing will
/// degrade compression and so it should be used only when necessary.
/// </summary>
Sync,
/// <summary>
/// Use this during compression to specify that all output should be flushed, as
/// with <c>FlushType.Sync</c>, but also, the compression state should be reset
/// so that decompression can restart from this point if previous compressed
/// data has been damaged or if random access is desired. Using
/// <c>FlushType.Full</c> too often can significantly degrade the compression.
/// </summary>
Full,
/// <summary>Signals the end of the compression/decompression stream.</summary>
Finish,
}
/// <summary>
/// The compression level to be used when using a DeflateStream or ZlibStream with CompressionMode.Compress.
/// </summary>
public enum CompressionLevel
{
/// <summary>
/// None means that the data will be simply stored, with no change at all.
/// If you are producing ZIPs for use on Mac OSX, be aware that archives produced with CompressionLevel.None
/// cannot be opened with the default zip reader. Use a different CompressionLevel.
/// </summary>
None= 0,
/// <summary>
/// Same as None.
/// </summary>
Level0 = 0,
/// <summary>
/// The fastest but least effective compression.
/// </summary>
BestSpeed = 1,
/// <summary>
/// A synonym for BestSpeed.
/// </summary>
Level1 = 1,
/// <summary>
/// A little slower, but better, than level 1.
/// </summary>
Level2 = 2,
/// <summary>
/// A little slower, but better, than level 2.
/// </summary>
Level3 = 3,
/// <summary>
/// A little slower, but better, than level 3.
/// </summary>
Level4 = 4,
/// <summary>
/// A little slower than level 4, but with better compression.
/// </summary>
Level5 = 5,
/// <summary>
/// The default compression level, with a good balance of speed and compression efficiency.
/// </summary>
Default = 6,
/// <summary>
/// A synonym for Default.
/// </summary>
Level6 = 6,
/// <summary>
/// Pretty good compression!
/// </summary>
Level7 = 7,
/// <summary>
/// Better compression than Level7!
/// </summary>
Level8 = 8,
/// <summary>
/// The "best" compression, where best means greatest reduction in size of the input data stream.
/// This is also the slowest compression.
/// </summary>
BestCompression = 9,
/// <summary>
/// A synonym for BestCompression.
/// </summary>
Level9 = 9,
}
/// <summary>
/// Describes options for how the compression algorithm is executed. Different strategies
/// work better on different sorts of data. The strategy parameter can affect the compression
/// ratio and the speed of compression but not the correctness of the compresssion.
/// </summary>
public enum CompressionStrategy
{
/// <summary>
/// The default strategy is probably the best for normal data.
/// </summary>
Default = 0,
/// <summary>
/// The <c>Filtered</c> strategy is intended to be used most effectively with data produced by a
/// filter or predictor. By this definition, filtered data consists mostly of small
/// values with a somewhat random distribution. In this case, the compression algorithm
/// is tuned to compress them better. The effect of <c>Filtered</c> is to force more Huffman
/// coding and less string matching; it is a half-step between <c>Default</c> and <c>HuffmanOnly</c>.
/// </summary>
Filtered = 1,
/// <summary>
/// Using <c>HuffmanOnly</c> will force the compressor to do Huffman encoding only, with no
/// string matching.
/// </summary>
HuffmanOnly = 2,
}
/// <summary>
/// An enum to specify the direction of transcoding - whether to compress or decompress.
/// </summary>
public enum CompressionMode
{
/// <summary>
/// Used to specify that the stream should compress the data.
/// </summary>
Compress= 0,
/// <summary>
/// Used to specify that the stream should decompress the data.
/// </summary>
Decompress = 1,
}
/// <summary>
/// A general purpose exception class for exceptions in the Zlib library.
/// </summary>
[Interop.GuidAttribute("ebc25cf6-9120-4283-b972-0e5520d0000E")]
public class ZlibException : System.Exception
{
/// <summary>
/// The ZlibException class captures exception information generated
/// by the Zlib library.
/// </summary>
public ZlibException()
: base()
{
}
/// <summary>
/// This ctor collects a message attached to the exception.
/// </summary>
/// <param name="s">the message for the exception.</param>
public ZlibException(System.String s)
: base(s)
{
}
}
internal class SharedUtils
{
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static int URShift(int number, int bits)
{
return (int)((uint)number >> bits);
}
#if NOT
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static long URShift(long number, int bits)
{
return (long) ((UInt64)number >> bits);
}
#endif
/// <summary>
/// Reads a number of characters from the current source TextReader and writes
/// the data to the target array at the specified index.
/// </summary>
///
/// <param name="sourceTextReader">The source TextReader to read from</param>
/// <param name="target">Contains the array of characteres read from the source TextReader.</param>
/// <param name="start">The starting index of the target array.</param>
/// <param name="count">The maximum number of characters to read from the source TextReader.</param>
///
/// <returns>
/// The number of characters read. The number will be less than or equal to
/// count depending on the data available in the source TextReader. Returns -1
/// if the end of the stream is reached.
/// </returns>
public static System.Int32 ReadInput(System.IO.TextReader sourceTextReader, byte[] target, int start, int count)
{
// Returns 0 bytes if not enough space in target
if (target.Length == 0) return 0;
char[] charArray = new char[target.Length];
int bytesRead = sourceTextReader.Read(charArray, start, count);
// Returns -1 if EOF
if (bytesRead == 0) return -1;
for (int index = start; index < start + bytesRead; index++)
target[index] = (byte)charArray[index];
return bytesRead;
}
internal static byte[] ToByteArray(System.String sourceString)
{
return System.Text.Encoding.UTF8.GetBytes(sourceString);
}
internal static char[] ToCharArray(byte[] byteArray)
{
return System.Text.Encoding.UTF8.GetChars(byteArray);
}
}
internal static class InternalConstants
{
internal static readonly int MAX_BITS = 15;
internal static readonly int BL_CODES = 19;
internal static readonly int D_CODES = 30;
internal static readonly int LITERALS = 256;
internal static readonly int LENGTH_CODES = 29;
internal static readonly int L_CODES = (LITERALS + 1 + LENGTH_CODES);
// Bit length codes must not exceed MAX_BL_BITS bits
internal static readonly int MAX_BL_BITS = 7;
// repeat previous bit length 3-6 times (2 bits of repeat count)
internal static readonly int REP_3_6 = 16;
// repeat a zero length 3-10 times (3 bits of repeat count)
internal static readonly int REPZ_3_10 = 17;
// repeat a zero length 11-138 times (7 bits of repeat count)
internal static readonly int REPZ_11_138 = 18;
}
internal sealed class StaticTree
{
internal static readonly short[] lengthAndLiteralsTreeCodes = new short[] {
12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172, 8, 108, 8, 236, 8,
28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188, 8, 124, 8, 252, 8,
2, 8, 130, 8, 66, 8, 194, 8, 34, 8, 162, 8, 98, 8, 226, 8,
18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, 114, 8, 242, 8,
10, 8, 138, 8, 74, 8, 202, 8, 42, 8, 170, 8, 106, 8, 234, 8,
26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, 8, 122, 8, 250, 8,
6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8, 102, 8, 230, 8,
22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182, 8, 118, 8, 246, 8,
14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174, 8, 110, 8, 238, 8,
30, 8, 158, 8, 94, 8, 222, 8, 62, 8, 190, 8, 126, 8, 254, 8,
1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8, 97, 8, 225, 8,
17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177, 8, 113, 8, 241, 8,
9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8, 105, 8, 233, 8,
25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, 8, 121, 8, 249, 8,
5, 8, 133, 8, 69, 8, 197, 8, 37, 8, 165, 8, 101, 8, 229, 8,
21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, 8, 117, 8, 245, 8,
13, 8, 141, 8, 77, 8, 205, 8, 45, 8, 173, 8, 109, 8, 237, 8,
29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189, 8, 125, 8, 253, 8,
19, 9, 275, 9, 147, 9, 403, 9, 83, 9, 339, 9, 211, 9, 467, 9,
51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371, 9, 243, 9, 499, 9,
11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331, 9, 203, 9, 459, 9,
43, 9, 299, 9, 171, 9, 427, 9, 107, 9, 363, 9, 235, 9, 491, 9,
27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347, 9, 219, 9, 475, 9,
59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379, 9, 251, 9, 507, 9,
7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327, 9, 199, 9, 455, 9,
39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359, 9, 231, 9, 487, 9,
23, 9, 279, 9, 151, 9, 407, 9, 87, 9, 343, 9, 215, 9, 471, 9,
55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375, 9, 247, 9, 503, 9,
15, 9, 271, 9, 143, 9, 399, 9, 79, 9, 335, 9, 207, 9, 463, 9,
47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367, 9, 239, 9, 495, 9,
31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, 9, 223, 9, 479, 9,
63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383, 9, 255, 9, 511, 9,
0, 7, 64, 7, 32, 7, 96, 7, 16, 7, 80, 7, 48, 7, 112, 7,
8, 7, 72, 7, 40, 7, 104, 7, 24, 7, 88, 7, 56, 7, 120, 7,
4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7, 52, 7, 116, 7,
3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8, 99, 8, 227, 8
};
internal static readonly short[] distTreeCodes = new short[] {
0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20, 5, 12, 5, 28, 5,
2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30, 5,
1, 5, 17, 5, 9, 5, 25, 5, 5, 5, 21, 5, 13, 5, 29, 5,
3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5 };
internal static readonly StaticTree Literals;
internal static readonly StaticTree Distances;
internal static readonly StaticTree BitLengths;
internal short[] treeCodes; // static tree or null
internal int[] extraBits; // extra bits for each code or null
internal int extraBase; // base index for extra_bits
internal int elems; // max number of elements in the tree
internal int maxLength; // max bit length for the codes
private StaticTree(short[] treeCodes, int[] extraBits, int extraBase, int elems, int maxLength)
{
this.treeCodes = treeCodes;
this.extraBits = extraBits;
this.extraBase = extraBase;
this.elems = elems;
this.maxLength = maxLength;
}
static StaticTree()
{
Literals = new StaticTree(lengthAndLiteralsTreeCodes, Tree.ExtraLengthBits, InternalConstants.LITERALS + 1, InternalConstants.L_CODES, InternalConstants.MAX_BITS);
Distances = new StaticTree(distTreeCodes, Tree.ExtraDistanceBits, 0, InternalConstants.D_CODES, InternalConstants.MAX_BITS);
BitLengths = new StaticTree(null, Tree.extra_blbits, 0, InternalConstants.BL_CODES, InternalConstants.MAX_BL_BITS);
}
}
/// <summary>
/// Computes an Adler-32 checksum.
/// </summary>
/// <remarks>
/// The Adler checksum is similar to a CRC checksum, but faster to compute, though less
/// reliable. It is used in producing RFC1950 compressed streams. The Adler checksum
/// is a required part of the "ZLIB" standard. Applications will almost never need to
/// use this class directly.
/// </remarks>
///
/// <exclude/>
public sealed class Adler
{
// largest prime smaller than 65536
private static readonly uint BASE = 65521;
// NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
private static readonly int NMAX = 5552;
#pragma warning disable 3001
#pragma warning disable 3002
/// <summary>
/// Calculates the Adler32 checksum.
/// </summary>
/// <remarks>
/// <para>
/// This is used within ZLIB. You probably don't need to use this directly.
/// </para>
/// </remarks>
/// <example>
/// To compute an Adler32 checksum on a byte array:
/// <code>
/// var adler = Adler.Adler32(0, null, 0, 0);
/// adler = Adler.Adler32(adler, buffer, index, length);
/// </code>
/// </example>
public static uint Adler32(uint adler, byte[] buf, int index, int len)
{
if (buf == null)
return 1;
uint s1 = (uint) (adler & 0xffff);
uint s2 = (uint) ((adler >> 16) & 0xffff);
while (len > 0)
{
int k = len < NMAX ? len : NMAX;
len -= k;
while (k >= 16)
{
//s1 += (buf[index++] & 0xff); s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
k -= 16;
}
if (k != 0)
{
do
{
s1 += buf[index++];
s2 += s1;
}
while (--k != 0);
}
s1 %= BASE;
s2 %= BASE;
}
return (uint)((s2 << 16) | s1);
}
#pragma warning restore 3001
#pragma warning restore 3002
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.Animation;
using ESRI.ArcGIS.ADF;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.ADF.CATIDs;
namespace AnimationDeveloperSamples
{
[Guid("E0DFDD9F-1C59-4FE8-89FA-71BE8D242A9C")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("AnimationDeveloperSamples.AnimationTypeMapGraphic")]
public class AnimationTypeMapGraphic : IAGAnimationType, IAGAnimationTypeUI
{
#region COM Registration Function(s)
[ComRegisterFunction()]
[ComVisible(false)]
static void RegisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryRegistration(registerType);
//
// TODO: Add any COM registration code here
//
}
[ComUnregisterFunction()]
[ComVisible(false)]
static void UnregisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryUnregistration(registerType);
//
// TODO: Add any COM unregistration code here
//
}
#region ArcGIS Component Category Registrar generated code
/// <summary>
/// Required method for ArcGIS Component Category registration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryRegistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
MapAnimationTypes.Register(regKey);
}
/// <summary>
/// Required method for ArcGIS Component Category unregistration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryUnregistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
MapAnimationTypes.Unregister(regKey);
}
#endregion
#endregion
private string[] propName;
private esriAnimationPropertyType[] propType;
private string typeName;
#region constructor
public AnimationTypeMapGraphic()
{
propName = new string[2];
propName[0] = "Position";
propName[1] = "Rotation";
propType = new esriAnimationPropertyType[2];
propType[0] = esriAnimationPropertyType.esriAnimationPropertyPoint;
propType[1] = esriAnimationPropertyType.esriAnimationPropertyDouble;
typeName = "Map Graphic";
}
#endregion
#region IAGAnimationType members
public esriAnimationClass AnimationClass
{
get
{
return esriAnimationClass.esriAnimationClassGeneric;
}
}
public object get_AnimationObjectByID(IAGAnimationContainer pContainer, int objectID)
{
IArray array;
array = get_ObjectArray(pContainer);
IElement elem = (IElement)array.get_Element(objectID);
return elem;
}
public int get_AnimationObjectID(IAGAnimationContainer pContainer, object pObject)
{
IArray array = get_ObjectArray(pContainer);
int count = array.Count;
int objectID = 0;
for (int i = 0; i < count; i++)
{
IElement elem = (IElement)array.get_Element(i);
if (elem == pObject)
break;
objectID++;
}
return objectID;
}
public string get_AnimationObjectName(IAGAnimationContainer pContainer, object pObject)
{
string objectName;
IElementProperties elemProps = (IElementProperties)pObject;
objectName = elemProps.Name;
return objectName;
}
public bool get_AppliesToObject(object pObject)
{
if ((pObject is IMarkerElement) || (pObject is IGroupElement) || (pObject is ITextElement))
return true;
else
return false;
}
public UID CLSID
{
get
{
UID uid = new UIDClass();
uid.Value = "{E0DFDD9F-1C59-4FE8-89FA-71BE8D242A9C}";
return uid;
}
}
public UID KeyframeCLSID
{
get
{
UID uid = new UIDClass();
uid.Value = "{B2263D65-7FAF-4118-A255-5B0D47E453EE}";
return uid;
}
}
public string Name
{
get
{
return typeName;
}
}
public IArray get_ObjectArray(IAGAnimationContainer pContainer)
{
IActiveView view = pContainer.CurrentView as IActiveView;
IGraphicsContainer graphicsContainer = view as IGraphicsContainer;
graphicsContainer.Reset();
IArray array = new ArrayClass();
IElement elem = graphicsContainer.Next();
while (elem != null)
{
if(get_AppliesToObject(elem))
array.Add(elem);
elem = graphicsContainer.Next();
}
return array;
}
public int PropertyCount
{
get
{
return 2;
}
}
public string get_PropertyName(int index)
{
if (index >= 0 && index < 2)
return propName[index];
else
return null;
}
public esriAnimationPropertyType get_PropertyType(int index)
{
return propType[index];
}
public void ResetObject(IAGAnimationContainer pContainer, object pObject)
{
return;
}
public void UpdateTrackExtensions(IAGAnimationTrack pTrack)
{
return;
}
#endregion
#region IAGAnimationTypeUI members
public IStringArray get_ChoiceList(int propIndex, int columnIndex)
{
return null;
}
public int get_ColumnCount(int propIndex)
{
if (propIndex == 0)
return 2;
else
return 1;
}
public string get_ColumnName(int propIndex, int columnIndex)
{
if (propIndex == 0)
{
if (columnIndex == 0)
return "Position:X";
else
return "Position:Y";
}
else if (propIndex == 1)
{
return "Rotation";
}
return null;
}
#endregion
}
}
| |
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <author name="Daniel Grunwald"/>
// <version>$Revision: 5674 $</version>
// </file>
using ICSharpCode.AvalonEdit.Utils;
using System;
using System.IO;
namespace ICSharpCode.AvalonEdit.Document
{
/// <summary>
/// Interface for read-only access to a text source.
/// </summary>
/// <seealso cref="TextDocument"/>
/// <seealso cref="StringTextSource"/>
public interface ITextSource
{
/// <summary>
/// Gets the whole text as string.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
string Text { get; }
/// <summary>
/// Is raised when the Text property changes.
/// </summary>
event EventHandler TextChanged;
/// <summary>
/// Gets the total text length.
/// </summary>
/// <returns>The length of the text, in characters.</returns>
/// <remarks>This is the same as Text.Length, but is more efficient because
/// it doesn't require creating a String object.</remarks>
int TextLength { get; }
/// <summary>
/// Gets a character at the specified position in the document.
/// </summary>
/// <paramref name="offset">The index of the character to get.</paramref>
/// <exception cref="ArgumentOutOfRangeException">Offset is outside the valid range (0 to TextLength-1).</exception>
/// <returns>The character at the specified position.</returns>
/// <remarks>This is the same as Text[offset], but is more efficient because
/// it doesn't require creating a String object.</remarks>
char GetCharAt(int offset);
/// <summary>
/// Retrieves the text for a portion of the document.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">offset or length is outside the valid range.</exception>
/// <remarks>This is the same as Text.Substring, but is more efficient because
/// it doesn't require creating a String object for the whole document.</remarks>
string GetText(int offset, int length);
/// <summary>
/// Creates a snapshot of the current text.
/// </summary>
/// <remarks>
/// This method is generally not thread-safe when called on a mutable text buffer, but the resulting text buffer is immutable and thread-safe.
/// However, some implementing classes may provide additional thread-safety guarantees, see <see cref="TextDocument.CreateSnapshot()">TextDocument.CreateSnapshot</see>.
/// </remarks>
ITextSource CreateSnapshot();
/// <summary>
/// Creates a snapshot of a part of the current text.
/// </summary>
/// <remarks>
/// This method is generally not thread-safe when called on a mutable text buffer, but the resulting text buffer is immutable and thread-safe.
/// However, some implementing classes may provide additional thread-safety guarantees, see <see cref="TextDocument.CreateSnapshot()">TextDocument.CreateSnapshot</see>.
/// </remarks>
ITextSource CreateSnapshot(int offset, int length);
/// <summary>
/// Creates a text reader.
/// If the text is changed while a reader is active, the reader will continue to read from the old text version.
/// </summary>
TextReader CreateReader();
}
/// <summary>
/// Implements the ITextSource interface by wrapping another TextSource
/// and viewing only a part of the text.
/// </summary>
[Obsolete("This class will be removed in a future version of AvalonEdit")]
public sealed class TextSourceView : ITextSource
{
readonly ITextSource baseTextSource;
readonly ISegment viewedSegment;
/// <summary>
/// Creates a new TextSourceView object.
/// </summary>
/// <param name="baseTextSource">The base text source.</param>
/// <param name="viewedSegment">A text segment from the base text source</param>
public TextSourceView(ITextSource baseTextSource, ISegment viewedSegment)
{
if (baseTextSource == null)
throw new ArgumentNullException("baseTextSource");
if (viewedSegment == null)
throw new ArgumentNullException("viewedSegment");
this.baseTextSource = baseTextSource;
this.viewedSegment = viewedSegment;
}
/// <inheritdoc/>
public event EventHandler TextChanged {
add { baseTextSource.TextChanged += value; }
remove { baseTextSource.TextChanged -= value; }
}
/// <inheritdoc/>
public string Text {
get {
return baseTextSource.GetText(viewedSegment.Offset, viewedSegment.Length);
}
}
/// <inheritdoc/>
public int TextLength {
get { return viewedSegment.Length; }
}
/// <inheritdoc/>
public char GetCharAt(int offset)
{
return baseTextSource.GetCharAt(viewedSegment.Offset + offset);
}
/// <inheritdoc/>
public string GetText(int offset, int length)
{
return baseTextSource.GetText(viewedSegment.Offset + offset, length);
}
/// <inheritdoc/>
public ITextSource CreateSnapshot()
{
return baseTextSource.CreateSnapshot(viewedSegment.Offset, viewedSegment.Length);
}
/// <inheritdoc/>
public ITextSource CreateSnapshot(int offset, int length)
{
return baseTextSource.CreateSnapshot(viewedSegment.Offset + offset, length);
}
/// <inheritdoc/>
public TextReader CreateReader()
{
return CreateSnapshot().CreateReader();
}
}
/// <summary>
/// Implements the ITextSource interface using a string.
/// </summary>
public sealed class StringTextSource : ITextSource
{
readonly string text;
/// <summary>
/// Creates a new StringTextSource.
/// </summary>
public StringTextSource(string text)
{
if (text == null)
throw new ArgumentNullException("text");
this.text = text;
}
// Text can never change
event EventHandler ITextSource.TextChanged { add {} remove {} }
/// <inheritdoc/>
public string Text {
get { return text; }
}
/// <inheritdoc/>
public int TextLength {
get { return text.Length; }
}
/// <inheritdoc/>
public char GetCharAt(int offset)
{
// GetCharAt must throw ArgumentOutOfRangeException, not IndexOutOfRangeException
if (offset < 0 || offset >= text.Length)
throw new ArgumentOutOfRangeException("offset", offset, "offset must be between 0 and " + (text.Length - 1));
return text[offset];
}
/// <inheritdoc/>
public string GetText(int offset, int length)
{
return text.Substring(offset, length);
}
/// <inheritdoc/>
public TextReader CreateReader()
{
return new StringReader(text);
}
/// <inheritdoc/>
public ITextSource CreateSnapshot()
{
return this; // StringTextSource already is immutable
}
/// <inheritdoc/>
public ITextSource CreateSnapshot(int offset, int length)
{
return new StringTextSource(text.Substring(offset, length));
}
}
/// <summary>
/// Implements the ITextSource interface using a rope.
/// </summary>
public sealed class RopeTextSource : ITextSource
{
readonly Rope<char> rope;
/// <summary>
/// Creates a new RopeTextSource.
/// </summary>
public RopeTextSource(Rope<char> rope)
{
if (rope == null)
throw new ArgumentNullException("rope");
this.rope = rope;
}
/// <summary>
/// Returns a clone of the rope used for this text source.
/// </summary>
/// <remarks>
/// RopeTextSource only publishes a copy of the contained rope to ensure that the underlying rope cannot be modified.
/// Unless the creator of the RopeTextSource still has a reference on the rope, RopeTextSource is immutable.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification="Not a property because it creates a clone")]
public Rope<char> GetRope()
{
return rope.Clone();
}
// Change event is not supported
event EventHandler ITextSource.TextChanged { add {} remove {} }
/// <inheritdoc/>
public string Text {
get { return rope.ToString(); }
}
/// <inheritdoc/>
public int TextLength {
get { return rope.Length; }
}
/// <inheritdoc/>
public char GetCharAt(int offset)
{
return rope[offset];
}
/// <inheritdoc/>
public string GetText(int offset, int length)
{
return rope.ToString(offset, length);
}
/// <inheritdoc/>
public TextReader CreateReader()
{
return new RopeTextReader(rope);
}
/// <inheritdoc/>
public ITextSource CreateSnapshot()
{
// we clone the underlying rope because the creator of the RopeTextSource might be modifying it
return new RopeTextSource(rope.Clone());
}
/// <inheritdoc/>
public ITextSource CreateSnapshot(int offset, int length)
{
return new RopeTextSource(rope.GetRange(offset, length));
}
}
}
| |
// 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 SubtractDouble()
{
var test = new SimpleBinaryOpTest__SubtractDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// 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();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// 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 works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__SubtractDouble
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Double);
private static Double[] _data1 = new Double[ElementCount];
private static Double[] _data2 = new Double[ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private SimpleBinaryOpTest__DataTable<Double> _dataTable;
static SimpleBinaryOpTest__SubtractDouble()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__SubtractDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Double>(_data1, _data2, new Double[ElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Subtract(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Subtract(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Subtract(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Subtract(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse2.Subtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.Subtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.Subtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__SubtractDouble();
var result = Sse2.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Subtract(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Double> left, Vector128<Double> right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[ElementCount];
Double[] inArray2 = new Double[ElementCount];
Double[] outArray = new Double[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[ElementCount];
Double[] inArray2 = new Double[ElementCount];
Double[] outArray = new Double[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
if (BitConverter.DoubleToInt64Bits(left[0] - right[0]) != BitConverter.DoubleToInt64Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if (BitConverter.DoubleToInt64Bits(left[i] - right[i]) != BitConverter.DoubleToInt64Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Subtract)}<Double>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the AprActividadControlPerinatal class.
/// </summary>
[Serializable]
public partial class AprActividadControlPerinatalCollection : ActiveList<AprActividadControlPerinatal, AprActividadControlPerinatalCollection>
{
public AprActividadControlPerinatalCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>AprActividadControlPerinatalCollection</returns>
public AprActividadControlPerinatalCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
AprActividadControlPerinatal o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the APR_ActividadControlPerinatal table.
/// </summary>
[Serializable]
public partial class AprActividadControlPerinatal : ActiveRecord<AprActividadControlPerinatal>, IActiveRecord
{
#region .ctors and Default Settings
public AprActividadControlPerinatal()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public AprActividadControlPerinatal(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public AprActividadControlPerinatal(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public AprActividadControlPerinatal(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("APR_ActividadControlPerinatal", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdActividadControlPerinatal = new TableSchema.TableColumn(schema);
colvarIdActividadControlPerinatal.ColumnName = "idActividadControlPerinatal";
colvarIdActividadControlPerinatal.DataType = DbType.Int32;
colvarIdActividadControlPerinatal.MaxLength = 0;
colvarIdActividadControlPerinatal.AutoIncrement = true;
colvarIdActividadControlPerinatal.IsNullable = false;
colvarIdActividadControlPerinatal.IsPrimaryKey = true;
colvarIdActividadControlPerinatal.IsForeignKey = false;
colvarIdActividadControlPerinatal.IsReadOnly = false;
colvarIdActividadControlPerinatal.DefaultSetting = @"";
colvarIdActividadControlPerinatal.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdActividadControlPerinatal);
TableSchema.TableColumn colvarIdHistoriaClinicaPerinatal = new TableSchema.TableColumn(schema);
colvarIdHistoriaClinicaPerinatal.ColumnName = "idHistoriaClinicaPerinatal";
colvarIdHistoriaClinicaPerinatal.DataType = DbType.Int32;
colvarIdHistoriaClinicaPerinatal.MaxLength = 0;
colvarIdHistoriaClinicaPerinatal.AutoIncrement = false;
colvarIdHistoriaClinicaPerinatal.IsNullable = false;
colvarIdHistoriaClinicaPerinatal.IsPrimaryKey = false;
colvarIdHistoriaClinicaPerinatal.IsForeignKey = false;
colvarIdHistoriaClinicaPerinatal.IsReadOnly = false;
colvarIdHistoriaClinicaPerinatal.DefaultSetting = @"";
colvarIdHistoriaClinicaPerinatal.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdHistoriaClinicaPerinatal);
TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema);
colvarIdEfector.ColumnName = "idEfector";
colvarIdEfector.DataType = DbType.Int32;
colvarIdEfector.MaxLength = 0;
colvarIdEfector.AutoIncrement = false;
colvarIdEfector.IsNullable = false;
colvarIdEfector.IsPrimaryKey = false;
colvarIdEfector.IsForeignKey = true;
colvarIdEfector.IsReadOnly = false;
colvarIdEfector.DefaultSetting = @"";
colvarIdEfector.ForeignKeyTableName = "Sys_Efector";
schema.Columns.Add(colvarIdEfector);
TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema);
colvarFecha.ColumnName = "Fecha";
colvarFecha.DataType = DbType.DateTime;
colvarFecha.MaxLength = 0;
colvarFecha.AutoIncrement = false;
colvarFecha.IsNullable = true;
colvarFecha.IsPrimaryKey = false;
colvarFecha.IsForeignKey = false;
colvarFecha.IsReadOnly = false;
colvarFecha.DefaultSetting = @"";
colvarFecha.ForeignKeyTableName = "";
schema.Columns.Add(colvarFecha);
TableSchema.TableColumn colvarIdActividadEmbarazo = new TableSchema.TableColumn(schema);
colvarIdActividadEmbarazo.ColumnName = "idActividadEmbarazo";
colvarIdActividadEmbarazo.DataType = DbType.Int32;
colvarIdActividadEmbarazo.MaxLength = 0;
colvarIdActividadEmbarazo.AutoIncrement = false;
colvarIdActividadEmbarazo.IsNullable = true;
colvarIdActividadEmbarazo.IsPrimaryKey = false;
colvarIdActividadEmbarazo.IsForeignKey = true;
colvarIdActividadEmbarazo.IsReadOnly = false;
colvarIdActividadEmbarazo.DefaultSetting = @"";
colvarIdActividadEmbarazo.ForeignKeyTableName = "APR_ActividadEmbarazo";
schema.Columns.Add(colvarIdActividadEmbarazo);
TableSchema.TableColumn colvarMotivo = new TableSchema.TableColumn(schema);
colvarMotivo.ColumnName = "Motivo";
colvarMotivo.DataType = DbType.AnsiString;
colvarMotivo.MaxLength = -1;
colvarMotivo.AutoIncrement = false;
colvarMotivo.IsNullable = true;
colvarMotivo.IsPrimaryKey = false;
colvarMotivo.IsForeignKey = false;
colvarMotivo.IsReadOnly = false;
colvarMotivo.DefaultSetting = @"";
colvarMotivo.ForeignKeyTableName = "";
schema.Columns.Add(colvarMotivo);
TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema);
colvarDescripcion.ColumnName = "Descripcion";
colvarDescripcion.DataType = DbType.AnsiString;
colvarDescripcion.MaxLength = -1;
colvarDescripcion.AutoIncrement = false;
colvarDescripcion.IsNullable = true;
colvarDescripcion.IsPrimaryKey = false;
colvarDescripcion.IsForeignKey = false;
colvarDescripcion.IsReadOnly = false;
colvarDescripcion.DefaultSetting = @"";
colvarDescripcion.ForeignKeyTableName = "";
schema.Columns.Add(colvarDescripcion);
TableSchema.TableColumn colvarIdProfesional = new TableSchema.TableColumn(schema);
colvarIdProfesional.ColumnName = "idProfesional";
colvarIdProfesional.DataType = DbType.Int32;
colvarIdProfesional.MaxLength = 0;
colvarIdProfesional.AutoIncrement = false;
colvarIdProfesional.IsNullable = true;
colvarIdProfesional.IsPrimaryKey = false;
colvarIdProfesional.IsForeignKey = true;
colvarIdProfesional.IsReadOnly = false;
colvarIdProfesional.DefaultSetting = @"";
colvarIdProfesional.ForeignKeyTableName = "Sys_Profesional";
schema.Columns.Add(colvarIdProfesional);
TableSchema.TableColumn colvarCreatedBy = new TableSchema.TableColumn(schema);
colvarCreatedBy.ColumnName = "CreatedBy";
colvarCreatedBy.DataType = DbType.AnsiString;
colvarCreatedBy.MaxLength = 50;
colvarCreatedBy.AutoIncrement = false;
colvarCreatedBy.IsNullable = true;
colvarCreatedBy.IsPrimaryKey = false;
colvarCreatedBy.IsForeignKey = false;
colvarCreatedBy.IsReadOnly = false;
colvarCreatedBy.DefaultSetting = @"";
colvarCreatedBy.ForeignKeyTableName = "";
schema.Columns.Add(colvarCreatedBy);
TableSchema.TableColumn colvarCreatedOn = new TableSchema.TableColumn(schema);
colvarCreatedOn.ColumnName = "CreatedOn";
colvarCreatedOn.DataType = DbType.DateTime;
colvarCreatedOn.MaxLength = 0;
colvarCreatedOn.AutoIncrement = false;
colvarCreatedOn.IsNullable = true;
colvarCreatedOn.IsPrimaryKey = false;
colvarCreatedOn.IsForeignKey = false;
colvarCreatedOn.IsReadOnly = false;
colvarCreatedOn.DefaultSetting = @"";
colvarCreatedOn.ForeignKeyTableName = "";
schema.Columns.Add(colvarCreatedOn);
TableSchema.TableColumn colvarModifiedBy = new TableSchema.TableColumn(schema);
colvarModifiedBy.ColumnName = "ModifiedBy";
colvarModifiedBy.DataType = DbType.AnsiString;
colvarModifiedBy.MaxLength = 50;
colvarModifiedBy.AutoIncrement = false;
colvarModifiedBy.IsNullable = true;
colvarModifiedBy.IsPrimaryKey = false;
colvarModifiedBy.IsForeignKey = false;
colvarModifiedBy.IsReadOnly = false;
colvarModifiedBy.DefaultSetting = @"";
colvarModifiedBy.ForeignKeyTableName = "";
schema.Columns.Add(colvarModifiedBy);
TableSchema.TableColumn colvarModifiedOn = new TableSchema.TableColumn(schema);
colvarModifiedOn.ColumnName = "ModifiedOn";
colvarModifiedOn.DataType = DbType.DateTime;
colvarModifiedOn.MaxLength = 0;
colvarModifiedOn.AutoIncrement = false;
colvarModifiedOn.IsNullable = true;
colvarModifiedOn.IsPrimaryKey = false;
colvarModifiedOn.IsForeignKey = false;
colvarModifiedOn.IsReadOnly = false;
colvarModifiedOn.DefaultSetting = @"";
colvarModifiedOn.ForeignKeyTableName = "";
schema.Columns.Add(colvarModifiedOn);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("APR_ActividadControlPerinatal",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdActividadControlPerinatal")]
[Bindable(true)]
public int IdActividadControlPerinatal
{
get { return GetColumnValue<int>(Columns.IdActividadControlPerinatal); }
set { SetColumnValue(Columns.IdActividadControlPerinatal, value); }
}
[XmlAttribute("IdHistoriaClinicaPerinatal")]
[Bindable(true)]
public int IdHistoriaClinicaPerinatal
{
get { return GetColumnValue<int>(Columns.IdHistoriaClinicaPerinatal); }
set { SetColumnValue(Columns.IdHistoriaClinicaPerinatal, value); }
}
[XmlAttribute("IdEfector")]
[Bindable(true)]
public int IdEfector
{
get { return GetColumnValue<int>(Columns.IdEfector); }
set { SetColumnValue(Columns.IdEfector, value); }
}
[XmlAttribute("Fecha")]
[Bindable(true)]
public DateTime? Fecha
{
get { return GetColumnValue<DateTime?>(Columns.Fecha); }
set { SetColumnValue(Columns.Fecha, value); }
}
[XmlAttribute("IdActividadEmbarazo")]
[Bindable(true)]
public int? IdActividadEmbarazo
{
get { return GetColumnValue<int?>(Columns.IdActividadEmbarazo); }
set { SetColumnValue(Columns.IdActividadEmbarazo, value); }
}
[XmlAttribute("Motivo")]
[Bindable(true)]
public string Motivo
{
get { return GetColumnValue<string>(Columns.Motivo); }
set { SetColumnValue(Columns.Motivo, value); }
}
[XmlAttribute("Descripcion")]
[Bindable(true)]
public string Descripcion
{
get { return GetColumnValue<string>(Columns.Descripcion); }
set { SetColumnValue(Columns.Descripcion, value); }
}
[XmlAttribute("IdProfesional")]
[Bindable(true)]
public int? IdProfesional
{
get { return GetColumnValue<int?>(Columns.IdProfesional); }
set { SetColumnValue(Columns.IdProfesional, value); }
}
[XmlAttribute("CreatedBy")]
[Bindable(true)]
public string CreatedBy
{
get { return GetColumnValue<string>(Columns.CreatedBy); }
set { SetColumnValue(Columns.CreatedBy, value); }
}
[XmlAttribute("CreatedOn")]
[Bindable(true)]
public DateTime? CreatedOn
{
get { return GetColumnValue<DateTime?>(Columns.CreatedOn); }
set { SetColumnValue(Columns.CreatedOn, value); }
}
[XmlAttribute("ModifiedBy")]
[Bindable(true)]
public string ModifiedBy
{
get { return GetColumnValue<string>(Columns.ModifiedBy); }
set { SetColumnValue(Columns.ModifiedBy, value); }
}
[XmlAttribute("ModifiedOn")]
[Bindable(true)]
public DateTime? ModifiedOn
{
get { return GetColumnValue<DateTime?>(Columns.ModifiedOn); }
set { SetColumnValue(Columns.ModifiedOn, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a AprActividadEmbarazo ActiveRecord object related to this AprActividadControlPerinatal
///
/// </summary>
public DalSic.AprActividadEmbarazo AprActividadEmbarazo
{
get { return DalSic.AprActividadEmbarazo.FetchByID(this.IdActividadEmbarazo); }
set { SetColumnValue("idActividadEmbarazo", value.IdActividadEmbarazo); }
}
/// <summary>
/// Returns a SysEfector ActiveRecord object related to this AprActividadControlPerinatal
///
/// </summary>
public DalSic.SysEfector SysEfector
{
get { return DalSic.SysEfector.FetchByID(this.IdEfector); }
set { SetColumnValue("idEfector", value.IdEfector); }
}
/// <summary>
/// Returns a SysProfesional ActiveRecord object related to this AprActividadControlPerinatal
///
/// </summary>
public DalSic.SysProfesional SysProfesional
{
get { return DalSic.SysProfesional.FetchByID(this.IdProfesional); }
set { SetColumnValue("idProfesional", value.IdProfesional); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdHistoriaClinicaPerinatal,int varIdEfector,DateTime? varFecha,int? varIdActividadEmbarazo,string varMotivo,string varDescripcion,int? varIdProfesional,string varCreatedBy,DateTime? varCreatedOn,string varModifiedBy,DateTime? varModifiedOn)
{
AprActividadControlPerinatal item = new AprActividadControlPerinatal();
item.IdHistoriaClinicaPerinatal = varIdHistoriaClinicaPerinatal;
item.IdEfector = varIdEfector;
item.Fecha = varFecha;
item.IdActividadEmbarazo = varIdActividadEmbarazo;
item.Motivo = varMotivo;
item.Descripcion = varDescripcion;
item.IdProfesional = varIdProfesional;
item.CreatedBy = varCreatedBy;
item.CreatedOn = varCreatedOn;
item.ModifiedBy = varModifiedBy;
item.ModifiedOn = varModifiedOn;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdActividadControlPerinatal,int varIdHistoriaClinicaPerinatal,int varIdEfector,DateTime? varFecha,int? varIdActividadEmbarazo,string varMotivo,string varDescripcion,int? varIdProfesional,string varCreatedBy,DateTime? varCreatedOn,string varModifiedBy,DateTime? varModifiedOn)
{
AprActividadControlPerinatal item = new AprActividadControlPerinatal();
item.IdActividadControlPerinatal = varIdActividadControlPerinatal;
item.IdHistoriaClinicaPerinatal = varIdHistoriaClinicaPerinatal;
item.IdEfector = varIdEfector;
item.Fecha = varFecha;
item.IdActividadEmbarazo = varIdActividadEmbarazo;
item.Motivo = varMotivo;
item.Descripcion = varDescripcion;
item.IdProfesional = varIdProfesional;
item.CreatedBy = varCreatedBy;
item.CreatedOn = varCreatedOn;
item.ModifiedBy = varModifiedBy;
item.ModifiedOn = varModifiedOn;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdActividadControlPerinatalColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdHistoriaClinicaPerinatalColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdEfectorColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn FechaColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn IdActividadEmbarazoColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn MotivoColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn DescripcionColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn IdProfesionalColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn CreatedByColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn CreatedOnColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn ModifiedByColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn ModifiedOnColumn
{
get { return Schema.Columns[11]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdActividadControlPerinatal = @"idActividadControlPerinatal";
public static string IdHistoriaClinicaPerinatal = @"idHistoriaClinicaPerinatal";
public static string IdEfector = @"idEfector";
public static string Fecha = @"Fecha";
public static string IdActividadEmbarazo = @"idActividadEmbarazo";
public static string Motivo = @"Motivo";
public static string Descripcion = @"Descripcion";
public static string IdProfesional = @"idProfesional";
public static string CreatedBy = @"CreatedBy";
public static string CreatedOn = @"CreatedOn";
public static string ModifiedBy = @"ModifiedBy";
public static string ModifiedOn = @"ModifiedOn";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
/******************************************************************************
* Copyright (C) Leap Motion, Inc. 2011-2017. *
* Leap Motion proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
******************************************************************************/
using System;
using System.Collections.Generic;
namespace Leap.Unity.Query {
public static class ListAndArrayExtensions {
public static T[] Fill<T>(this T[] array, T value) {
for (int i = 0; i < array.Length; i++) {
array[i] = value;
}
return array;
}
public static T[] Fill<T>(this T[] array, Func<T> constructor) {
for (int i = 0; i < array.Length; i++) {
array[i] = constructor();
}
return array;
}
public static T[,] Fill<T>(this T[,] array, T value) {
for (int i = 0; i < array.GetLength(0); i++) {
for (int j = 0; j < array.GetLength(1); j++) {
array[i, j] = value;
}
}
return array;
}
public static List<T> Fill<T>(this List<T> list, T value) {
for (int i = 0; i < list.Count; i++) {
list[i] = value;
}
return list;
}
public static List<T> Fill<T>(this List<T> list, int count, T value) {
list.Clear();
for (int i = 0; i < count; i++) {
list.Add(value);
}
return list;
}
public static List<T> FillEach<T>(this List<T> list, Func<T> generator) {
for (int i = 0; i < list.Count; i++) {
list[i] = generator();
}
return list;
}
public static List<T> FillEach<T>(this List<T> list, Func<int, T> generator) {
for (int i = 0; i < list.Count; i++) {
list[i] = generator(i);
}
return list;
}
public static List<T> FillEach<T>(this List<T> list, int count, Func<T> generator) {
list.Clear();
for (int i = 0; i < count; i++) {
list.Add(generator());
}
return list;
}
public static List<T> FillEach<T>(this List<T> list, int count, Func<int, T> generator) {
list.Clear();
for (int i = 0; i < count; i++) {
list.Add(generator(i));
}
return list;
}
public static List<T> Append<T>(this List<T> list, int count, T value) {
for (int i = 0; i < count; i++) {
list.Add(value);
}
return list;
}
public static T RemoveLast<T>(this List<T> list) {
T last = list[list.Count - 1];
list.RemoveAt(list.Count - 1);
return last;
}
/// <summary>
/// If the element exists in the list, the first instance is replaced
/// with the last element of the list.
/// </summary>
public static bool RemoveUnordered<T>(this List<T> list, T element) {
for (int i = 0; i < list.Count; i++) {
if (list[i].Equals(element)) {
list[i] = list.RemoveLast();
return true;
}
}
return false;
}
public static void RemoveAtUnordered<T>(this List<T> list, int index) {
if (list.Count - 1 == index) {
list.RemoveLast();
} else {
list[index] = list.RemoveLast();
}
}
public static void InsertUnordered<T>(this List<T> list, int index, T element) {
list.Add(list[index]);
list[index] = element;
}
/// <summary>
/// Removes each element referenced by the 'sortedIndexes' list. This
/// is much faster than calling RemoveAt for each index individually.
///
/// This operation is equivilent to calling RemoveAt for each index in
/// the *reverse* order as provided by 'sortedIndexes'.
/// </summary>
public static void RemoveAtMany<T>(this List<T> list, List<int> sortedIndexes) {
if (sortedIndexes.Count == 0) return;
//If just removing one, might as well use built-in function
if (sortedIndexes.Count == 1) {
list.RemoveAt(sortedIndexes[0]);
return;
}
int to = sortedIndexes[0];
int from = to;
int index = 0;
while (true) {
while (from == sortedIndexes[index]) {
from++;
index++;
if (index == sortedIndexes.Count) {
//Copy remaining
while (from < list.Count) {
list[to++] = list[from++];
}
//Remove the last elements on the end
list.RemoveRange(list.Count - index, index);
return;
}
}
list[to++] = list[from++];
}
}
/// <summary>
/// Inserts each element in the 'elements' list into each index referenced by the 'sorted'Indexes'
/// list. This is much faster than calling Insert for each element individually.
///
/// This operation is equivilent to calling Insert for each element in the same order the elements
/// are found in the argument list.
/// </summary>
public static void InsertMany<T>(this List<T> list, List<int> sortedIndexes, List<T> elements) {
if (sortedIndexes.Count == 0) return;
if (sortedIndexes.Count == 1) {
list.Insert(sortedIndexes[0], elements[0]);
return;
}
int from = list.Count - 1;
//First expand array to be large enough to hold all the new elements
for (int i = 0; i < sortedIndexes.Count; i++) {
list.Add(default(T));
}
int to = list.Count - 1;
int index = sortedIndexes.Count - 1;
while (true) {
while (to == sortedIndexes[index]) {
list[to--] = elements[index--];
if (index == -1) {
return;
}
}
list[to--] = list[from--];
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class NoParameterBlockTests : SharedBlockTests
{
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void SingleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void DoubleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Fact]
public void DoubleElementBlockNullArgument()
{
AssertExtensions.Throws<ArgumentNullException>("arg0", () => Expression.Block(default(Expression), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentNullException>("arg1", () => Expression.Block(Expression.Constant(1), default(Expression)));
}
[Fact]
public void DoubleElementBlockUnreadable()
{
AssertExtensions.Throws<ArgumentException>("arg0", () => Expression.Block(UnreadableExpression, Expression.Constant(1)));
AssertExtensions.Throws<ArgumentException>("arg1", () => Expression.Block(Expression.Constant(1), UnreadableExpression));
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void TripleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
Expression.Empty(),
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Fact]
public void TripleElementBlockNullArgument()
{
AssertExtensions.Throws<ArgumentNullException>("arg0", () => Expression.Block(default(Expression), Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentNullException>("arg1", () => Expression.Block(Expression.Constant(1), default(Expression), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentNullException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), default(Expression)));
}
[Fact]
public void TripleElementBlockUnreadable()
{
AssertExtensions.Throws<ArgumentException>("arg0", () => Expression.Block(UnreadableExpression, Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentException>("arg1", () => Expression.Block(Expression.Constant(1), UnreadableExpression, Expression.Constant(1)));
AssertExtensions.Throws<ArgumentException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), UnreadableExpression));
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void QuadrupleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Fact]
public void QuadrupleElementBlockNullArgument()
{
AssertExtensions.Throws<ArgumentNullException>("arg0", () => Expression.Block(default(Expression), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentNullException>("arg1", () => Expression.Block(Expression.Constant(1), default(Expression), Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentNullException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), default(Expression), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentNullException>("arg3", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), default(Expression)));
}
[Fact]
public void QuadrupleElementBlockUnreadable()
{
AssertExtensions.Throws<ArgumentException>("arg0", () => Expression.Block(UnreadableExpression, Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentException>("arg1", () => Expression.Block(Expression.Constant(1), UnreadableExpression, Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), UnreadableExpression, Expression.Constant(1)));
AssertExtensions.Throws<ArgumentException>("arg3", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), UnreadableExpression));
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void QuintupleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Fact]
public void QuintupleElementBlockNullArgument()
{
AssertExtensions.Throws<ArgumentNullException>("arg0", () => Expression.Block(default(Expression), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentNullException>("arg1", () => Expression.Block(Expression.Constant(1), default(Expression), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentNullException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), default(Expression), Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentNullException>("arg3", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), default(Expression), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentNullException>("arg4", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), default(Expression)));
}
[Fact]
public void QuintupleElementBlockUnreadable()
{
AssertExtensions.Throws<ArgumentException>("arg0", () => Expression.Block(UnreadableExpression, Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentException>("arg1", () => Expression.Block(Expression.Constant(1), UnreadableExpression, Expression.Constant(1), Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), UnreadableExpression, Expression.Constant(1), Expression.Constant(1)));
AssertExtensions.Throws<ArgumentException>("arg3", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), UnreadableExpression, Expression.Constant(1)));
AssertExtensions.Throws<ArgumentException>("arg4", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), UnreadableExpression));
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void SextupleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Fact]
public void NullExpicitType()
{
AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Block(default(Type), default(IEnumerable<ParameterExpression>), Expression.Constant(0)));
AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Block(default(Type), null, Enumerable.Repeat(Expression.Constant(0), 1)));
}
[Fact]
public void NullExpressionList()
{
AssertExtensions.Throws<ArgumentNullException>("expressions", () => Expression.Block(default(Expression[])));
AssertExtensions.Throws<ArgumentNullException>("expressions", () => Expression.Block(default(IEnumerable<Expression>)));
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void NullExpressionInExpressionList(int size)
{
List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList();
for (int i = 0; i != expressionList.Count; ++i)
{
Expression[] expressions = expressionList.ToArray();
expressions[i] = null;
Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(expressions));
Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(expressions.Skip(0)));
Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(typeof(int), expressions));
Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(typeof(int), expressions.Skip(0)));
Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(typeof(int), null, expressions));
Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(typeof(int), null, expressions.Skip(0)));
}
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void UnreadableExpressionInExpressionList(int size)
{
List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList();
for (int i = 0; i != expressionList.Count; ++i)
{
Expression[] expressions = expressionList.ToArray();
expressions[i] = UnreadableExpression;
Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(expressions));
Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(expressions.Skip(0)));
Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(typeof(int), expressions));
Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(typeof(int), expressions.Skip(0)));
Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(typeof(int), null, expressions));
Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(typeof(int), null, expressions.Skip(0)));
}
}
[Theory]
[PerCompilationType(nameof(ObjectAssignableConstantValuesAndSizes))]
public void BlockExplicitType(object value, int blockSize, bool useInterpreter)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
BlockExpression block = Expression.Block(typeof(object), PadBlock(blockSize - 1, constant));
Assert.Equal(typeof(object), block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void BlockInvalidExplicitType(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0));
Assert.Throws<ArgumentException>(null, () => Expression.Block(typeof(string), expressions));
Assert.Throws<ArgumentException>(null, (() => Expression.Block(typeof(string), expressions.ToArray())));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void InvalidExpressionIndex(object value, int blockSize)
{
BlockExpression block = Expression.Block(PadBlock(blockSize - 1, Expression.Constant(value, value.GetType())));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[-1]);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[blockSize]);
}
[Fact]
public void EmptyBlockWithNonVoidTypeNotAllowed()
{
Assert.Throws<ArgumentException>(null, () => Expression.Block(typeof(int)));
Assert.Throws<ArgumentException>(null, () => Expression.Block(typeof(int), Enumerable.Empty<Expression>()));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void ResultPropertyFromParams(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions.ToArray());
Assert.Same(constant, block.Result);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void ResultPropertyFromEnumerable(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
Assert.Same(constant, block.Result);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void VariableCountZeroOnNonVariableAcceptingForms(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
Assert.Empty(block.Variables);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void RewriteToSameWithSameValues(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray();
BlockExpression block = Expression.Block(expressions);
Assert.Same(block, block.Update(null, expressions));
Assert.Same(block, block.Update(Enumerable.Empty<ParameterExpression>(), expressions));
Assert.Same(block, NoOpVisitor.Instance.Visit(block));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void CanFindItems(object value, int blockSize)
{
ConstantExpression[] values = new ConstantExpression[blockSize];
for (int i = 0; i != values.Length; ++i)
values[i] = Expression.Constant(value);
BlockExpression block = Expression.Block(values);
IList<Expression> expressions = block.Expressions;
for (int i = 0; i != values.Length; ++i)
Assert.Equal(i, expressions.IndexOf(values[i]));
}
[Theory, MemberData(nameof(BlockSizes))]
public void ExpressionListBehavior(int parCount)
{
// This method contains a lot of assertions, which amount to one large assertion that
// the result of the Expressions property behaves correctly.
Expression[] exps = Enumerable.Range(0, parCount).Select(_ => Expression.Constant(0)).ToArray();
BlockExpression block = Expression.Block(exps);
ReadOnlyCollection<Expression> children = block.Expressions;
Assert.Equal(parCount, children.Count);
using (var en = children.GetEnumerator())
{
IEnumerator nonGenEn = ((IEnumerable)children).GetEnumerator();
for (int i = 0; i != parCount; ++i)
{
Assert.True(en.MoveNext());
Assert.True(nonGenEn.MoveNext());
Assert.Same(exps[i], children[i]);
Assert.Same(exps[i], en.Current);
Assert.Same(exps[i], nonGenEn.Current);
Assert.Equal(i, children.IndexOf(exps[i]));
Assert.True(children.Contains(exps[i]));
}
Assert.False(en.MoveNext());
Assert.False(nonGenEn.MoveNext());
(nonGenEn as IDisposable)?.Dispose();
}
Expression[] copyToTest = new Expression[parCount + 1];
Assert.Throws<ArgumentNullException>(() => children.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => children.CopyTo(copyToTest, -1));
Assert.All(copyToTest, Assert.Null); // assert partial copy didn't happen before exception
Assert.Throws<ArgumentException>(() => children.CopyTo(copyToTest, 2));
Assert.All(copyToTest, Assert.Null);
children.CopyTo(copyToTest, 1);
Assert.Equal(copyToTest, exps.Prepend(null));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => children[-1]);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => children[parCount]);
Assert.Equal(-1, children.IndexOf(Expression.Parameter(typeof(int))));
Assert.False(children.Contains(Expression.Parameter(typeof(int))));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void IdentifyNonAbsentItemAsAbsent(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
Assert.Equal(-1, block.Expressions.IndexOf(Expression.Default(typeof(long))));
Assert.False(block.Expressions.Contains(null));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void ExpressionsEnumerable(object value, int blockSize)
{
ConstantExpression[] values = new ConstantExpression[blockSize];
for (int i = 0; i != values.Length; ++i)
values[i] = Expression.Constant(value);
BlockExpression block = Expression.Block(values);
Assert.True(values.SequenceEqual(block.Expressions));
int index = 0;
foreach (Expression exp in ((IEnumerable)block.Expressions))
Assert.Same(exp, values[index++]);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void UpdateWithExpressionsReturnsSame(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
Assert.Same(block, block.Update(block.Variables, block.Expressions));
Assert.Same(block, NoOpVisitor.Instance.Visit(block));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void Visit(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
Assert.NotSame(block, new TestVistor().Visit(block));
}
[Theory]
[MemberData(nameof(ObjectAssignableConstantValuesAndSizes))]
public void VisitTyped(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(typeof(object), expressions);
Assert.NotSame(block, new TestVistor().Visit(block));
}
[Theory, MemberData(nameof(BlockSizes))]
public void UpdateToNullArguments(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(expressions);
AssertExtensions.Throws<ArgumentNullException>("expressions", () => block.Update(null, null));
}
[Theory, MemberData(nameof(BlockSizes))]
public void UpdateDoesntRepeatEnumeration(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray();
BlockExpression block = Expression.Block(expressions);
Assert.Same(block, block.Update(null, new RunOnceEnumerable<Expression>(expressions)));
Assert.NotSame(
block,
block.Update(null, new RunOnceEnumerable<Expression>(PadBlock(blockSize - 1, Expression.Constant(1)))));
}
[Theory, MemberData(nameof(BlockSizes))]
public void UpdateDifferentSizeReturnsDifferent(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray();
BlockExpression block = Expression.Block(expressions);
Assert.NotSame(block, block.Update(null, block.Expressions.Prepend(Expression.Empty())));
}
[Theory, MemberData(nameof(BlockSizes))]
public void UpdateAnyExpressionDifferentReturnsDifferent(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
Expression[] expressions = PadBlock(blockSize - 1, constant).ToArray();
BlockExpression block = Expression.Block(expressions);
for (int i = 0; i != expressions.Length; ++i)
{
Expression[] newExps = new Expression[expressions.Length];
expressions.CopyTo(newExps, 0);
newExps[i] = Expression.Constant(1);
Assert.NotSame(block, block.Update(null, newExps));
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Xsolla
{
public class PaymentFormController : ScreenBaseConroller<object>
{
public delegate void BackButtonHandler();
public BackButtonHandler OnClickBack;
public LinearLayout layout;
public GameObject footer;
private XsollaForm _form;
public override void InitScreen (XsollaTranslations translations, object model)
{
throw new System.NotImplementedException ();
}
public void InitView(XsollaTranslations pTranslations, XsollaForm form)
{
_form = form;
// if have skipCheckout and this checkout form
if ((form.GetCurrentCommand() == XsollaForm.CurrentCommand.CHECKOUT) && form.GetSkipChekout()){
string checkoutToken = _form.GetCheckoutToken();
bool isLinkRequired = checkoutToken != null
&& !"".Equals(checkoutToken)
&& !"null".Equals(checkoutToken)
&& !"false".Equals(checkoutToken);
if (isLinkRequired){
OnClickPay(isLinkRequired);
return;
}
}
string pattern = "{{.*?}}";
Regex regex = new Regex (pattern);
string title = regex.Replace (pTranslations.Get(XsollaTranslations.PAYMENT_PAGE_TITLE_VIA), form.GetTitle (), 1);
layout.AddObject (GetTitle (title));
layout.AddObject (GetError (form.GetError ()));
layout.AddObject (GetInfo (form.GetMessage ()));
if (form.GetVisible ().Count > 0) {
GameObject formView = GetFormView (form, pTranslations);
layout.AddObject (formView);
}
if (form.GetAccountXsolla () != null && !"".Equals (form.GetAccountXsolla ()) && !"null".Equals (form.GetAccountXsolla ()))
layout.AddObject (GetTwoTextPlate ("Xsolla number", form.GetAccountXsolla ()));
if (form.GetAccount () != null && !"".Equals (form.GetAccount ()) && !"null".Equals (form.GetAccount ()))
layout.AddObject (GetTwoTextPlate ("2pay number", form.GetAccount ()));
if (form.IsValidPaymentSystem ())
layout.AddObject (GetTextPlate (pTranslations.Get (XsollaTranslations.FORM_CC_EULA)));
GameObject footerInstance = Instantiate (footer);
Text[] footerTexts = footerInstance.GetComponentsInChildren<Text> ();
string nextStep = form.GetNextStepString ();
footerTexts [2].text = nextStep;
Button[] footerButtons = footerInstance.GetComponentsInChildren<Button> ();
if (OnClickBack != null) {
footerButtons [0].onClick.AddListener (() =>
{
OnBack ();
});
} else {
footerButtons [0].gameObject.SetActive(false);
}
if (form.GetCurrentCommand () == XsollaForm.CurrentCommand.ACCOUNT
|| form.GetCurrentCommand () == XsollaForm.CurrentCommand.CREATE
|| form.GetCurrentCommand () == XsollaForm.CurrentCommand.CHECKOUT) {//
footerTexts [1].text = "";//total
RectTransform buttonRect = footerButtons [1].GetComponent<RectTransform>();
Vector2 vecMin = buttonRect.anchorMin;
vecMin.x = vecMin.x - (buttonRect.anchorMax.x - vecMin.x)/2;
buttonRect.anchorMin = vecMin;
} else {
footerTexts [1].text = pTranslations.Get (XsollaTranslations.TOTAL) + " " + form.GetSumTotal ();//total
}
layout.AddObject (footerInstance);
layout.Invalidate ();
if (!"".Equals (nextStep) && form.GetCurrentCommand() != XsollaForm.CurrentCommand.ACCOUNT) {
string checkoutToken = _form.GetCheckoutToken();
bool isLinkRequired = checkoutToken != null
&& !"".Equals(checkoutToken)
&& !"null".Equals(checkoutToken)
&& !"false".Equals(checkoutToken);
string link = "https://secure.xsolla.com/pages/checkout/?token=" + _form.GetCheckoutToken();
if(isLinkRequired && Application.platform == RuntimePlatform.WebGLPlayer){
RectTransform buttonRect = footerButtons [1].GetComponent<RectTransform>();
int width = (int)(buttonRect.rect.xMax - buttonRect.rect.xMin);
int height = (int)(buttonRect.rect.yMax - buttonRect.rect.yMin);
height = height * 8;
Vector3[] vec = new Vector3[4];
buttonRect.GetWorldCorners(vec);
int xPos = (int)vec[0].x;
int yPos = (int)vec[0].y;
yPos = yPos/2;
CreateLinkButtonWebGl(xPos, yPos, width, height, link, "CardPaymeentForm", "Next");
footerButtons [1].onClick.AddListener (() => {
OnClickPay (false);});
} else {
footerButtons [1].onClick.AddListener (() => {
OnClickPay (isLinkRequired);});
}
} else {
footerButtons [1].gameObject.SetActive(false);
}
}
public GameObject GetFormView(XsollaForm xsollaForm, XsollaTranslations translations){
bool isCcRender = xsollaForm.GetCurrentCommand() == XsollaForm.CurrentCommand.FORM && xsollaForm.IsCreditCard();
if (isCcRender)
{
return GetCardViewWeb(xsollaForm, translations);
} else {
FormElementAdapter adapter = GetComponent<FormElementAdapter>();
adapter.SetForm (xsollaForm, translations);
GameObject list = GetList (adapter);
list.GetComponent<ListView>().DrawList(GetComponent<RectTransform> ());
return list;
}
}
private bool isMaestro;
private List<ValidatorInputField> validators;
public GameObject GetCardViewWeb(XsollaForm xsollaForm, XsollaTranslations translations)
{
GameObject cardViewObj = Instantiate (Resources.Load("Prefabs/SimpleView/_ScreenCheckout/CardViewLayoutWeb")) as GameObject;
InputField[] inputs = cardViewObj.GetComponentsInChildren<InputField>();
validators = new List<ValidatorInputField> ();
for(int i = inputs.Length - 1; i >= 0 ; i--)
{
XsollaFormElement element = null;
string newErrorMsg = "Invalid";
InputField input = inputs[i];
ValidatorInputField validator = input.GetComponentInChildren<ValidatorInputField>();
// CVV > *HOLDER* > *ZIP* > YEAR > MONTH > NUMBER
switch(i)//input.tag)
{
case 5://"CardNumber":
element = xsollaForm.GetItem(XsollaApiConst.CARD_NUMBER);
newErrorMsg = translations.Get(XsollaTranslations.VALIDATION_MESSAGE_CARDNUMBER);
CCEditText ccEditText = input.GetComponent<CCEditText>();
isMaestro = ccEditText.IsMaestro();
validator.AddValidator(new ValidatorEmpty(newErrorMsg));
validator.AddValidator(new ValidatorCreditCard(newErrorMsg));
break;
case 4://"Month":
element = xsollaForm.GetItem(XsollaApiConst.CARD_EXP_MONTH);
newErrorMsg = translations.Get(XsollaTranslations.VALIDATION_MESSAGE_CARD_MONTH);
validator.AddValidator(new ValidatorEmpty(newErrorMsg));
validator.AddValidator(new ValidatorMonth(newErrorMsg));
break;
case 3://"Year":
element = xsollaForm.GetItem(XsollaApiConst.CARD_EXP_YEAR);
newErrorMsg = translations.Get(XsollaTranslations.VALIDATION_MESSAGE_CARD_YEAR);
validator.AddValidator(new ValidatorEmpty(newErrorMsg));
validator.AddValidator(new ValidatorYear(newErrorMsg));
break;
case 2://"Zip":
element = xsollaForm.GetItem(XsollaApiConst.CARD_ZIP);
newErrorMsg = translations.Get(XsollaTranslations.VALIDATION_MESSAGE_REQUIRED);
validator.AddValidator(new ValidatorEmpty(newErrorMsg));
break;
case 1://"CardHolder":
element = xsollaForm.GetItem(XsollaApiConst.CARD_HOLDER);
newErrorMsg = translations.Get(XsollaTranslations.VALIDATION_MESSAGE_REQUIRED);
validator.AddValidator(new ValidatorEmpty(newErrorMsg));
break;
case 0://"Cvv":
element = xsollaForm.GetItem(XsollaApiConst.CARD_CVV);
newErrorMsg = translations.Get(XsollaTranslations.VALIDATION_MESSAGE_CVV);
validator.AddValidator(new ValidatorEmpty(newErrorMsg));
validator.AddValidator(new ValidatorCvv(newErrorMsg, isMaestro));
break;
default:
break;
}
if(element != null){
// input.text = element.GetTitle();
// input.GetComponentInChildren<MainValidator>().setErrorMsg(newErrorMsg);
if (element.GetName() != XsollaApiConst.CARD_CVV)
input.GetComponentInChildren<Text>().text = element.GetExample();
// FIX update with unity 5.2
input.onValueChanged.AddListener(delegate{OnValueChange(input, element.GetName());});
} else {
DestroyImmediate(input.transform.parent.gameObject);
}
if(validator != null)
validators.Add(validator);
}
// Toggle allowSubscription
// get toggle object
Toggle toggle = cardViewObj.GetComponentInChildren<Toggle> ();
if (xsollaForm.Contains(XsollaApiConst.ALLOW_SUBSCRIPTION))
{
XsollaFormElement ToggleElement = null;
ToggleElement = xsollaForm.GetItem(XsollaApiConst.ALLOW_SUBSCRIPTION);
// set label name
Text lable = toggle.transform.GetComponentInChildren<Text>();
lable.text = ToggleElement.GetTitle();
OnValueChange(ToggleElement.GetName(), toggle.isOn?"1":"0");
toggle.onValueChanged.AddListener ((b) => {
OnValueChange(ToggleElement.GetName(), b?"1":"0");
});
}
else
{
GameObject.Find(toggle.transform.parent.name).SetActive(false);
}
if (xsollaForm.Contains("couponCode") && xsollaForm.GetItem("couponCode").IsVisible())
{
GameObject promoController = Instantiate(Resources.Load("Prefabs/SimpleView/_PaymentFormElements/ContainerPromoCode")) as GameObject;
PromoCodeController controller = promoController.GetComponent<PromoCodeController>();
//controller.InitScreen(translations, xsollaForm.GetItem("couponCode"));
controller._inputField.onValueChanged.AddListener((s) => {
OnValueChange("couponCode", s.Trim());
});
controller._promoCodeApply.onClick.AddListener(() =>
{
bool isLinkRequired = false;
if ((_form.GetCurrentCommand() == XsollaForm.CurrentCommand.CHECKOUT) && _form.GetSkipChekout()){
string checkoutToken = _form.GetCheckoutToken();
isLinkRequired = checkoutToken != null
&& !"".Equals(checkoutToken)
&& !"null".Equals(checkoutToken)
&& !"false".Equals(checkoutToken);
}
if(isLinkRequired){
string link = "https://secure.xsolla.com/pages/checkout/?token=" + _form.GetCheckoutToken();
if (Application.platform == RuntimePlatform.WebGLPlayer
//|| Application.platform == RuntimePlatform.OSXWebPlayer
//|| Application.platform == RuntimePlatform.WindowsWebPlayer
) {
Application.ExternalEval("window.open('" + link + "','Window title')");
} else {
Application.OpenURL(link);
}
}
gameObject.GetComponentInParent<XsollaPaystationController> ().ApplyPromoCoupone (_form.GetXpsMap ());
});
promoController.transform.SetParent(cardViewObj.transform);
}
return cardViewObj;
}
private void OnValueChange(InputField _input, string elemName)
{
_form.UpdateElement(elemName, _input.text);
}
private void OnValueChange(string elemName, string pValue)
{
_form.UpdateElement(elemName, pValue);
}
//TODO make new window non blocking
private void OnClickPay(bool isLinkRequired)
{
Logger.Log ("OnClickPay");
bool isValid = true;
if (validators != null) {
foreach (var v in validators) {
if(isValid)
isValid = v.IsValid ();
}
}
if(isValid) {
if(isLinkRequired){
string link = "https://secure.xsolla.com/pages/checkout/?token=" + _form.GetCheckoutToken();
if (Application.platform == RuntimePlatform.WebGLPlayer
//|| Application.platform == RuntimePlatform.OSXWebPlayer
//|| Application.platform == RuntimePlatform.WindowsWebPlayer
) {
Application.ExternalEval("window.open('" + link + "','Window title')");
} else {
Application.OpenURL(link);
}
}
gameObject.GetComponentInParent<XsollaPaystationController> ().DoPayment (_form.GetXpsMap ());
}
}
private void Next(){
Logger.Log ("OnClickNext");
if(Application.platform == RuntimePlatform.WebGLPlayer )
RemoveLinkButtonWebGL();
gameObject.GetComponentInParent<XsollaPaystationController> ().DoPayment (_form.GetXpsMap ());
}
private bool isDivCreated = false;
public void CreateLinkButtonWebGl(int xPos, int yPos, int width, int heigth, string link, string objName, string functionToCall){
string js = String.Format(@"var div = document.createElement('a');
div.id = 'customLinkButton';
div.style.zIndex = '9999';
div.style.position = 'absolute';
div.style.left = '{0}px';
div.style.bottom = '{1}px';
div.style.width = '{2}px';
div.style.height = '{3}px';
div.href = '{4}';
div.target = '_blank';
div.onclick = function() {{ SendMessage('{5}','{6}');}};
document.getElementById('canvas').parentNode.appendChild(div);",
Math.Abs(xPos), Math.Abs(yPos), Math.Abs(width), Math.Abs(heigth), link, objName, functionToCall);
Application.ExternalEval(js);
isDivCreated = true;
}
public void RemoveLinkButtonWebGL(){
if (Application.platform == RuntimePlatform.WebGLPlayer && isDivCreated) {
string js = @"var elem = document.getElementById('customLinkButton');
elem.parentNode.removeChild(elem);";
Application.ExternalEval (js);
isDivCreated = false;
}
}
private const string PrefabInfo = "Prefabs/SimpleView/_ScreenCheckout/InfoPlate";
private GameObject GetInfo(XsollaMessage infoText){
bool isError = infoText != null;
if (isError) {
GameObject infoObj = GetObject (PrefabInfo);
SetText (infoObj, infoText.message);
return infoObj;
}
return null;
}
void OnDestroy() {
RemoveLinkButtonWebGL ();
}
private void OnBack()
{
if(OnClickBack != null)
OnClickBack();
}
}
}
| |
namespace SportPredictionsSystem.Data.Migrations
{
using System.Data.Entity.Migrations;
using System.Linq;
using SportPredictionsSystem.Data.Models;
public class Configuration : DbMigrationsConfiguration<SportPredictionsSystemDbContext>
{
public Configuration()
{
this.AutomaticMigrationsEnabled = true;
this.AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(SportPredictionsSystemDbContext context)
{
this.SeedCountries(context);
}
private void SeedCountries(SportPredictionsSystemDbContext context)
{
if (!context.Countries.Any())
{
var countryNames = new[]
{
"Afghanistan",
"Albania",
"Algeria",
"American Samoa",
"Andorra",
"Angola",
"Anguilla",
"Antarctica",
"Antigua and Barbuda",
"Argentina",
"Armenia",
"Aruba",
"Australia",
"Austria",
"Azerbaijan",
"Bahamas",
"Bahrain",
"Bangladesh",
"Barbados",
"Belarus",
"Belgium",
"Belize",
"Benin",
"Bermuda",
"Bhutan",
"Bolivia",
"Bosnia and Herzegovina",
"Botswana",
"Brazil",
"Brunei Darussalam",
"Bulgaria",
"Burkina Faso",
"Burundi",
"Cambodia",
"Cameroon",
"Canada",
"Cape Verde",
"Cayman Islands",
"Central African Republic",
"Chad",
"Chile",
"China",
"Christmas Island",
"Cocos (Keeling) Islands",
"Colombia",
"Comoros",
"Democratic Republic of the Congo (Kinshasa)",
"Congo, Republic of (Brazzaville)",
"Cook Islands",
"Costa Rica",
"Ivory Coast",
"Croatia",
"Cuba",
"Cyprus",
"Czech Republic",
"Denmark",
"Djibouti",
"Dominica",
"Dominican Republic",
"East Timor (Timor-Leste)",
"Ecuador",
"Egypt",
"El Salvador",
"Equatorial Guinea",
"Eritrea",
"Estonia",
"Ethiopia",
"Falkland Islands",
"Faroe Islands",
"Fiji",
"Finland",
"France",
"French Guiana",
"French Polynesia",
"French Southern Territories",
"Gabon",
"Gambia",
"Georgia",
"Germany",
"Ghana",
"Gibraltar",
"Great Britain",
"Greece",
"Greenland",
"Grenada",
"Guadeloupe",
"Guam",
"Guatemala",
"Guinea",
"Guinea-Bissau",
"Guyana",
"Haiti",
"Holy See",
"Honduras",
"Hong Kong",
"Hungary",
"Iceland",
"India",
"Indonesia",
"Iran (Islamic Republic of)",
"Iraq",
"Ireland",
"Israel",
"Italy",
"Jamaica",
"Japan",
"Jordan",
"Kazakhstan",
"Kenya",
"Kiribati",
"Korea, Democratic People's Rep. (North Korea)",
"Korea, Republic of (South Korea)",
"Kosovo",
"Kuwait",
"Kyrgyzstan",
"Lao, People's Democratic Republic",
"Latvia",
"Lebanon",
"Lesotho",
"Liberia",
"Libya",
"Liechtenstein",
"Lithuania",
"Luxembourg",
"Macau",
"Macedonia, Rep. of",
"Madagascar",
"Malawi",
"Malaysia",
"Maldives",
"Mali",
"Malta",
"Marshall Islands",
"Martinique",
"Mauritania",
"Mauritius",
"Mayotte",
"Mexico",
"Micronesia, Federal States of",
"Moldova, Republic of",
"Monaco",
"Mongolia",
"Montenegro",
"Montserrat",
"Morocco",
"Mozambique",
"Myanmar, Burma",
"Namibia",
"Nauru",
"Nepal",
"Netherlands",
"Netherlands Antilles",
"New Caledonia",
"New Zealand",
"Nicaragua",
"Niger",
"Nigeria",
"Niue",
"Northern Mariana Islands",
"Norway",
"Oman",
"Pakistan",
"Palau",
"Palestinian territories",
"Panama",
"Papua New Guinea",
"Paraguay",
"Peru",
"Philippines",
"Pitcairn Island",
"Poland",
"Portugal",
"Puerto Rico",
"Qatar",
"Reunion Island",
"Romania",
"Russian Federation",
"Rwanda",
"Saint Kitts and Nevis",
"Saint Lucia",
"Saint Vincent and the Grenadines",
"Samoa",
"San Marino",
"Sao Tome and Principe",
"Saudi Arabia",
"Senegal",
"Serbia",
"Seychelles",
"Sierra Leone",
"Singapore",
"Slovakia (Slovak Republic)",
"Slovenia",
"Solomon Islands",
"Somalia",
"South Africa",
"South Sudan",
"Spain",
"Sri Lanka",
"Sudan",
"Suriname",
"Swaziland",
"Sweden",
"Switzerland",
"Syria, Syrian Arab Republic",
"Taiwan (Republic of China)",
"Tajikistan",
"Tanzania; officially the United Republic of Tanzania",
"Thailand",
"Tibet",
"Timor-Leste (East Timor)",
"Togo",
"Tokelau",
"Tonga",
"Trinidad and Tobago",
"Tunisia",
"Turkey",
"Turkmenistan",
"Turks and Caicos Islands",
"Tuvalu",
"Uganda",
"Ukraine",
"United Arab Emirates",
"United Kingdom",
"United States",
"Uruguay",
"Uzbekistan",
"Vanuatu",
"Vatican City State (Holy See)",
"Venezuela",
"Vietnam",
"Virgin Islands (British)",
"Virgin Islands (U.S.)",
"Wallis and Futuna Islands",
"Western Sahara",
"Yemen",
"Zambia",
"Zimbabwe"
};
foreach (var countryName in countryNames)
{
context.Countries.Add(new Country { NameEn = countryName });
}
context.SaveChanges();
}
}
}
}
| |
using System;
using NBM.Plugin;
using WinForms = System.Windows.Forms;
// 8/5/03
namespace NBM
{
/// <summary>
/// Context menu for the protocols
/// </summary>
public class ProtocolMenu : WinForms.ContextMenu, IProtocolListener
{
private MainForm mainForm;
private Protocol protocol;
private StatusMenu statusMenu;
private WinForms.MenuItem addFriendItem, debugReportItem, optionsItem, connectItem, disconnectItem;
/// <summary>
/// Constructs a ProtocolMenu
/// </summary>
/// <param name="mainForm"></param>
/// <param name="protocol"></param>
public ProtocolMenu(MainForm mainForm, Protocol protocol)
{
this.mainForm = mainForm;
this.protocol = protocol;
this.protocol.AddListener(this);
// add connect and disconnect menu items
this.statusMenu = new StatusMenu("Status", new EventHandler(OnStatusClick));
foreach (StatusMenuItem item in this.statusMenu.MenuItems)
{
item.RadioCheck = true;
item.Checked = item.Status == this.protocol.Settings.Status;
}
this.MenuItems.Add(statusMenu);
this.MenuItems.Add("-");
this.connectItem = new WinForms.MenuItem("Connect", new EventHandler(connectMenuItem_Click));
this.MenuItems.Add(this.connectItem);
this.disconnectItem = new WinForms.MenuItem("Disconnect", new EventHandler(disconnectMenuItem_Click));
this.disconnectItem.Enabled = false;
this.MenuItems.Add(this.disconnectItem);
this.MenuItems.Add("-");
this.optionsItem = new WinForms.MenuItem("Options", new EventHandler(optionsMenuItem_Click));
this.MenuItems.Add(this.optionsItem);
this.MenuItems.Add("-");
this.addFriendItem = new WinForms.MenuItem("Add friend", new EventHandler(addfriendMenuItem_Click));
this.addFriendItem.Enabled = false;
this.MenuItems.Add(this.addFriendItem);
this.MenuItems.Add("-");
this.debugReportItem = new WinForms.MenuItem("Debug Report", new EventHandler(debugReportMenuItem_Click));
this.MenuItems.Add(this.debugReportItem);
this.Disposed += new EventHandler(OnDispose);
// this.MenuItems.Add("Self Destruct", new EventHandler(selfdestruct_click));
}
private void OnStatusClick(object sender, EventArgs e)
{
this.protocol.ChangeStatus(((StatusMenuItem)sender).Status, new OperationCompleteEvent());
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnDispose(object sender, EventArgs e)
{
if (this.protocol != null)
this.protocol.RemoveListener(this);
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void connectMenuItem_Click(object sender, System.EventArgs e)
{
protocol.Connect(new OperationCompleteEvent());
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void disconnectMenuItem_Click(object sender, System.EventArgs e)
{
protocol.Disconnect(new OperationCompleteEvent());
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void addfriendMenuItem_Click(object sender, System.EventArgs e)
{
if (this.protocol.Connected)
{
// show add friend dialog
AddFriendForm form = new AddFriendForm(this.protocol);
if (form.ShowDialog() == WinForms.DialogResult.OK)
{
this.protocol.AddFriendToList(form.Username, form.Message, new OperationCompleteEvent());
}
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void debugReportMenuItem_Click(object sender, System.EventArgs e)
{
this.protocol.Reporter.Show();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void optionsMenuItem_Click(object sender, System.EventArgs e)
{
OptionsForm form = new OptionsForm(this.mainForm, this.protocol);
form.Show();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void selfdestruct_click(object sender, EventArgs e)
{
this.protocol.SelfDestruct();
}
#region ProtocolListener methods
/// <summary>
///
/// </summary>
/// <param name="friend"></param>
public void OnFriendAdd(Friend friend)
{
}
/// <summary>
///
/// </summary>
/// <param name="friend"></param>
public void OnFriendRemove(Friend friend)
{
}
/// <summary>
///
/// </summary>
/// <param name="friend"></param>
/// <param name="status"></param>
public void OnFriendChangeStatus(Friend friend, OnlineStatus status)
{
}
/// <summary>
///
/// </summary>
/// <param name="friend"></param>
/// <param name="newName"></param>
public void OnFriendChangeDisplayName(Friend friend, string newName)
{
}
/// <summary>
///
/// </summary>
public void OnBeginConnect()
{
}
/// <summary>
///
/// </summary>
public void OnConnect()
{
this.addFriendItem.Enabled = true;
this.connectItem.Enabled = false;
this.disconnectItem.Enabled = true;
}
/// <summary>
/// Called when the connection is canceled
/// </summary>
public void OnConnectCanceled()
{
this.addFriendItem.Enabled = false;
this.disconnectItem.Enabled = false;
this.connectItem.Enabled = true;
}
/// <summary>
///
/// </summary>
/// <param name="forced"></param>
public void OnDisconnect(bool forced)
{
this.addFriendItem.Enabled = false;
this.disconnectItem.Enabled = false;
this.connectItem.Enabled = true;
}
/// <summary>
///
/// </summary>
/// <param name="status"></param>
public void OnChangeStatus(OnlineStatus status)
{
foreach (StatusMenuItem item in this.statusMenu.MenuItems)
{
item.Checked = item.Status == status;
}
}
/// <summary>
///
/// </summary>
/// <param name="friend"></param>
/// <param name="opCompleteEvent"></param>
/// <param name="tag"></param>
public void OnInvitedToConversation(Friend friend, OperationCompleteEvent opCompleteEvent, object tag)
{
}
/// <summary>
///
/// </summary>
/// <param name="username"></param>
public void OnAddFriendToList(string username)
{
}
/// <summary>
///
/// </summary>
/// <param name="friend"></param>
public void OnRemoveFriendFromList(Friend friend)
{
}
/// <summary>
///
/// </summary>
/// <param name="friend"></param>
public void OnBlockFriend(Friend friend)
{
}
/// <summary>
///
/// </summary>
/// <param name="friend"></param>
public void OnUnblockFriend(Friend friend)
{
}
/// <summary>
///
/// </summary>
/// <param name="text"></param>
public void OnWriteDebug(string text)
{
}
/// <summary>
///
/// </summary>
/// <param name="friend"></param>
/// <param name="reason"></param>
/// <param name="enableAddCheckbox"></param>
public void OnPromptForStrangerHasAddedMe(Friend friend, string reason, bool enableAddCheckbox)
{
}
#endregion
}
}
| |
using System;
using System.Windows;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TypeVisualiser;
using TypeVisualiser.Geometry;
namespace TypeVisualiserUnitTests.Geometry
{
/// <summary>
/// Summary description for UnitTest1
/// </summary>
[TestClass]
public class AreaTest
{
[TestMethod]
public void CanConstructUsing2Points()
{
double topX = 12.43, topY = 56.89;
double bottomX = 45.89, bottomY = 45.87;
var topPoint = new Point(topX, topY);
var bottomPoint = new Point(bottomX, bottomY);
var subject = new Area(topPoint, bottomPoint);
// Ensure it doesnt change after creation, ie cloned.
topPoint.Offset(1, 1);
bottomPoint.Offset(2, 2);
Assert.AreEqual(topX, subject.TopLeft.X);
Assert.AreEqual(topY, subject.TopLeft.Y);
Assert.AreEqual(bottomX, subject.BottomRight.X);
Assert.AreEqual(bottomY, subject.BottomRight.Y);
}
[TestMethod]
public void CentreShouldBeAsExpected()
{
var subject = new Area(new Point(1, 1), new Point(3, 3));
Point result = subject.Centre;
Assert.AreEqual(2, result.X);
Assert.AreEqual(2, result.Y);
}
[TestMethod]
public void DistanceToPointShouldBeAsExpected()
{
var subject = new Area(new Point(1, 1), new Point(3, 3));
double result = subject.DistanceToPoint(new Point(10, 10));
Assert.AreEqual(12.72792, result, 0.00001);
}
[TestMethod]
public void HeightShouldBeAsExpected()
{
var subject = new Area(new Point(1, 1), new Point(3, 3));
double result = subject.Height;
Assert.AreEqual(2, result);
}
[TestMethod]
public void IfThisIsNaNShouldNotThrowOverlap()
{
var area1 = new Area(new Point(10, 10), new Point(20, 20));
var area2 = new Area(new Point(double.NaN, 20), new Point(25, 25));
ProximityTestResult result = area2.OverlapsWith(area1);
Assert.AreEqual(Proximity.NotOverlapping, result.Proximity);
}
[TestMethod]
[ExpectedException(typeof (ArgumentException))]
public void NaNShouldThrowOverlap()
{
var area1 = new Area(new Point(double.NaN, 10), new Point(20, 20));
var area2 = new Area(new Point(11, 20), new Point(25, 25));
area2.OverlapsWith(area1);
}
[TestMethod]
[ExpectedException(typeof (ArgumentNullResourceException))]
public void NullShouldThrowOverlap()
{
Area area1 = null;
var area2 = new Area(new Point(11, 20), new Point(25, 25));
area2.OverlapsWith(area1);
Assert.Fail();
}
[TestMethod]
public void OffSetShouldMoveAsExpected()
{
var subject = new Area(new Point(12.34, 45.56), new Point(67.67, 89.90));
Area result = subject.Offset(1, 1);
Assert.AreEqual(13.34, result.TopLeft.X);
Assert.AreEqual(46.56, result.TopLeft.Y);
Assert.AreEqual(68.67, result.BottomRight.X);
Assert.AreEqual(90.90, result.BottomRight.Y);
}
[TestMethod]
public void OffSetShouldNotReassignReference()
{
var subject = new Area(new Point(12.34, 45.56), new Point(67.67, 89.90));
Area result = subject.Offset(1, 1);
// Ensure it doesnt change after creation, ie cloned.
subject.Offset(1, 1);
Assert.AreNotEqual(result.TopLeft, subject.TopLeft);
Assert.AreNotEqual(result.BottomRight, subject.BottomRight);
}
[TestMethod]
public void OffsetToCentreMustMoveToCentre()
{
var subject = new Area(new Point(12.34, 45.56), new Point(67.67, 89.90));
Area result = subject.OffsetToMakeTopLeftCentre();
Assert.AreEqual(result.Centre, subject.TopLeft);
}
[TestMethod]
public void OffsetToCentreMustNotReassignReference()
{
var subject = new Area(new Point(12.34, 45.56), new Point(67.67, 89.90));
Area result = subject.OffsetToMakeTopLeftCentre();
Assert.AreNotEqual(subject.TopLeft, result.TopLeft);
}
[TestMethod]
public void ShouldBeVeryCloseAndBeDown()
{
var area1 = new Area(new Point(20, 0), new Point(25, 5));
var area2 = new Area(new Point(20, 20), new Point(25, 25));
ProximityTestResult result = area1.OverlapsWith(area2);
Assert.AreEqual(Direction.Down, result.DirectionToOtherObject);
Assert.AreEqual(Proximity.VeryClose, result.Proximity);
}
[TestMethod]
public void ShouldBeVeryCloseAndBeToTheLeft()
{
var area1 = new Area(new Point(10, 20), new Point(15, 25));
var area2 = new Area(new Point(20, 20), new Point(25, 25));
ProximityTestResult result = area2.OverlapsWith(area1);
Assert.AreEqual(Direction.Left, result.DirectionToOtherObject);
Assert.AreEqual(Proximity.VeryClose, result.Proximity);
}
[TestMethod]
public void ShouldBeVeryCloseAndBeToTheRight()
{
var area1 = new Area(new Point(10, 20), new Point(15, 25));
var area2 = new Area(new Point(20, 20), new Point(25, 25));
ProximityTestResult result = area1.OverlapsWith(area2);
Assert.AreEqual(Direction.Right, result.DirectionToOtherObject);
Assert.AreEqual(Proximity.VeryClose, result.Proximity);
}
[TestMethod]
public void ShouldBeVeryCloseAndBeUp()
{
var area1 = new Area(new Point(0, 0), new Point(5, 5));
var area2 = new Area(new Point(0, 10), new Point(5, 15));
ProximityTestResult result = area2.OverlapsWith(area1);
Assert.AreEqual(Direction.Up, result.DirectionToOtherObject);
Assert.AreEqual(Proximity.VeryClose, result.Proximity);
}
[TestMethod]
public void ShouldBeVeryCloseNotTouching()
{
var area1 = new Area(new Point(10, 10), new Point(20, 20));
var area2 = new Area(new Point(11, 21), new Point(25, 25));
Assert.AreEqual(Proximity.VeryClose, area2.OverlapsWith(area1).Proximity);
}
[TestMethod]
public void ShouldBeVeryCloseTouching()
{
var area1 = new Area(new Point(10, 10), new Point(20, 20));
var area2 = new Area(new Point(10, 20), new Point(25, 25));
Assert.AreEqual(Proximity.VeryClose, area2.OverlapsWith(area1).Proximity);
}
[TestMethod]
public void ShouldNotOverlapAndBeDown()
{
var area1 = new Area(new Point(20, 0), new Point(25, 5));
var area2 = new Area(new Point(20, 45.1), new Point(25, 65.1));
ProximityTestResult result = area1.OverlapsWith(area2);
result.Proximity.Should().Be(Proximity.VeryClose);
}
[TestMethod]
public void ShouldNotOverlapAndBeToTheLeft()
{
var area1 = new Area(new Point(10, 20), new Point(15, 25));
var area2 = new Area(new Point(55, 20), new Point(60, 25));
ProximityTestResult result = area2.OverlapsWith(area1);
result.Proximity.Should().Be(Proximity.VeryClose);
}
[TestMethod]
public void ShouldNotOverlapAndBeToTheRight()
{
var area1 = new Area(new Point(10, 20), new Point(15, 25));
var area2 = new Area(new Point(55, 20), new Point(60, 25));
ProximityTestResult result = area1.OverlapsWith(area2);
result.Proximity.Should().Be(Proximity.VeryClose);
}
[TestMethod]
public void ShouldNotOverlapAndBeUp()
{
var area1 = new Area(new Point(20, 0), new Point(25, 5));
var area2 = new Area(new Point(20, 45.1), new Point(25, 65.1));
ProximityTestResult result = area2.OverlapsWith(area1);
result.Proximity.Should().Be(Proximity.VeryClose);
}
[TestMethod]
public void ShouldOverlap()
{
var area1 = new Area(new Point(10, 10), new Point(20, 20));
var area2 = new Area(new Point(15, 15), new Point(25, 25));
Assert.AreEqual(Proximity.Overlapping, area2.OverlapsWith(area1).Proximity);
}
[TestMethod]
public void WidthShouldBeAsExpected()
{
var subject = new Area(new Point(1, 1), new Point(3, 3));
double result = subject.Height;
Assert.AreEqual(2, result);
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Linq;
using System.Collections.Generic;
using ProBuilder2.Common;
/**
* Responsible for spawning and removing pipes. Also controls
* pipe running variables, like speed, size, and length.
*/
public class PipeSpawner : MonoBehaviour
{
public int desiredActivePipeCount = 1; ///< How many pipes to keep active at once.
public float pipeSize = 1f; ///< The size each pipe will be instantiated with.
public float pipeSpeed = 13f; ///< The speed with which pipes will propogate themselves.
public int maxPipesOnScreen = 7; ///< How many pipes to allow on screen at once.
public int minPipeTurns = 100; ///< The minimum number of turns a pipe must make before completing itself.
public int maxPipeTurns = 200; ///< The maximum number of turns a pipe may make before completing itself.
public Material material; ///< The material to used for pipes.
public Material fadeMaterial; ///< The material to used for pipes.
public float fadeTime = 2f; ///< How many seconds it takes to fade a pipe into oblivion.
public Texture2D pausedImage; ///< Shown when composition is paused.
public Bounds bounds = new Bounds(Vector3.zero, Vector3.one * 10f); ///< The bounds to stay inside when pipes are running.
[SerializeField] int activePipes = 0;
[SerializeField] List<Pipe> finishedPipes = new List<Pipe>(); ///< Pipes that have been built out and run out of moves are saved so that we can reset the screen.
RotateCamera rotateCam;
#region Initialization
void Awake()
{
rotateCam = Camera.main.transform.GetComponent<RotateCamera>();
}
void Start()
{
StartCoroutine( SpawnPipes() );
}
/**
* Begin by Spawning pipes at intervals so that you can see it happening.
*/
IEnumerator SpawnPipes()
{
while(activePipes < desiredActivePipeCount && !paused)
{
SpawnPipe();
yield return new WaitForSeconds( Random.Range(.5f, 1f));
}
}
#endregion
#region Set / Get
public bool IsPaused()
{
return paused;
}
void SetSpeed(float speed)
{
foreach(Pipe pipe in FindObjectsOfType(typeof(Pipe)))
pipe.SetSpeed(speed);
}
#endregion
#region Update Loop / GUI
// GUI Settings vars
bool showSettings = false;
public Rect SettingsWindowRect { get { return settingsWindowRect; } }
Rect settingsWindowRect = new Rect(10, 20, 200, 200);
void OnGUI()
{
showSettings = GUILayout.Toggle(showSettings, "Settings");
if(showSettings)
{
settingsWindowRect = GUILayout.Window(0, settingsWindowRect, SettingsWindow, "Settings");
settingsWindowRect.x = Mathf.Clamp(settingsWindowRect.x, 0, Screen.width-settingsWindowRect.width);
settingsWindowRect.y = Mathf.Clamp(settingsWindowRect.y, 0, Screen.height-20);
}
if(paused)
{
if(pausedImage != null)
{
if(GUI.Button(new Rect(Screen.width/2f-pausedImage.width/2f, Screen.height-pausedImage.height-20, pausedImage.width, pausedImage.height), pausedImage, GUIStyle.none))
TogglePause();
}
else
GUI.Label(new Rect(Screen.width/2f-60, Screen.height-40, 120, 24), "PAUSED");
}
}
bool paused = false;
void Update()
{
if(Input.GetKeyUp(KeyCode.Space))
{
TogglePause();
}
}
public void TogglePause()
{
paused = !paused;
if(!paused && activePipes < desiredActivePipeCount)
{
SetSpeed(pipeSpeed);
StartCoroutine(SpawnPipes());
}
SetSpeed(paused ? 0f : pipeSpeed);
}
void SettingsWindow(int id)
{
int tmp = 0;
bool doUpdate = false;
GUILayout.Label("\"Escape\" key to Quit\n\"Space\" key to Pause");
GUILayout.Label("Active Pipes: " + desiredActivePipeCount);
{
tmp = desiredActivePipeCount;
desiredActivePipeCount = (int)GUILayout.HorizontalSlider(desiredActivePipeCount, 1, 8);
if(desiredActivePipeCount != tmp)
{
if(activePipes > desiredActivePipeCount)
{
int end = activePipes - desiredActivePipeCount, i = 0;
foreach(Pipe p in FindObjectsOfType(typeof(Pipe)))
{
if(!p.IsPaused())
{
p.EndPipe();
if(++i > end)
break;
}
}
}
else
{
if(!paused)
doUpdate = true;
}
}
}
GUILayout.Label("Max Pipes on Screen: " + maxPipesOnScreen);
{
tmp = maxPipesOnScreen;
maxPipesOnScreen = (int)GUILayout.HorizontalSlider(maxPipesOnScreen, desiredActivePipeCount, 12);
if(tmp != maxPipesOnScreen)
doUpdate = true;
}
GUILayout.Label("Speed: " + pipeSpeed);
{
tmp = (int)pipeSpeed;
pipeSpeed = GUILayout.HorizontalSlider(pipeSpeed, 1f, 40f);
if( (int)pipeSpeed != tmp && !paused )
SetSpeed(pipeSpeed);
}
GUILayout.Space(6);
GUILayout.Label("Camera Orbit Speed: " + rotateCam.idleSpeed.ToString("F2"));
{
rotateCam.idleSpeed = GUILayout.HorizontalSlider(rotateCam.idleSpeed, .01f, 10f);
}
if( GUILayout.Button("Reset") )
{
activePipes = 0;
finishedPipes.Clear();
foreach(Pipe pipe in FindObjectsOfType(typeof(Pipe)))
GameObject.Destroy(pipe.gameObject);
StartCoroutine( SpawnPipes() );
}
if(doUpdate)
{
ClearPipes();
if( activePipes < desiredActivePipeCount )
StartCoroutine( SpawnPipes() );
}
GUI.DragWindow(new Rect(0,0,10000,20));
}
#endregion
#region Pipe Management
/**
* The delegate that Pipe's event handler will call when out of moves.
*/
public void OnPipeFinished(Pipe pipe)
{
pipe.OnPipeFinished -= this.OnPipeFinished;
activePipes--;
finishedPipes.Add(pipe);
// Check if we need to clear any old pipes from the screen to meet the maxPipesOnScreen limit.
ClearPipes();
// And finally spawn a new pipe to replace the finished one.
if(activePipes < desiredActivePipeCount)
StartCoroutine( SpawnPipes() );
}
/**
* Create a new Pipe and add it to the activePipes list.
*/
void SpawnPipe()
{
// pb_Shape_Generator provides API access to all ProBuilder primitives. All *Generator methods
// return a reference to the pb_Object created, so you'll need to get the gameObject yourself.
pb_Object pb = pb_Shape_Generator.CubeGenerator(Vector3.one * pipeSize);
// Get the gameObject.
GameObject pipeGameObject = pb.gameObject;
// Move the new gameObject to a random position inside the bounds.
pipeGameObject.transform.position = GetStartPosition();
// Set the entire object's material. You can also set just a subset of faces this way.
pb.SetFaceMaterial(pb.faces, material);
// Set the AutoUV generation parameter for useWorldSpace - this keeps UVs looking
// uniform. You can also set your own UVs using the pb.SetUVs(Vector2[] uv) calls.
foreach(pb_Face face in pb.faces)
face.uv.useWorldSpace = true;
// Add the Pipe component. This is the script responsible for moving the pipe around
// and doing most of the interesting stuff.
Pipe pipe = pipeGameObject.AddComponent<Pipe>();
// Set the size of the pipe.
pipe.SetSize(pipeSize);
// and the speed to build itself out.
pipe.SetSpeed(pipeSpeed);
// aaand the bounds.
pipe.SetBounds(bounds);
// and finally the amount of turns before it finishes itself.
pipe.SetMaxTurns( (int) Random.Range(minPipeTurns, maxPipeTurns) );
// pipe.spawner = this;
// Register for a callback when the pipe completes it's tasks.
// We'll use this to keep track of what pipes are completed and
// remove them when necessary.
pipe.OnPipeFinished += OnPipeFinished;
// Add this pipe to the activePipes count/
activePipes++;
}
/**
* Will remove completed pipes until the total on screen pipe count is less than maxPipesOnScreen.
*/
void ClearPipes()
{
int totalPipeCount = activePipes + finishedPipes.Count;
while( totalPipeCount > maxPipesOnScreen && finishedPipes.Count > 0 )
{
finishedPipes[0].GetComponent<Pipe>().FadeOut(fadeTime, 0f, fadeMaterial);
finishedPipes.RemoveAt(0);
totalPipeCount--;
}
}
#endregion
#region Utility / Gizmos
/**
* Returns a random Vector3 within the bounds.
* @todo - This should try to put new pipes in less populated quadants.
*/
Vector3 GetStartPosition()
{
return new Vector3(
Random.Range(bounds.center.x - bounds.extents.x, bounds.center.x + bounds.extents.x),
Random.Range(bounds.center.y - bounds.extents.y, bounds.center.y + bounds.extents.y),
Random.Range(bounds.center.z - bounds.extents.z, bounds.center.z + bounds.extents.z) );
}
/**
* Show the active bounds with neat lookin' gizmos.
*/
void OnDrawGizmos()
{
// // Draw Wireframe
Vector3 cen = bounds.center;
Vector3 ext = bounds.extents;
DrawBoundsEdge(cen, -ext.x, -ext.y, -ext.z, 1f);
DrawBoundsEdge(cen, -ext.x, -ext.y, ext.z, 1f);
DrawBoundsEdge(cen, ext.x, -ext.y, -ext.z, 1f);
DrawBoundsEdge(cen, ext.x, -ext.y, ext.z, 1f);
DrawBoundsEdge(cen, -ext.x, ext.y, -ext.z, 1f);
DrawBoundsEdge(cen, -ext.x, ext.y, ext.z, 1f);
DrawBoundsEdge(cen, ext.x, ext.y, -ext.z, 1f);
DrawBoundsEdge(cen, ext.x, ext.y, ext.z, 1f);
}
private void DrawBoundsEdge(Vector3 center, float x, float y, float z, float size)
{
Vector3 p = center;
p.x += x;
p.y += y;
p.z += z;
Gizmos.DrawLine(p, p + ( -(x/Mathf.Abs(x)) * Vector3.right * Mathf.Min(size, Mathf.Abs(x))));
Gizmos.DrawLine(p, p + ( -(y/Mathf.Abs(y)) * Vector3.up * Mathf.Min(size, Mathf.Abs(y))));
Gizmos.DrawLine(p, p + ( -(z/Mathf.Abs(z)) * Vector3.forward * Mathf.Min(size, Mathf.Abs(z))));
}
#endregion
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnArbol class.
/// </summary>
[Serializable]
public partial class PnArbolCollection : ActiveList<PnArbol, PnArbolCollection>
{
public PnArbolCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnArbolCollection</returns>
public PnArbolCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnArbol o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_arbol table.
/// </summary>
[Serializable]
public partial class PnArbol : ActiveRecord<PnArbol>, IActiveRecord
{
#region .ctors and Default Settings
public PnArbol()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnArbol(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnArbol(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnArbol(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_arbol", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdNodo = new TableSchema.TableColumn(schema);
colvarIdNodo.ColumnName = "id_nodo";
colvarIdNodo.DataType = DbType.Int32;
colvarIdNodo.MaxLength = 0;
colvarIdNodo.AutoIncrement = true;
colvarIdNodo.IsNullable = false;
colvarIdNodo.IsPrimaryKey = true;
colvarIdNodo.IsForeignKey = false;
colvarIdNodo.IsReadOnly = false;
colvarIdNodo.DefaultSetting = @"";
colvarIdNodo.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdNodo);
TableSchema.TableColumn colvarIdPermisoPadre = new TableSchema.TableColumn(schema);
colvarIdPermisoPadre.ColumnName = "id_permiso_padre";
colvarIdPermisoPadre.DataType = DbType.Int32;
colvarIdPermisoPadre.MaxLength = 0;
colvarIdPermisoPadre.AutoIncrement = false;
colvarIdPermisoPadre.IsNullable = true;
colvarIdPermisoPadre.IsPrimaryKey = false;
colvarIdPermisoPadre.IsForeignKey = false;
colvarIdPermisoPadre.IsReadOnly = false;
colvarIdPermisoPadre.DefaultSetting = @"";
colvarIdPermisoPadre.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdPermisoPadre);
TableSchema.TableColumn colvarIdPermisoHijo = new TableSchema.TableColumn(schema);
colvarIdPermisoHijo.ColumnName = "id_permiso_hijo";
colvarIdPermisoHijo.DataType = DbType.Int32;
colvarIdPermisoHijo.MaxLength = 0;
colvarIdPermisoHijo.AutoIncrement = false;
colvarIdPermisoHijo.IsNullable = true;
colvarIdPermisoHijo.IsPrimaryKey = false;
colvarIdPermisoHijo.IsForeignKey = false;
colvarIdPermisoHijo.IsReadOnly = false;
colvarIdPermisoHijo.DefaultSetting = @"";
colvarIdPermisoHijo.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdPermisoHijo);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_arbol",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdNodo")]
[Bindable(true)]
public int IdNodo
{
get { return GetColumnValue<int>(Columns.IdNodo); }
set { SetColumnValue(Columns.IdNodo, value); }
}
[XmlAttribute("IdPermisoPadre")]
[Bindable(true)]
public int? IdPermisoPadre
{
get { return GetColumnValue<int?>(Columns.IdPermisoPadre); }
set { SetColumnValue(Columns.IdPermisoPadre, value); }
}
[XmlAttribute("IdPermisoHijo")]
[Bindable(true)]
public int? IdPermisoHijo
{
get { return GetColumnValue<int?>(Columns.IdPermisoHijo); }
set { SetColumnValue(Columns.IdPermisoHijo, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int? varIdPermisoPadre,int? varIdPermisoHijo)
{
PnArbol item = new PnArbol();
item.IdPermisoPadre = varIdPermisoPadre;
item.IdPermisoHijo = varIdPermisoHijo;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdNodo,int? varIdPermisoPadre,int? varIdPermisoHijo)
{
PnArbol item = new PnArbol();
item.IdNodo = varIdNodo;
item.IdPermisoPadre = varIdPermisoPadre;
item.IdPermisoHijo = varIdPermisoHijo;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdNodoColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdPermisoPadreColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdPermisoHijoColumn
{
get { return Schema.Columns[2]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdNodo = @"id_nodo";
public static string IdPermisoPadre = @"id_permiso_padre";
public static string IdPermisoHijo = @"id_permiso_hijo";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
// This object is used to wrap a bunch of ConnectAsync operations
// on behalf of a single user call to ConnectAsync with a DnsEndPoint
internal abstract class MultipleConnectAsync
{
protected SocketAsyncEventArgs _userArgs;
protected SocketAsyncEventArgs _internalArgs;
protected DnsEndPoint _endPoint;
protected IPAddress[] _addressList;
protected int _nextAddress;
private enum State
{
NotStarted,
DnsQuery,
ConnectAttempt,
Completed,
Canceled,
}
private State _state;
private object _lockObject = new object();
protected abstract Socket UserSocket { get; }
// Called by Socket to kick off the ConnectAsync process. We'll complete the user's SAEA
// when it's done. Returns true if the operation will be asynchronous, false if it has failed synchronously
public bool StartConnectAsync(SocketAsyncEventArgs args, DnsEndPoint endPoint)
{
lock (_lockObject)
{
if (endPoint.AddressFamily != AddressFamily.Unspecified &&
endPoint.AddressFamily != AddressFamily.InterNetwork &&
endPoint.AddressFamily != AddressFamily.InterNetworkV6)
{
NetEventSource.Fail(this, $"Unexpected endpoint address family: {endPoint.AddressFamily}");
}
_userArgs = args;
_endPoint = endPoint;
// If Cancel() was called before we got the lock, it only set the state to Canceled: we need to
// fail synchronously from here. Once State.DnsQuery is set, the Cancel() call will handle calling AsyncFail.
if (_state == State.Canceled)
{
SyncFail(new SocketException((int)SocketError.OperationAborted));
return false;
}
if (_state != State.NotStarted)
{
NetEventSource.Fail(this, "MultipleConnectAsync.StartConnectAsync(): Unexpected object state");
}
_state = State.DnsQuery;
IAsyncResult result = Dns.BeginGetHostAddresses(endPoint.Host, new AsyncCallback(DnsCallback), null);
if (result.CompletedSynchronously)
{
return DoDnsCallback(result, true);
}
else
{
return true;
}
}
}
// Callback which fires when the Dns Resolve is complete
private void DnsCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
DoDnsCallback(result, false);
}
}
// Called when the DNS query completes (either synchronously or asynchronously). Checks for failure and
// starts the first connection attempt if it succeeded. Returns true if the operation will be asynchronous,
// false if it has failed synchronously.
private bool DoDnsCallback(IAsyncResult result, bool sync)
{
Exception exception = null;
lock (_lockObject)
{
// If the connection attempt was canceled during the dns query, the user's callback has already been
// called asynchronously and we simply need to return.
if (_state == State.Canceled)
{
return true;
}
if (_state != State.DnsQuery)
{
NetEventSource.Fail(this, "MultipleConnectAsync.DoDnsCallback(): Unexpected object state");
}
try
{
_addressList = Dns.EndGetHostAddresses(result);
if (_addressList == null)
{
NetEventSource.Fail(this, "MultipleConnectAsync.DoDnsCallback(): EndGetHostAddresses returned null!");
}
}
catch (Exception e)
{
_state = State.Completed;
exception = e;
}
// If the dns query succeeded, try to connect to the first address
if (exception == null)
{
_state = State.ConnectAttempt;
_internalArgs = new SocketAsyncEventArgs();
_internalArgs.Completed += InternalConnectCallback;
_internalArgs.SetBuffer(_userArgs.Buffer, _userArgs.Offset, _userArgs.Count);
exception = AttemptConnection();
if (exception != null)
{
// There was a synchronous error while connecting
_state = State.Completed;
}
}
}
// Call this outside of the lock because it might call the user's callback.
if (exception != null)
{
return Fail(sync, exception);
}
else
{
return true;
}
}
// Callback which fires when an internal connection attempt completes.
// If it failed and there are more addresses to try, do it.
private void InternalConnectCallback(object sender, SocketAsyncEventArgs args)
{
Exception exception = null;
lock (_lockObject)
{
if (_state == State.Canceled)
{
// If Cancel was called before we got the lock, the Socket will be closed soon. We need to report
// OperationAborted (even though the connection actually completed), or the user will try to use a
// closed Socket.
exception = new SocketException((int)SocketError.OperationAborted);
}
else
{
Debug.Assert(_state == State.ConnectAttempt);
if (args.SocketError == SocketError.Success)
{
// The connection attempt succeeded; go to the completed state.
// The callback will be called outside the lock.
_state = State.Completed;
}
else if (args.SocketError == SocketError.OperationAborted)
{
// The socket was closed while the connect was in progress. This can happen if the user
// closes the socket, and is equivalent to a call to CancelConnectAsync
exception = new SocketException((int)SocketError.OperationAborted);
_state = State.Canceled;
}
else
{
// Keep track of this because it will be overwritten by AttemptConnection
SocketError currentFailure = args.SocketError;
Exception connectException = AttemptConnection();
if (connectException == null)
{
// don't call the callback, another connection attempt is successfully started
return;
}
else
{
SocketException socketException = connectException as SocketException;
if (socketException != null && socketException.SocketErrorCode == SocketError.NoData)
{
// If the error is NoData, that means there are no more IPAddresses to attempt
// a connection to. Return the last error from an actual connection instead.
exception = new SocketException((int)currentFailure);
}
else
{
exception = connectException;
}
_state = State.Completed;
}
}
}
}
if (exception == null)
{
Succeed();
}
else
{
AsyncFail(exception);
}
}
// Called to initiate a connection attempt to the next address in the list. Returns an exception
// if the attempt failed synchronously, or null if it was successfully initiated.
private Exception AttemptConnection()
{
try
{
Socket attemptSocket;
IPAddress attemptAddress = GetNextAddress(out attemptSocket);
if (attemptAddress == null)
{
return new SocketException((int)SocketError.NoData);
}
_internalArgs.RemoteEndPoint = new IPEndPoint(attemptAddress, _endPoint.Port);
return AttemptConnection(attemptSocket, _internalArgs);
}
catch (Exception e)
{
if (e is ObjectDisposedException)
{
NetEventSource.Fail(this, "unexpected ObjectDisposedException");
}
return e;
}
}
private static Exception AttemptConnection(Socket attemptSocket, SocketAsyncEventArgs args)
{
try
{
if (attemptSocket == null)
{
NetEventSource.Fail(null, "attemptSocket is null!");
}
if (!attemptSocket.ConnectAsync(args))
{
return new SocketException((int)args.SocketError);
}
}
catch (ObjectDisposedException)
{
// This can happen if the user closes the socket, and is equivalent to a call
// to CancelConnectAsync
return new SocketException((int)SocketError.OperationAborted);
}
catch (Exception e)
{
return e;
}
return null;
}
protected abstract void OnSucceed();
private void Succeed()
{
OnSucceed();
_userArgs.FinishWrapperConnectSuccess(_internalArgs.ConnectSocket, _internalArgs.BytesTransferred, _internalArgs.SocketFlags);
_internalArgs.Dispose();
}
protected abstract void OnFail(bool abortive);
private bool Fail(bool sync, Exception e)
{
if (sync)
{
SyncFail(e);
return false;
}
else
{
AsyncFail(e);
return true;
}
}
private void SyncFail(Exception e)
{
OnFail(false);
if (_internalArgs != null)
{
_internalArgs.Dispose();
}
SocketException socketException = e as SocketException;
if (socketException != null)
{
_userArgs.FinishConnectByNameSyncFailure(socketException, 0, SocketFlags.None);
}
else
{
ExceptionDispatchInfo.Capture(e).Throw();
}
}
private void AsyncFail(Exception e)
{
OnFail(false);
if (_internalArgs != null)
{
_internalArgs.Dispose();
}
_userArgs.FinishOperationAsyncFailure(e, 0, SocketFlags.None);
}
public void Cancel()
{
bool callOnFail = false;
lock (_lockObject)
{
switch (_state)
{
case State.NotStarted:
// Cancel was called before the Dns query was started. The dns query won't be started
// and the connection attempt will fail synchronously after the state change to DnsQuery.
// All we need to do here is close all the sockets.
callOnFail = true;
break;
case State.DnsQuery:
// Cancel was called after the Dns query was started, but before it finished. We can't
// actually cancel the Dns query, but we'll fake it by failing the connect attempt asynchronously
// from here, and silently dropping the connection attempt when the Dns query finishes.
Task.Factory.StartNew(
s => CallAsyncFail(s),
null,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
callOnFail = true;
break;
case State.ConnectAttempt:
// Cancel was called after the Dns query completed, but before we had a connection result to give
// to the user. Closing the sockets will cause any in-progress ConnectAsync call to fail immediately
// with OperationAborted, and will cause ObjectDisposedException from any new calls to ConnectAsync
// (which will be translated to OperationAborted by AttemptConnection).
callOnFail = true;
break;
case State.Completed:
// Cancel was called after we locked in a result to give to the user. Ignore it and give the user
// the real completion.
break;
default:
NetEventSource.Fail(this, "Unexpected object state");
break;
}
_state = State.Canceled;
}
// Call this outside the lock because Socket.Close may block
if (callOnFail)
{
OnFail(true);
}
}
// Call AsyncFail on a threadpool thread so it's asynchronous with respect to Cancel().
private void CallAsyncFail(object ignored)
{
AsyncFail(new SocketException((int)SocketError.OperationAborted));
}
protected abstract IPAddress GetNextAddress(out Socket attemptSocket);
}
// Used when the instance ConnectAsync method is called, or when the DnsEndPoint specified
// an AddressFamily. There's only one Socket, and we only try addresses that match its
// AddressFamily
internal sealed class SingleSocketMultipleConnectAsync : MultipleConnectAsync
{
private Socket _socket;
private bool _userSocket;
protected override Socket UserSocket => _socket;
public SingleSocketMultipleConnectAsync(Socket socket, bool userSocket)
{
_socket = socket;
_userSocket = userSocket;
}
protected override IPAddress GetNextAddress(out Socket attemptSocket)
{
_socket.ReplaceHandleIfNecessaryAfterFailedConnect();
IPAddress rval = null;
do
{
if (_nextAddress >= _addressList.Length)
{
attemptSocket = null;
return null;
}
rval = _addressList[_nextAddress];
++_nextAddress;
}
while (!_socket.CanTryAddressFamily(rval.AddressFamily));
attemptSocket = _socket;
return rval;
}
protected override void OnFail(bool abortive)
{
// Close the socket if this is an abortive failure (CancelConnectAsync)
// or if we created it internally
if (abortive || !_userSocket)
{
_socket.Dispose();
}
}
// nothing to do on success
protected override void OnSucceed() { }
}
// This is used when the static ConnectAsync method is called. We don't know the address family
// ahead of time, so we create both IPv4 and IPv6 sockets.
internal sealed class DualSocketMultipleConnectAsync : MultipleConnectAsync
{
private Socket _socket4;
private Socket _socket6;
protected override Socket UserSocket => null;
public DualSocketMultipleConnectAsync(SocketType socketType, ProtocolType protocolType)
{
if (Socket.OSSupportsIPv4)
{
_socket4 = new Socket(AddressFamily.InterNetwork, socketType, protocolType);
}
if (Socket.OSSupportsIPv6)
{
_socket6 = new Socket(AddressFamily.InterNetworkV6, socketType, protocolType);
}
}
protected override IPAddress GetNextAddress(out Socket attemptSocket)
{
IPAddress rval = null;
attemptSocket = null;
while (attemptSocket == null)
{
if (_nextAddress >= _addressList.Length)
{
return null;
}
rval = _addressList[_nextAddress];
++_nextAddress;
if (rval.AddressFamily == AddressFamily.InterNetworkV6)
{
attemptSocket = _socket6;
}
else if (rval.AddressFamily == AddressFamily.InterNetwork)
{
attemptSocket = _socket4;
}
}
attemptSocket?.ReplaceHandleIfNecessaryAfterFailedConnect();
return rval;
}
// on success, close the socket that wasn't used
protected override void OnSucceed()
{
if (_socket4 != null && !_socket4.Connected)
{
_socket4.Dispose();
}
if (_socket6 != null && !_socket6.Connected)
{
_socket6.Dispose();
}
}
// close both sockets whether its abortive or not - we always create them internally
protected override void OnFail(bool abortive)
{
_socket4?.Dispose();
_socket6?.Dispose();
}
}
}
| |
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using NHibernate;
using NHibernate.Metadata;
using NHibernate.Type;
using NHibernate.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Breeze.Core;
using Newtonsoft.Json.Converters;
using System.Threading.Tasks;
using System.Threading;
namespace Breeze.Persistence.NH {
/// <summary> Manage persistence for NHibernate entity models </summary>
public class NHPersistenceManager : Breeze.Persistence.PersistenceManager, IDisposable {
private readonly ISession session;
//protected Configuration configuration;
private static readonly Dictionary<ISessionFactory, NHBreezeMetadata> _factoryMetadata = new Dictionary<ISessionFactory, NHBreezeMetadata>();
private static readonly object _metadataLock = new object();
static NHPersistenceManager() {
EntityQuery.NeedsExecution = NHQueryHelper.NeedsExecution;
EntityQuery.ApplyCustomLogic = (eq, iq, type) => iq.Provider.CreateQuery(iq.Expression);
EntityQuery.AfterExecution = NHQueryHelper.PostExecuteQuery;
}
/// <summary>
/// Create a new context for the given session.
/// Each thread should have its own NHContext and Session.
/// </summary>
/// <param name="session">Used for queries and updates</param>
public NHPersistenceManager(ISession session) {
this.session = session;
}
/// <summary>
/// Creates a new context using the session and metadata from the sourceContext
/// </summary>
/// <param name="sourceContext">source of the Session and metadata used by this new context.</param>
public NHPersistenceManager(NHPersistenceManager sourceContext) {
this.session = sourceContext.Session;
this._metadata = sourceContext.GetMetadata();
}
/// <summary> The NHibernate session. Readonly. </summary>
public ISession Session {
get { return session; }
}
/// <summary>
/// Return a query for the given entity
/// </summary>
/// <typeparam name="T">Entity type</typeparam>
/// <param name="cacheable">Whether to mark the query Cacheable. Default is false.</param>
/// <returns></returns>
public IQueryable<T> GetQuery<T>(bool cacheable = false) {
var q = session.Query<T>();
if (cacheable) {
q = q.WithOptions(o => o.SetCacheable(true));
}
return q;
}
/// <summary>
/// Return a cacheable query for the given entity, using the given cache region
/// </summary>
/// <typeparam name="T">Entity type</typeparam>
/// <param name="cacheRegion">Cache region to use.</param>
/// <returns></returns>
public IQueryable<T> GetQuery<T>(string cacheRegion) {
var q = session.Query<T>().WithOptions(o => {
o.SetCacheable(true).SetCacheRegion(cacheRegion);
});
return q;
}
/// <summary>
/// Close the session
/// </summary>
public void Close() {
if (session != null && session.IsOpen) session.Close();
}
/// <summary>
/// Close the session
/// </summary>
public void Dispose() {
Close();
}
/// <returns>The connection from the session.</returns>
public override IDbConnection GetDbConnection() {
return session.Connection;
}
/// <summary> Does nothing; connection is already open when session is created </summary>
protected override void OpenDbConnection() {
}
/// <summary> Does nothing; connection is already open when session is created </summary>
protected override Task OpenDbConnectionAsync(CancellationToken cancellationToken) {
return Task.FromResult(0);
}
/// <summary> Close the session and its associated db connection </summary>
protected override void CloseDbConnection() {
if (session != null && session.IsOpen) {
var dbc = session.Close();
if (dbc != null) dbc.Close();
}
}
/// <summary> Close the session and its associated db connection </summary>
protected override Task CloseDbConnectionAsync() {
if (session != null && session.IsOpen) {
var dbc = session.Close();
if (dbc != null) {
return dbc.CloseAsync();
}
}
return Task.FromResult(0);
}
/// <summary> Start a transaction on the session </summary>
protected override IDbTransaction BeginTransaction(System.Data.IsolationLevel isolationLevel) {
var itran = session.BeginTransaction(isolationLevel);
var wrapper = new NHTransactionWrapper(itran, session.Connection, isolationLevel);
return wrapper;
}
/// <summary> Start a transaction on the session </summary>
protected override Task<IDbTransaction> BeginTransactionAsync(System.Data.IsolationLevel isolationLevel, CancellationToken cancellationToken) {
var itran = session.BeginTransaction(isolationLevel);
var wrapper = new NHTransactionWrapper(itran, session.Connection, isolationLevel);
return Task.FromResult(wrapper as IDbTransaction);
}
/// <summary> Get the primary key values for the entity </summary>
public override object[] GetKeyValues(EntityInfo entityInfo) {
return GetKeyValues(entityInfo.Entity);
}
/// <summary> Get the primary key values for the entity </summary>
public object[] GetKeyValues(object entity) {
var classMeta = session.SessionFactory.GetClassMetadata(entity.GetType());
if (classMeta == null) {
throw new ArgumentException("Metadata not found for type " + entity.GetType());
}
var keyValues = GetIdentifierAsArray(entity, classMeta);
return keyValues;
}
/// <summary>
/// Allows subclasses to process entities before they are saved. This method is called
/// after BeforeSaveEntities(saveMap), and before any session.Save methods are called.
/// The foreign-key associations on the entities have been resolved, relating the entities
/// to each other, and attaching proxies for other many-to-one associations.
/// </summary>
/// <param name="entitiesToPersist">List of entities in the order they will be saved</param>
/// <returns>The same entitiesToPersist. Overrides of this method may modify the list.</returns>
public virtual List<EntityInfo> BeforeSaveEntityGraph(List<EntityInfo> entitiesToPersist) {
return entitiesToPersist;
}
/// <summary>
/// If TypeFilter function is defined, returns TypeFilter(entityInfo.Entity.GetType())
/// </summary>
/// <param name="entityInfo"></param>
/// <returns>true if the entity should be saved, false if not</returns>
protected override bool BeforeSaveEntity(EntityInfo entityInfo) {
if (!base.BeforeSaveEntity(entityInfo)) return false;
if (this.TypeFilter == null) return true;
return this.TypeFilter(entityInfo.Entity.GetType());
}
#region Metadata
/// <summary>
/// Sets a function to filter types from metadata generation and SaveChanges.
/// The function returns true if a Type should be included, false otherwise.
/// </summary><example>
/// // exclude the LogRecord entity
/// MyNHContext.TypeFilter = (type) => type.Name != "LogRecord";
/// </example><example>
/// // exclude certain entities, and all Audit* entities
/// var excluded = new string[] { "Comment", "LogRecord", "UserPermission" };
/// MyNHContext.TypeFilter = (type) =>
/// {
/// if (excluded.Contains(type.Name)) return false;
/// if (type.Name.StartsWith("Audit")) return false;
/// return true;
/// };
/// </example>
public Func<Type, bool> TypeFilter { get; set; }
/// <summary> Build the JSON string of Breeze metadata for the NHibernate entity model </summary>
protected override string BuildJsonMetadata() {
var meta = GetMetadata();
var jss = new JsonSerializerSettings() {
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
jss.Converters.Add(new StringEnumConverter());
var json = JsonConvert.SerializeObject(meta, Formatting.Indented, jss);
return json;
}
/// <summary> Build the BreezeMetadata for the NHibernate entity model. </summary>
/// <remarks> The metadata structure is cached by the NHPersistenceManager instance. </remarks>
protected NHBreezeMetadata GetMetadata() {
if (_metadata == null) {
lock (_metadataLock) {
if (!_factoryMetadata.TryGetValue(session.SessionFactory, out _metadata)) {
var builder = new NHMetadataBuilder(session.SessionFactory);
_metadata = builder.BuildMetadata(TypeFilter);
_factoryMetadata.Add(session.SessionFactory, _metadata);
}
}
}
return _metadata;
}
#endregion
#region Save Changes
private readonly Dictionary<EntityInfo, KeyMapping> EntityKeyMapping = new Dictionary<EntityInfo, KeyMapping>();
private readonly List<EntityError> entityErrors = new List<EntityError>();
private NHBreezeMetadata _metadata;
/// <summary>
/// Persist the changes to the entities in the saveMap.
/// This implements the abstract method in PersistenceManager.
/// Assigns saveWorkState.KeyMappings, which map the temporary keys to their real generated keys.
/// Note that this method sets session.FlushMode = FlushMode.Never, so manual flushes are required.
/// </summary>
protected override void SaveChangesCore(SaveWorkState saveWorkState) {
var saveMap = saveWorkState.SaveMap;
session.FlushMode = FlushMode.Manual;
var tx = session.Transaction;
var hasExistingTransaction = tx.IsActive;
if (!hasExistingTransaction) tx.Begin(BreezeConfig.Instance.GetTransactionSettings().IsolationLevelAs);
try {
// Relate entities in the saveMap to other NH entities, so NH can save the FK values.
var fixer = GetRelationshipFixer(saveMap);
var saveOrder = fixer.FixupRelationships();
// Allow subclass to process entities before we save them
saveOrder = BeforeSaveEntityGraph(saveOrder);
ProcessSaves(saveOrder);
session.Flush();
RefreshFromSession(saveMap);
if (!hasExistingTransaction) tx.Commit();
fixer.RemoveRelationships();
} catch (PropertyValueException pve) {
// NHibernate can throw this
if (!hasExistingTransaction) tx.Rollback();
entityErrors.Add(new EntityError() {
EntityTypeName = pve.EntityName,
ErrorMessage = pve.Message,
ErrorName = "PropertyValueException",
KeyValues = null,
PropertyName = pve.PropertyName
});
saveWorkState.EntityErrors = entityErrors;
} catch (Exception) {
if (!hasExistingTransaction) tx.Rollback();
throw;
} finally {
if (!hasExistingTransaction) tx.Dispose();
}
saveWorkState.KeyMappings = UpdateAutoGeneratedKeys(saveWorkState.EntitiesWithAutoGeneratedKeys);
}
/// <summary>
/// Persist the changes to the entities in the saveMap.
/// This implements the abstract method in PersistenceManager.
/// Assigns saveWorkState.KeyMappings, which map the temporary keys to their real generated keys.
/// Note that this method sets session.FlushMode = FlushMode.Never, so manual flushes are required.
/// </summary>
protected override async Task SaveChangesCoreAsync(SaveWorkState saveWorkState, CancellationToken cancellationToken) {
var saveMap = saveWorkState.SaveMap;
session.FlushMode = FlushMode.Manual;
var tx = session.GetCurrentTransaction();
var hasExistingTransaction = tx != null && tx.IsActive;
if (!hasExistingTransaction) {
if (tx == null) {
tx = session.BeginTransaction(BreezeConfig.Instance.GetTransactionSettings().IsolationLevelAs);
} else {
tx.Begin(BreezeConfig.Instance.GetTransactionSettings().IsolationLevelAs);
}
}
try {
// Relate entities in the saveMap to other NH entities, so NH can save the FK values.
var fixer = GetRelationshipFixer(saveMap);
var saveOrder = fixer.FixupRelationships();
// Allow subclass to process entities before we save them
saveOrder = BeforeSaveEntityGraph(saveOrder);
await ProcessSavesAsync(saveOrder, cancellationToken);
await session.FlushAsync(cancellationToken);
await RefreshFromSessionAsync(saveMap, cancellationToken);
if (!hasExistingTransaction) {
await tx.CommitAsync(cancellationToken);
}
fixer.RemoveRelationships();
} catch (PropertyValueException pve) {
// NHibernate can throw this
if (!hasExistingTransaction) {
await tx.RollbackAsync(cancellationToken);
}
entityErrors.Add(new EntityError() {
EntityTypeName = pve.EntityName,
ErrorMessage = pve.Message,
ErrorName = "PropertyValueException",
KeyValues = null,
PropertyName = pve.PropertyName
});
saveWorkState.EntityErrors = entityErrors;
} catch (Exception) {
if (!hasExistingTransaction) {
await tx.RollbackAsync(cancellationToken);
}
throw;
} finally {
if (!hasExistingTransaction) {
tx.Dispose();
}
}
saveWorkState.KeyMappings = UpdateAutoGeneratedKeys(saveWorkState.EntitiesWithAutoGeneratedKeys);
}
/// <summary>
/// Get a new NHRelationshipFixer using the saveMap and the foreign-key map from the metadata.
/// </summary>
/// <param name="saveMap"></param>
/// <returns></returns>
protected NHRelationshipFixer GetRelationshipFixer(Dictionary<Type, List<EntityInfo>> saveMap) {
// Get the map of foreign key relationships from the metadata
var fkMap = GetMetadata().ForeignKeyMap;
return new NHRelationshipFixer(saveMap, fkMap, session);
}
/// <summary>
/// Persist the changes to the entities in the saveOrder.
/// </summary>
/// <param name="saveOrder"></param>
protected void ProcessSaves(List<EntityInfo> saveOrder) {
var sessionFactory = session.SessionFactory;
foreach (var entityInfo in saveOrder) {
var entityType = entityInfo.Entity.GetType();
var classMeta = sessionFactory.GetClassMetadata(entityType);
AddKeyMapping(entityInfo, entityType, classMeta);
ProcessEntity(entityInfo, classMeta);
}
}
/// <summary>
/// Persist the changes to the entities in the saveOrder.
/// </summary>
/// <param name="saveOrder"></param>
protected async Task ProcessSavesAsync(List<EntityInfo> saveOrder, CancellationToken cancellationToken) {
var sessionFactory = session.SessionFactory;
foreach (var entityInfo in saveOrder) {
var entityType = entityInfo.Entity.GetType();
var classMeta = sessionFactory.GetClassMetadata(entityType);
AddKeyMapping(entityInfo, entityType, classMeta);
// have to await each one, not use WhenAll(), because no parallelism
await ProcessEntityAsync(entityInfo, classMeta, cancellationToken);
}
}
/// <summary>
/// Add, update, or delete the entity according to its EntityState.
/// </summary>
/// <param name="entityInfo"></param>
protected void ProcessEntity(EntityInfo entityInfo, IClassMetadata classMeta) {
var entity = entityInfo.Entity;
var state = entityInfo.EntityState;
// Restore the old value of the concurrency column so Hibernate will be able to save the entity
if (classMeta.IsVersioned) {
RestoreOldVersionValue(entityInfo, classMeta);
}
if (state == EntityState.Modified) {
CheckForKeyUpdate(entityInfo, classMeta);
session.Update(entity);
} else if (state == EntityState.Added) {
session.Save(entity);
} else if (state == EntityState.Deleted) {
session.Delete(entity);
} else {
// Ignore EntityState.Unchanged. Too many problems using session.Lock or session.Merge
//session.Lock(entity, LockMode.None);
}
}
/// <summary>
/// Add, update, or delete the entity according to its EntityState.
/// </summary>
protected Task ProcessEntityAsync(EntityInfo entityInfo, IClassMetadata classMeta, CancellationToken cancellationToken) {
var entity = entityInfo.Entity;
var state = entityInfo.EntityState;
// Restore the old value of the concurrency column so Hibernate will be able to save the entity
if (classMeta.IsVersioned) {
RestoreOldVersionValue(entityInfo, classMeta);
}
if (state == EntityState.Modified) {
CheckForKeyUpdate(entityInfo, classMeta);
return session.UpdateAsync(entity, cancellationToken);
} else if (state == EntityState.Added) {
return session.SaveAsync(entity, cancellationToken);
} else if (state == EntityState.Deleted) {
return session.DeleteAsync(entity, cancellationToken);
} else {
// Ignore EntityState.Unchanged. Too many problems using session.Lock or session.Merge
//session.Lock(entity, LockMode.None);
return Task.FromResult(0);
}
}
/// <summary> Throw an exception if the OriginalValuesMap shows an attempt to update the entity's key </summary>
protected void CheckForKeyUpdate(EntityInfo entityInfo, IClassMetadata classMeta) {
if (classMeta.HasIdentifierProperty && entityInfo.OriginalValuesMap != null
&& entityInfo.OriginalValuesMap.ContainsKey(classMeta.IdentifierPropertyName)) {
var errors = new EntityError[1] {
new EntityError() {
EntityTypeName = entityInfo.Entity.GetType().FullName,
ErrorMessage = "Cannot update part of the entity's key",
ErrorName = "KeyUpdateException",
KeyValues = GetIdentifierAsArray(entityInfo.Entity, classMeta),
PropertyName = classMeta.IdentifierPropertyName
}};
throw new EntityErrorsException("Cannot update part of the entity's key", errors);
}
}
/// <summary>
/// Restore the old value of the concurrency column so Hibernate will save the entity.
/// Otherwise it will complain because Breeze has already changed the value.
/// </summary>
/// <param name="entityInfo"></param>
/// <param name="classMeta"></param>
protected void RestoreOldVersionValue(EntityInfo entityInfo, IClassMetadata classMeta) {
if (entityInfo.OriginalValuesMap == null || entityInfo.OriginalValuesMap.Count == 0) return;
var vcol = classMeta.VersionProperty;
var vname = classMeta.PropertyNames[vcol];
object oldVersion;
if (entityInfo.OriginalValuesMap.TryGetValue(vname, out oldVersion)) {
var entity = entityInfo.Entity;
var vtype = classMeta.PropertyTypes[vcol].ReturnedClass;
oldVersion = Convert.ChangeType(oldVersion, vtype); // because JsonConvert makes all integers Int64
classMeta.SetPropertyValue(entity, vname, oldVersion);
}
}
/// <summary>
/// Record the value of the temporary key in EntityKeyMapping
/// </summary>
/// <param name="entityInfo"></param>
protected void AddKeyMapping(EntityInfo entityInfo, Type type, IClassMetadata meta) {
if (entityInfo.EntityState != EntityState.Added) return;
var entity = entityInfo.Entity;
var id = GetIdentifier(entity, meta);
var km = new KeyMapping() { EntityTypeName = type.FullName, TempValue = id };
EntityKeyMapping.Add(entityInfo, km);
}
/// <summary>
/// Get the identifier value for the entity. If the entity does not have an
/// identifier property, or natural identifiers defined, then the entity itself is returned.
/// </summary>
/// <param name="entity"></param>
/// <param name="meta"></param>
/// <returns></returns>
protected object GetIdentifier(object entity, IClassMetadata meta = null) {
var type = entity.GetType();
meta = meta ?? session.SessionFactory.GetClassMetadata(type);
if (meta.IdentifierType != null) {
var id = meta.GetIdentifier(entity);
if (meta.IdentifierType.IsComponentType) {
var compType = (ComponentType)meta.IdentifierType;
return compType.GetPropertyValues(id);
} else {
return id;
}
} else if (meta.HasNaturalIdentifier) {
var idprops = meta.NaturalIdentifierProperties;
var values = meta.GetPropertyValues(entity);
var idvalues = idprops.Select(i => values[i]).ToArray();
return idvalues;
}
return entity;
}
/// <summary>
/// Get the identier value for the entity as an object[].
/// This is needed for creating an EntityError.
/// </summary>
/// <param name="entity"></param>
/// <param name="meta"></param>
/// <returns></returns>
protected object[] GetIdentifierAsArray(object entity, IClassMetadata meta) {
var value = GetIdentifier(entity, meta);
if (value.GetType().IsArray) {
return (object[])value;
} else {
return new object[] { value };
}
}
/// <summary>
/// Update the KeyMappings with their real values.
/// </summary>
/// <returns></returns>
protected List<KeyMapping> UpdateAutoGeneratedKeys(List<EntityInfo> entitiesWithAutoGeneratedKeys) {
var list = new List<KeyMapping>();
foreach (var entityInfo in entitiesWithAutoGeneratedKeys) {
KeyMapping km;
if (EntityKeyMapping.TryGetValue(entityInfo, out km)) {
if (km.TempValue != null) {
var entity = entityInfo.Entity;
var id = GetIdentifier(entity);
km.RealValue = id;
list.Add(km);
}
}
}
return list;
}
/// <summary>
/// Refresh the entities from the database. This picks up changes due to triggers, etc.
/// </summary>
/// TODO make this faster
/// TODO make this optional
/// <param name="saveMap"></param>
protected void RefreshFromSession(Dictionary<Type, List<EntityInfo>> saveMap) {
foreach (var kvp in saveMap) {
foreach (var entityInfo in kvp.Value) {
if (entityInfo.EntityState == EntityState.Added || entityInfo.EntityState == EntityState.Modified)
session.Refresh(entityInfo.Entity);
}
}
}
/// <summary>
/// Refresh the entities from the database. This picks up changes due to triggers, etc.
/// </summary>
/// TODO make this faster
/// TODO make this optional
/// <param name="saveMap"></param>
protected async Task RefreshFromSessionAsync(Dictionary<Type, List<EntityInfo>> saveMap, CancellationToken cancellationToken) {
foreach (var kvp in saveMap) {
foreach (var entityInfo in kvp.Value) {
if (entityInfo.EntityState == EntityState.Added || entityInfo.EntityState == EntityState.Modified)
// have to await, not WhenAll(), because no parallel operations
await session.RefreshAsync(entityInfo.Entity, cancellationToken);
}
}
}
#endregion
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>MediaFile</c> resource.</summary>
public sealed partial class MediaFileName : gax::IResourceName, sys::IEquatable<MediaFileName>
{
/// <summary>The possible contents of <see cref="MediaFileName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/mediaFiles/{media_file_id}</c>.
/// </summary>
CustomerMediaFile = 1,
}
private static gax::PathTemplate s_customerMediaFile = new gax::PathTemplate("customers/{customer_id}/mediaFiles/{media_file_id}");
/// <summary>Creates a <see cref="MediaFileName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="MediaFileName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static MediaFileName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new MediaFileName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="MediaFileName"/> with the pattern <c>customers/{customer_id}/mediaFiles/{media_file_id}</c>
/// .
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="mediaFileId">The <c>MediaFile</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="MediaFileName"/> constructed from the provided ids.</returns>
public static MediaFileName FromCustomerMediaFile(string customerId, string mediaFileId) =>
new MediaFileName(ResourceNameType.CustomerMediaFile, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), mediaFileId: gax::GaxPreconditions.CheckNotNullOrEmpty(mediaFileId, nameof(mediaFileId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="MediaFileName"/> with pattern
/// <c>customers/{customer_id}/mediaFiles/{media_file_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="mediaFileId">The <c>MediaFile</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="MediaFileName"/> with pattern
/// <c>customers/{customer_id}/mediaFiles/{media_file_id}</c>.
/// </returns>
public static string Format(string customerId, string mediaFileId) => FormatCustomerMediaFile(customerId, mediaFileId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="MediaFileName"/> with pattern
/// <c>customers/{customer_id}/mediaFiles/{media_file_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="mediaFileId">The <c>MediaFile</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="MediaFileName"/> with pattern
/// <c>customers/{customer_id}/mediaFiles/{media_file_id}</c>.
/// </returns>
public static string FormatCustomerMediaFile(string customerId, string mediaFileId) =>
s_customerMediaFile.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(mediaFileId, nameof(mediaFileId)));
/// <summary>Parses the given resource name string into a new <see cref="MediaFileName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/mediaFiles/{media_file_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="mediaFileName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="MediaFileName"/> if successful.</returns>
public static MediaFileName Parse(string mediaFileName) => Parse(mediaFileName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="MediaFileName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/mediaFiles/{media_file_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="mediaFileName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="MediaFileName"/> if successful.</returns>
public static MediaFileName Parse(string mediaFileName, bool allowUnparsed) =>
TryParse(mediaFileName, allowUnparsed, out MediaFileName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="MediaFileName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/mediaFiles/{media_file_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="mediaFileName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="MediaFileName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string mediaFileName, out MediaFileName result) => TryParse(mediaFileName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="MediaFileName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/mediaFiles/{media_file_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="mediaFileName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="MediaFileName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string mediaFileName, bool allowUnparsed, out MediaFileName result)
{
gax::GaxPreconditions.CheckNotNull(mediaFileName, nameof(mediaFileName));
gax::TemplatedResourceName resourceName;
if (s_customerMediaFile.TryParseName(mediaFileName, out resourceName))
{
result = FromCustomerMediaFile(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(mediaFileName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private MediaFileName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string mediaFileId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
MediaFileId = mediaFileId;
}
/// <summary>
/// Constructs a new instance of a <see cref="MediaFileName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/mediaFiles/{media_file_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="mediaFileId">The <c>MediaFile</c> ID. Must not be <c>null</c> or empty.</param>
public MediaFileName(string customerId, string mediaFileId) : this(ResourceNameType.CustomerMediaFile, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), mediaFileId: gax::GaxPreconditions.CheckNotNullOrEmpty(mediaFileId, nameof(mediaFileId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>MediaFile</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string MediaFileId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerMediaFile: return s_customerMediaFile.Expand(CustomerId, MediaFileId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as MediaFileName);
/// <inheritdoc/>
public bool Equals(MediaFileName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(MediaFileName a, MediaFileName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(MediaFileName a, MediaFileName b) => !(a == b);
}
public partial class MediaFile
{
/// <summary>
/// <see cref="gagvr::MediaFileName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal MediaFileName ResourceNameAsMediaFileName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::MediaFileName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::MediaFileName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
internal MediaFileName MediaFileName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::MediaFileName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// --------------------------------------------------------------------------------------------
#region // Copyright (c) 2020, SIL International. All Rights Reserved.
// <copyright from='2011' to='2020' company='SIL International'>
// Copyright (c) 2020, SIL International. All Rights Reserved.
//
// Distributable under the terms of the MIT License (https://sil.mit-license.org/)
// </copyright>
#endregion
// --------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using HearThis.Publishing;
using L10NSharp;
using SIL.DblBundle;
using SIL.DblBundle.Text;
using SIL.Reporting;
using SIL.Scripture;
using SIL.Xml;
namespace HearThis.Script
{
public class SampleScriptProvider : ScriptProviderBase, IProjectInfo
{
public const string kProjectUiName = "Sample";
public const string kProjectFolderName = "sample";
private readonly BibleStats _stats;
private readonly List<string> _paragraphStyleNames;
public override string ProjectFolderName
{
get { return kProjectFolderName; }
}
public override IEnumerable<string> AllEncounteredParagraphStyleNames
{
get { return _paragraphStyleNames; }
}
public override IBibleStats VersificationInfo
{
get { return _stats; }
}
public SampleScriptProvider()
{
_stats = new BibleStats();
_paragraphStyleNames = new List<string>(3);
_paragraphStyleNames.Add(LocalizationManager.GetString("Sample.ChapterStyleName", "Chapter", "Only for sample data"));
_paragraphStyleNames.Add(LocalizationManager.GetString("Sample.IntroductionParagraphStyleName", "Introduction", "Only for sample data"));
_paragraphStyleNames.Add(LocalizationManager.GetString("Sample.NormalParagraphStyleName", "Normal Paragraph", "Only for sample data"));
_paragraphStyleNames.Add(LocalizationManager.GetString("Sample.SectionHeadParagraphStyleName", "Section Head", "Only for sample data"));
Initialize();
try
{
CreateSampleRecordingsInfoAndProblems();
}
catch (Exception ex)
{
ErrorReport.ReportNonFatalExceptionWithMessage(ex,
LocalizationManager.GetString("Sample.ErrorGeneratingData", "An error occurred setting up the sample project."));
}
SetSkippedStyle(_paragraphStyleNames[3], true);
}
private void CreateSampleRecordingsInfoAndProblems()
{
var initializationInfo = XmlSerializationHelper.DeserializeFromString<Recordings>(Properties.Resources.SampleDataRecordngInfo);
foreach (var book in initializationInfo.Books)
{
var bookNum = BCVRef.BookToNumber(book.Id) - 1;
var bookInfo = new BookInfo(Name, bookNum, this);
foreach (var chapter in book.Chapters)
{
ChapterInfo info = null;
foreach (var recording in chapter.Recordings)
{
var scriptLine = GetBlock(bookNum, chapter.Number, recording.Block);
var wavFileName = ClipRepository.GetPathToLineRecording(Name, bookInfo.Name, chapter.Number, recording.Block);
using (var ms = new MemoryStream())
{
string wavStreamName = recording.Type == SampleRecordingType.ChapterAnnouncement ?
"sample" + recording.Type + (bookNum == BCVRef.BookToNumber("PSA") - 1 ? "Psalm" : "Chapter") + chapter.Number :
"sampleSentence" + recording.Type;
Properties.Resources.ResourceManager.GetStream(wavStreamName).CopyTo(ms);
using (var fs = new FileStream(wavFileName, FileMode.Create, FileAccess.Write))
ms.WriteTo(fs);
}
if (!recording.OmitInfo)
{
if (info == null)
info = ChapterInfo.Create(bookInfo, chapter.Number);
if (!string.IsNullOrEmpty(recording.Text))
scriptLine.Text = recording.Text;
scriptLine.RecordingTime = DateTime.Parse("2019-10-29 13:23:10");
info.OnScriptBlockRecorded(scriptLine);
}
}
}
}
}
// Nothing to do, sample script provider doesn't have cached script lines to update.
public override void UpdateSkipInfo()
{
}
private string NormalSampleTextLine => LocalizationManager.GetString("Sample.WouldBeSentence",
"Here if we were using a real project, there would be a sentence for you to read.", "Only for sample data");
public override ScriptLine GetBlock(int bookNumber, int chapterNumber, int lineNumber0Based)
{
string line;
int iStyle;
if (chapterNumber == 0)
{
line = LocalizationManager.GetString("Sample.Introductory", "Some introductory material about ", "Only for sample data") +
_stats.GetBookName(bookNumber);
iStyle = 1;
}
else if (lineNumber0Based == 0)
{
if (bookNumber == BCVRef.BookToNumber("PSA") - 1)
{
line = String.Format(LocalizationManager.GetString("Sample.PsalmFormat", "Psalm {0}", "Only for sample data; Param 0: Psalm number"),
chapterNumber);
}
else
{
line = String.Format(LocalizationManager.GetString("Sample.BookAndChapterFormat", "{0} Chapter {1}", "Only for sample data; Param 0: Book name; Param 1: Chapter number"),
_stats.GetBookName(bookNumber), chapterNumber);
}
iStyle = 0;
}
else if (IsEphesiansChapter3(bookNumber, chapterNumber) && lineNumber0Based == 4)
{
// In Ephesians 3, we throw in a section head before the block representing verse 4
// in order to illustrate an example of a block that uses a skipped style. Note that
// this corresponds to an entry in SampleDataRecordingInfo.xml because we wanted to
// be able to illustrate the problem case where a recording exists for a block that
// is supposed to be skipped. Ideally, that XML file and the classes that process it
// should be enhanced to allow for this special case to be represented fully rather
// than hard-coding it in this class.
line = LocalizationManager.GetString("Sample.SectionHeadInEph3", "The Mystery", "Only for sample data");
iStyle = 3;
}
else
{
line = NormalSampleTextLine;
iStyle = 2;
}
return new ScriptLine()
{
Number = lineNumber0Based + 1,
Text =line,
FontName = "Arial",
FontSize = 12,
ParagraphStyle = _paragraphStyleNames[iStyle],
Heading = iStyle == 0 || iStyle == 3,
Verse = chapterNumber > 0 ? (lineNumber0Based+1).ToString() : null
};
}
public override int GetScriptBlockCount(int bookNumber0Based, int chapter1Based)
{
if (chapter1Based == 0)//introduction
return 1;
// For most chapters, we just want one "extra" block for the chapter number.
// But for Ephesians 3, we throw in a section head in order to illustrate an
// example of a block that uses a skipped style.
var extra = IsEphesiansChapter3(bookNumber0Based, chapter1Based) ? 2 : 1;
return _stats.GetVersesInChapter(bookNumber0Based, chapter1Based) + extra;
}
// In Ephesians 3, we throw in a section head in order to illustrate an
// example of a block that uses a skipped style.
private bool IsEphesiansChapter3(int bookNumber0Based, int chapterNumber) =>
bookNumber0Based == BCVRef.BookToNumber("EPH") - 1 && chapterNumber == 3;
public override int GetSkippedScriptBlockCount(int bookNumber, int chapter1Based)
{
return GetScriptLines(bookNumber, chapter1Based).Count(s => s.Skipped);
}
public override int GetUnskippedScriptBlockCount(int bookNumber, int chapter1Based)
{
return GetScriptLines(bookNumber, chapter1Based).Count(s => !s.Skipped);
}
private IEnumerable<ScriptLine> GetScriptLines(int bookNumber, int chapter1Based)
{
List<ScriptLine> lines = new List<ScriptLine>();
for (int i = 0; i < GetScriptBlockCount(bookNumber, chapter1Based); i++)
{
lines.Add(GetBlock(bookNumber, chapter1Based, i));
PopulateSkippedFlag(bookNumber, chapter1Based, lines);
}
return lines;
}
public override int GetTranslatedVerseCount(int bookNumber0Based, int chapterNumber1Based)
{
return 1;
}
public override int GetScriptBlockCount(int bookNumber)
{
return _stats.GetChaptersInBook(bookNumber) * 10;
}
public override void LoadBook(int bookNumber0Based)
{
}
public override string EthnologueCode { get { return "KAL"; } }
public override bool RightToLeft { get { return false; } }
public override string FontName { get { return "Microsoft Sans Serif"; } }
public string Name { get { return kProjectUiName; } }
public string Id { get { return kProjectUiName; } }
public DblMetadataLanguage Language { get { return new DblMetadataLanguage { Iso="en", Name="English"}; } }
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="Networking.IPsecTrafficSelectorBinding", Namespace="urn:iControl")]
public partial class NetworkingIPsecTrafficSelector : iControlInterface {
public NetworkingIPsecTrafficSelector() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
public void create(
string [] selectors,
string [] src_addresses,
string [] src_netmasks,
string [] dst_addresses,
string [] dst_netmasks
) {
this.Invoke("create", new object [] {
selectors,
src_addresses,
src_netmasks,
dst_addresses,
dst_netmasks});
}
public System.IAsyncResult Begincreate(string [] selectors,string [] src_addresses,string [] src_netmasks,string [] dst_addresses,string [] dst_netmasks, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
selectors,
src_addresses,
src_netmasks,
dst_addresses,
dst_netmasks}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_traffic_selectors
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
public void delete_all_traffic_selectors(
) {
this.Invoke("delete_all_traffic_selectors", new object [0]);
}
public System.IAsyncResult Begindelete_all_traffic_selectors(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_traffic_selectors", new object[0], callback, asyncState);
}
public void Enddelete_all_traffic_selectors(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_traffic_selector
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
public void delete_traffic_selector(
string [] selectors
) {
this.Invoke("delete_traffic_selector", new object [] {
selectors});
}
public System.IAsyncResult Begindelete_traffic_selector(string [] selectors, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_traffic_selector", new object[] {
selectors}, callback, asyncState);
}
public void Enddelete_traffic_selector(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_action
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public NetworkingIPsecTrafficSelectorAction [] get_action(
string [] selectors
) {
object [] results = this.Invoke("get_action", new object [] {
selectors});
return ((NetworkingIPsecTrafficSelectorAction [])(results[0]));
}
public System.IAsyncResult Beginget_action(string [] selectors, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_action", new object[] {
selectors}, callback, asyncState);
}
public NetworkingIPsecTrafficSelectorAction [] Endget_action(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((NetworkingIPsecTrafficSelectorAction [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] selectors
) {
object [] results = this.Invoke("get_description", new object [] {
selectors});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] selectors, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
selectors}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_destination_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_destination_address(
string [] selectors
) {
object [] results = this.Invoke("get_destination_address", new object [] {
selectors});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_destination_address(string [] selectors, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_destination_address", new object[] {
selectors}, callback, asyncState);
}
public string [] Endget_destination_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_destination_netmask
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_destination_netmask(
string [] selectors
) {
object [] results = this.Invoke("get_destination_netmask", new object [] {
selectors});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_destination_netmask(string [] selectors, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_destination_netmask", new object[] {
selectors}, callback, asyncState);
}
public string [] Endget_destination_netmask(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_destination_port
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_destination_port(
string [] selectors
) {
object [] results = this.Invoke("get_destination_port", new object [] {
selectors});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_destination_port(string [] selectors, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_destination_port", new object[] {
selectors}, callback, asyncState);
}
public long [] Endget_destination_port(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_direction
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public NetworkingIPsecDirection [] get_direction(
string [] selectors
) {
object [] results = this.Invoke("get_direction", new object [] {
selectors});
return ((NetworkingIPsecDirection [])(results[0]));
}
public System.IAsyncResult Beginget_direction(string [] selectors, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_direction", new object[] {
selectors}, callback, asyncState);
}
public NetworkingIPsecDirection [] Endget_direction(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((NetworkingIPsecDirection [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ip_protocol
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_ip_protocol(
string [] selectors
) {
object [] results = this.Invoke("get_ip_protocol", new object [] {
selectors});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_ip_protocol(string [] selectors, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ip_protocol", new object[] {
selectors}, callback, asyncState);
}
public long [] Endget_ip_protocol(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_order
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_order(
string [] selectors
) {
object [] results = this.Invoke("get_order", new object [] {
selectors});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_order(string [] selectors, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_order", new object[] {
selectors}, callback, asyncState);
}
public long [] Endget_order(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_policy
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_policy(
string [] selectors
) {
object [] results = this.Invoke("get_policy", new object [] {
selectors});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_policy(string [] selectors, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_policy", new object[] {
selectors}, callback, asyncState);
}
public string [] Endget_policy(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_source_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_source_address(
string [] selectors
) {
object [] results = this.Invoke("get_source_address", new object [] {
selectors});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_source_address(string [] selectors, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_source_address", new object[] {
selectors}, callback, asyncState);
}
public string [] Endget_source_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_source_netmask
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_source_netmask(
string [] selectors
) {
object [] results = this.Invoke("get_source_netmask", new object [] {
selectors});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_source_netmask(string [] selectors, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_source_netmask", new object[] {
selectors}, callback, asyncState);
}
public string [] Endget_source_netmask(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_source_port
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_source_port(
string [] selectors
) {
object [] results = this.Invoke("get_source_port", new object [] {
selectors});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_source_port(string [] selectors, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_source_port", new object[] {
selectors}, callback, asyncState);
}
public long [] Endget_source_port(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// set_action
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
public void set_action(
string [] selectors,
NetworkingIPsecTrafficSelectorAction [] actions
) {
this.Invoke("set_action", new object [] {
selectors,
actions});
}
public System.IAsyncResult Beginset_action(string [] selectors,NetworkingIPsecTrafficSelectorAction [] actions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_action", new object[] {
selectors,
actions}, callback, asyncState);
}
public void Endset_action(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
public void set_description(
string [] selectors,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
selectors,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] selectors,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
selectors,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_destination_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
public void set_destination_address(
string [] selectors,
string [] addresses,
string [] netmasks
) {
this.Invoke("set_destination_address", new object [] {
selectors,
addresses,
netmasks});
}
public System.IAsyncResult Beginset_destination_address(string [] selectors,string [] addresses,string [] netmasks, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_destination_address", new object[] {
selectors,
addresses,
netmasks}, callback, asyncState);
}
public void Endset_destination_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_destination_port
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
public void set_destination_port(
string [] selectors,
long [] ports
) {
this.Invoke("set_destination_port", new object [] {
selectors,
ports});
}
public System.IAsyncResult Beginset_destination_port(string [] selectors,long [] ports, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_destination_port", new object[] {
selectors,
ports}, callback, asyncState);
}
public void Endset_destination_port(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_direction
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
public void set_direction(
string [] selectors,
NetworkingIPsecDirection [] directions
) {
this.Invoke("set_direction", new object [] {
selectors,
directions});
}
public System.IAsyncResult Beginset_direction(string [] selectors,NetworkingIPsecDirection [] directions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_direction", new object[] {
selectors,
directions}, callback, asyncState);
}
public void Endset_direction(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_ip_protocol
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
public void set_ip_protocol(
string [] selectors,
long [] ip_protocols
) {
this.Invoke("set_ip_protocol", new object [] {
selectors,
ip_protocols});
}
public System.IAsyncResult Beginset_ip_protocol(string [] selectors,long [] ip_protocols, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_ip_protocol", new object[] {
selectors,
ip_protocols}, callback, asyncState);
}
public void Endset_ip_protocol(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_order
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
public void set_order(
string [] selectors,
long [] orders
) {
this.Invoke("set_order", new object [] {
selectors,
orders});
}
public System.IAsyncResult Beginset_order(string [] selectors,long [] orders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_order", new object[] {
selectors,
orders}, callback, asyncState);
}
public void Endset_order(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_policy
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
public void set_policy(
string [] selectors,
string [] policies
) {
this.Invoke("set_policy", new object [] {
selectors,
policies});
}
public System.IAsyncResult Beginset_policy(string [] selectors,string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_policy", new object[] {
selectors,
policies}, callback, asyncState);
}
public void Endset_policy(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_source_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
public void set_source_address(
string [] selectors,
string [] addresses,
string [] netmasks
) {
this.Invoke("set_source_address", new object [] {
selectors,
addresses,
netmasks});
}
public System.IAsyncResult Beginset_source_address(string [] selectors,string [] addresses,string [] netmasks, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_source_address", new object[] {
selectors,
addresses,
netmasks}, callback, asyncState);
}
public void Endset_source_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_source_port
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecTrafficSelector",
RequestNamespace="urn:iControl:Networking/IPsecTrafficSelector", ResponseNamespace="urn:iControl:Networking/IPsecTrafficSelector")]
public void set_source_port(
string [] selectors,
long [] ports
) {
this.Invoke("set_source_port", new object [] {
selectors,
ports});
}
public System.IAsyncResult Beginset_source_port(string [] selectors,long [] ports, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_source_port", new object[] {
selectors,
ports}, callback, asyncState);
}
public void Endset_source_port(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Android.Views;
using Xamarin.Forms.Internals;
using AButton = Android.Widget.Button;
using AView = Android.Views.View;
using AndroidAnimation = Android.Animation;
namespace Xamarin.Forms.Platform.Android
{
public class NavigationRenderer : VisualElementRenderer<NavigationPage>
{
static ViewPropertyAnimator s_currentAnimation;
Page _current;
public NavigationRenderer()
{
AutoPackage = false;
}
public Task<bool> PopToRootAsync(Page page, bool animated = true)
{
return OnPopToRootAsync(page, animated);
}
public Task<bool> PopViewAsync(Page page, bool animated = true)
{
return OnPopViewAsync(page, animated);
}
public Task<bool> PushViewAsync(Page page, bool animated = true)
{
return OnPushAsync(page, animated);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
foreach (VisualElement child in Element.InternalChildren)
{
IVisualElementRenderer renderer = Platform.GetRenderer(child);
if (renderer != null)
renderer.Dispose();
}
if (Element != null)
{
var navController = (INavigationPageController)Element;
navController.PushRequested -= OnPushed;
navController.PopRequested -= OnPopped;
navController.PopToRootRequested -= OnPoppedToRoot;
navController.InsertPageBeforeRequested -= OnInsertPageBeforeRequested;
navController.RemovePageRequested -= OnRemovePageRequested;
}
}
base.Dispose(disposing);
}
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
Element.SendAppearing();
}
protected override void OnDetachedFromWindow()
{
base.OnDetachedFromWindow();
Element.SendDisappearing();
}
protected override void OnElementChanged(ElementChangedEventArgs<NavigationPage> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
var oldNavController = (INavigationPageController)e.OldElement;
oldNavController.PushRequested -= OnPushed;
oldNavController.PopRequested -= OnPopped;
oldNavController.PopToRootRequested -= OnPoppedToRoot;
oldNavController.InsertPageBeforeRequested -= OnInsertPageBeforeRequested;
oldNavController.RemovePageRequested -= OnRemovePageRequested;
RemoveAllViews();
}
var newNavController = (INavigationPageController)e.NewElement;
newNavController.PushRequested += OnPushed;
newNavController.PopRequested += OnPopped;
newNavController.PopToRootRequested += OnPoppedToRoot;
newNavController.InsertPageBeforeRequested += OnInsertPageBeforeRequested;
newNavController.RemovePageRequested += OnRemovePageRequested;
// If there is already stuff on the stack we need to push it
newNavController.StackCopy.Reverse().ForEach(p => PushViewAsync(p, false));
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
for (var i = 0; i < ChildCount; i++)
GetChildAt(i).Layout(0, 0, r - l, b - t);
}
protected virtual Task<bool> OnPopToRootAsync(Page page, bool animated)
{
return SwitchContentAsync(page, animated, true);
}
protected virtual Task<bool> OnPopViewAsync(Page page, bool animated)
{
Page pageToShow = ((INavigationPageController)Element).StackCopy.Skip(1).FirstOrDefault();
if (pageToShow == null)
return Task.FromResult(false);
return SwitchContentAsync(pageToShow, animated, true);
}
protected virtual Task<bool> OnPushAsync(Page view, bool animated)
{
return SwitchContentAsync(view, animated);
}
void InsertPageBefore(Page page, Page before)
{
}
void OnInsertPageBeforeRequested(object sender, NavigationRequestedEventArgs e)
{
InsertPageBefore(e.Page, e.BeforePage);
}
void OnPopped(object sender, NavigationRequestedEventArgs e)
{
e.Task = PopViewAsync(e.Page, e.Animated);
}
void OnPoppedToRoot(object sender, NavigationRequestedEventArgs e)
{
e.Task = PopToRootAsync(e.Page, e.Animated);
}
void OnPushed(object sender, NavigationRequestedEventArgs e)
{
e.Task = PushViewAsync(e.Page, e.Animated);
}
void OnRemovePageRequested(object sender, NavigationRequestedEventArgs e)
{
RemovePage(e.Page);
}
void RemovePage(Page page)
{
IVisualElementRenderer rendererToRemove = Platform.GetRenderer(page);
PageContainer containerToRemove = rendererToRemove == null ? null : (PageContainer)rendererToRemove.ViewGroup.Parent;
containerToRemove.RemoveFromParent();
if (rendererToRemove != null)
{
rendererToRemove.ViewGroup.RemoveFromParent();
rendererToRemove.Dispose();
}
containerToRemove?.Dispose();
Device.StartTimer(TimeSpan.FromMilliseconds(0), () =>
{
((Platform)Element.Platform).UpdateNavigationTitleBar();
return false;
});
}
Task<bool> SwitchContentAsync(Page view, bool animated, bool removed = false)
{
Context.HideKeyboard(this);
IVisualElementRenderer rendererToAdd = Platform.GetRenderer(view);
bool existing = rendererToAdd != null;
if (!existing)
Platform.SetRenderer(view, rendererToAdd = Platform.CreateRenderer(view));
Page pageToRemove = _current;
IVisualElementRenderer rendererToRemove = pageToRemove == null ? null : Platform.GetRenderer(pageToRemove);
PageContainer containerToRemove = rendererToRemove == null ? null : (PageContainer)rendererToRemove.ViewGroup.Parent;
PageContainer containerToAdd = (PageContainer)rendererToAdd.ViewGroup.Parent ?? new PageContainer(Context, rendererToAdd);
containerToAdd.SetWindowBackground();
_current = view;
((Platform)Element.Platform).NavAnimationInProgress = true;
var tcs = new TaskCompletionSource<bool>();
if (animated)
{
if (s_currentAnimation != null)
s_currentAnimation.Cancel();
if (removed)
{
// animate out
if (containerToAdd.Parent != this)
AddView(containerToAdd, Element.LogicalChildren.IndexOf(rendererToAdd.Element));
else
((Page)rendererToAdd.Element).SendAppearing();
containerToAdd.Visibility = ViewStates.Visible;
if (containerToRemove != null)
{
Action<AndroidAnimation.Animator> done = a =>
{
containerToRemove.Visibility = ViewStates.Gone;
containerToRemove.Alpha = 1;
containerToRemove.ScaleX = 1;
containerToRemove.ScaleY = 1;
RemoveView(containerToRemove);
tcs.TrySetResult(true);
((Platform)Element.Platform).NavAnimationInProgress = false;
VisualElement removedElement = rendererToRemove.Element;
rendererToRemove.Dispose();
if (removedElement != null)
Platform.SetRenderer(removedElement, null);
};
// should always happen
s_currentAnimation = containerToRemove.Animate().Alpha(0).ScaleX(0.8f).ScaleY(0.8f).SetDuration(250).SetListener(new GenericAnimatorListener { OnEnd = a =>
{
s_currentAnimation = null;
done(a);
},
OnCancel = done });
}
}
else
{
bool containerAlreadyAdded = containerToAdd.Parent == this;
// animate in
if (!containerAlreadyAdded)
AddView(containerToAdd);
else
((Page)rendererToAdd.Element).SendAppearing();
if (existing)
Element.ForceLayout();
containerToAdd.Alpha = 0;
containerToAdd.ScaleX = containerToAdd.ScaleY = 0.8f;
containerToAdd.Visibility = ViewStates.Visible;
s_currentAnimation = containerToAdd.Animate().Alpha(1).ScaleX(1).ScaleY(1).SetDuration(250).SetListener(new GenericAnimatorListener { OnEnd = a =>
{
if (containerToRemove != null && containerToRemove.Handle != IntPtr.Zero)
{
containerToRemove.Visibility = ViewStates.Gone;
if (pageToRemove != null)
pageToRemove.SendDisappearing();
}
s_currentAnimation = null;
tcs.TrySetResult(true);
((Platform)Element.Platform).NavAnimationInProgress = false;
} });
}
}
else
{
// just do it fast
if (containerToRemove != null)
{
if (removed)
RemoveView(containerToRemove);
else
containerToRemove.Visibility = ViewStates.Gone;
}
if (containerToAdd.Parent != this)
AddView(containerToAdd);
else
((Page)rendererToAdd.Element).SendAppearing();
if (containerToRemove != null && !removed)
pageToRemove.SendDisappearing();
if (existing)
Element.ForceLayout();
containerToAdd.Visibility = ViewStates.Visible;
tcs.SetResult(true);
((Platform)Element.Platform).NavAnimationInProgress = false;
}
return tcs.Task;
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
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.Windows.Forms;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml;
using System.Text;
using Axiom.Core;
using Axiom.Graphics;
using Axiom.MathLib;
using Multiverse.ToolBox;
namespace Multiverse.Tools.WorldEditor
{
public class GlobalFog : IWorldObject
{
protected float far;
protected float near;
protected ColorEx color;
protected IWorldContainer parent;
protected WorldEditor app;
protected WorldTreeNode parentNode;
protected WorldTreeNode node;
protected SceneManager scene;
protected List<ToolStripButton> buttonBar;
public GlobalFog(IWorldContainer parentContainer, WorldEditor worldEditor)
{
this.parent = parentContainer;
this.app = worldEditor;
this.scene = app.Scene;
this.color = app.Config.FogColorDefault;
this.far = app.Config.FogFarDefault;
this.near = app.Config.FogNearDefault;
}
public GlobalFog(IWorldContainer parentContainer, WorldEditor worldEditor, XmlReader r):
this(parentContainer, worldEditor)
{
fromXml(r);
}
[EditorAttribute(typeof(ColorValueUITypeEditor), typeof(System.Drawing.Design.UITypeEditor)),
DescriptionAttribute("Color of the fog (red, green, and blue values from 0 to 255).(click [...] to use the color picker dialog to select a color)."), CategoryAttribute("Miscellaneous")]
public ColorEx Color
{
get
{
return color;
}
set
{
color = value;
}
}
[BrowsableAttribute(true), DescriptionAttribute("Distance (in millimeters) from the camera where the fog effect reaches its maximum. Objects farther from the camera than this distance will be completely obscured (in this color)."), CategoryAttribute("Distance")]
public float Far
{
get
{
return far;
}
set
{
far = value;
}
}
[DescriptionAttribute("Distance (in millimeters) from the camera where the fog effect begins. Closer than this distance, there will be no fog effects."), CategoryAttribute("Distance")]
public float Near
{
get
{
return near;
}
set
{
near = value;
}
}
#region IWorldObject Members
public void AddToTree(WorldTreeNode parentNode)
{
this.parentNode = parentNode;
// add the Fog node
node = app.MakeTreeNode(this, "Global Fog");
parentNode.Nodes.Add(node);
CommandMenuBuilder menuBuilder = new CommandMenuBuilder();
menuBuilder.Add("Copy Description", "", app.copyToClipboardMenuButton_Click);
menuBuilder.Add("Help", "Global_Fog", app.HelpClickHandler);
node.ContextMenuStrip = menuBuilder.Menu;
buttonBar = menuBuilder.ButtonBar;
}
[BrowsableAttribute(false)]
public bool IsGlobal
{
get
{
return true;
}
}
[BrowsableAttribute(false)]
public bool IsTopLevel
{
get
{
return false;
}
}
[BrowsableAttribute(false)]
public bool WorldViewSelectable
{
get
{
return false;
}
set
{
// this property is not applicable to this object
}
}
public void Clone(IWorldContainer copyParent)
{
}
[BrowsableAttribute(false)]
public string ObjectAsString
{
get
{
string objString = String.Format("Name:{0}\r\n", ObjectType);
objString += String.Format("\tColor:\r\n");
objString += String.Format("\t\tR={0}\r\n",Color.r);
objString += String.Format("\t\tG={0}\r\n",Color.g);
objString += String.Format("\t\tB={0}\r\n",Color.b);
objString += String.Format("\tNear={0}\r\n",Near);
objString += String.Format("\tFar={0}\r\n",Far);
objString += "\r\n";
return objString;
}
}
[BrowsableAttribute(false)]
public List<ToolStripButton> ButtonBar
{
get
{
return buttonBar;
}
}
[BrowsableAttribute(false)]
public bool AcceptObjectPlacement
{
get
{
return false;
}
set
{
//not implemented for this type of object
}
}
public void RemoveFromTree()
{
if (node.IsSelected)
{
node.UnSelect();
}
parentNode.Nodes.Remove(node);
parentNode = null;
node = null;
}
public void AddToScene()
{
app.GlobalFog = this;
}
public void UpdateScene(UpdateTypes type, UpdateHint hint)
{
}
public void RemoveFromScene()
{
app.GlobalFog = null;
}
public void CheckAssets()
{
}
public void ToXml(XmlWriter w)
{
w.WriteStartElement("GlobalFog");
w.WriteAttributeString("Far", this.far.ToString());
w.WriteAttributeString("Near", this.near.ToString());
w.WriteStartElement("Color");
w.WriteAttributeString("R", this.color.r.ToString());
w.WriteAttributeString("G", this.color.g.ToString());
w.WriteAttributeString("B", this.color.b.ToString());
w.WriteEndElement(); // end color
w.WriteEndElement(); // end Fog
}
private void fromXml(XmlReader r)
{
// first parse the attributes
for (int i = 0; i < r.AttributeCount; i++)
{
r.MoveToAttribute(i);
// set the field in this object based on the element we just read
switch (r.Name)
{
case "Far":
this.far = float.Parse(r.Value);
break;
case "Near":
this.near = float.Parse(r.Value);
break;
}
}
r.MoveToElement(); //Moves the reader back to the element node.
// now parse the sub-elements
while (r.Read())
{
// look for the start of an element
if (r.NodeType == XmlNodeType.Element)
{
// parse that element
// save the name of the element
string elementName = r.Name;
switch (elementName)
{
case "Color":
color = XmlHelperClass.ParseColorAttributes(r);
break;
}
}
else if (r.NodeType == XmlNodeType.EndElement)
{
break;
}
}
}
[BrowsableAttribute(false)]
public Axiom.MathLib.Vector3 FocusLocation
{
get
{
return Vector3.Zero;
}
}
[BrowsableAttribute(false)]
public bool Highlight
{
get
{
return false;
}
set
{
}
}
[DescriptionAttribute("The type of this object."), CategoryAttribute("Miscellaneous")]
public string ObjectType
{
get
{
return "GlobalFog";
}
}
[BrowsableAttribute(false)]
public WorldTreeNode Node
{
get
{
return node;
}
set
{
node = value;
}
}
public void ToManifest(System.IO.StreamWriter w)
{
}
#endregion
#region IDisposable Members
public void Dispose()
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="etwprovider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <OWNER>[....]</OWNER>
//------------------------------------------------------------------------------
using Microsoft.Win32;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System;
namespace System.Diagnostics.Tracing
{
// New in CLR4.0
internal enum ControllerCommand
{
// Strictly Positive numbers are for provider-specific commands, negative number are for 'shared' commands. 256
// The first 256 negative numbers are reserved for the framework.
Update = 0, // Not used by EventPrividerBase.
SendManifest = -1,
Enable = -2,
Disable = -3,
};
/// <summary>
/// Only here because System.Diagnostics.EventProvider needs one more extensibility hook (when it gets a
/// controller callback)
/// </summary>
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
internal class EventProvider : IDisposable
{
// This is the windows EVENT_DATA_DESCRIPTOR structure. We expose it because this is what
// subclasses of EventProvider use when creating efficient (but unsafe) version of
// EventWrite. We do make it a nested type because we really don't expect anyone to use
// it except subclasses (and then only rarely).
public struct EventData
{
internal unsafe ulong Ptr;
internal uint Size;
internal uint Reserved;
}
/// <summary>
/// A struct characterizing ETW sessions (identified by the etwSessionId) as
/// activity-tracing-aware or legacy. A session that's activity-tracing-aware
/// has specified one non-zero bit in the reserved range 44-47 in the
/// 'allKeywords' value it passed in for a specific EventProvider.
/// </summary>
public struct SessionInfo
{
internal int sessionIdBit; // the index of the bit used for tracing in the "reserved" field of AllKeywords
internal int etwSessionId; // the machine-wide ETW session ID
internal SessionInfo(int sessionIdBit_, int etwSessionId_)
{ sessionIdBit = sessionIdBit_; etwSessionId = etwSessionId_; }
}
[SecurityCritical]
UnsafeNativeMethods.ManifestEtw.EtwEnableCallback m_etwCallback; // Trace Callback function
private long m_regHandle; // Trace Registration Handle
private byte m_level; // Tracing Level
private long m_anyKeywordMask; // Trace Enable Flags
private long m_allKeywordMask; // Match all keyword
private List<SessionInfo> m_liveSessions; // current live sessions (Tuple<sessionIdBit, etwSessionId>)
private bool m_enabled; // Enabled flag from Trace callback
private Guid m_providerId; // Control Guid
private int m_disposed; // when 1, provider has unregister
[ThreadStatic]
private static WriteEventErrorCode s_returnCode; // The last return code
private const int s_basicTypeAllocationBufferSize = 16;
private const int s_etwMaxMumberArguments = 32;
private const int s_etwAPIMaxStringCount = 8;
private const int s_maxEventDataDescriptors = 128;
private const int s_traceEventMaximumSize = 65482;
private const int s_traceEventMaximumStringSize = 32724;
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
public enum WriteEventErrorCode : int
{
//check mapping to runtime codes
NoError = 0,
NoFreeBuffers = 1,
EventTooBig = 2,
NullInput = 3,
TooManyArgs = 4,
Other = 5,
};
// <SecurityKernel Critical="True" Ring="1">
// <ReferencesCritical Name="Method: Register():Void" Ring="1" />
// </SecurityKernel>
/// <summary>
/// Constructs a new EventProvider. This causes the class to be registered with the OS and
/// if an ETW controller turns on the logging then logging will start.
/// </summary>
/// <param name="providerGuid">The GUID that identifies this provider to the system.</param>
[System.Security.SecurityCritical]
#pragma warning disable 618
[PermissionSet(SecurityAction.Demand, Unrestricted = true)]
#pragma warning restore 618
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "guid")]
protected EventProvider(Guid providerGuid)
{
m_providerId = providerGuid;
//
// Register the ProviderId with ETW
//
Register(providerGuid);
}
internal EventProvider()
{
}
/// <summary>
/// This method registers the controlGuid of this class with ETW. We need to be running on
/// Vista or above. If not a PlatformNotSupported exception will be thrown. If for some
/// reason the ETW Register call failed a NotSupported exception will be thrown.
/// </summary>
// <SecurityKernel Critical="True" Ring="0">
// <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventRegister(System.Guid&,Microsoft.Win32.UnsafeNativeMethods.ManifestEtw+EtwEnableCallback,System.Void*,System.Int64&):System.UInt32" />
// <SatisfiesLinkDemand Name="Win32Exception..ctor(System.Int32)" />
// <ReferencesCritical Name="Method: EtwEnableCallBack(Guid&, Int32, Byte, Int64, Int64, Void*, Void*):Void" Ring="1" />
// </SecurityKernel>
[System.Security.SecurityCritical]
internal unsafe void Register(Guid providerGuid)
{
m_providerId = providerGuid;
uint status;
m_etwCallback = new UnsafeNativeMethods.ManifestEtw.EtwEnableCallback(EtwEnableCallBack);
status = EventRegister(ref m_providerId, m_etwCallback);
if (status != 0)
{
throw new ArgumentException(Win32Native.GetMessage(unchecked((int)status)));
}
}
//
// implement Dispose Pattern to early deregister from ETW insted of waiting for
// the finalizer to call deregistration.
// Once the user is done with the provider it needs to call Close() or Dispose()
// If neither are called the finalizer will unregister the provider anyway
//
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// <SecurityKernel Critical="True" TreatAsSafe="Does not expose critical resource" Ring="1">
// <ReferencesCritical Name="Method: Deregister():Void" Ring="1" />
// </SecurityKernel>
[System.Security.SecuritySafeCritical]
protected virtual void Dispose(bool disposing)
{
//
// explicit cleanup is done by calling Dispose with true from
// Dispose() or Close(). The disposing arguement is ignored because there
// are no unmanaged resources.
// The finalizer calls Dispose with false.
//
//
// check if the object has been allready disposed
//
if (m_disposed == 1) return;
if (Interlocked.Exchange(ref m_disposed, 1) != 0)
{
// somebody is allready disposing the provider
return;
}
//
// Disables Tracing in the provider, then unregister
//
m_enabled = false;
Deregister();
}
/// <summary>
/// This method deregisters the controlGuid of this class with ETW.
///
/// </summary>
public virtual void Close()
{
Dispose();
}
~EventProvider()
{
Dispose(false);
}
/// <summary>
/// This method un-registers from ETW.
/// </summary>
// <SecurityKernel Critical="True" Ring="0">
// <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64):System.Int32" />
// </SecurityKernel>
//
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.Win32.UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64)"), System.Security.SecurityCritical]
private unsafe void Deregister()
{
//
// Unregister from ETW using the RegHandle saved from
// the register call.
//
if (m_regHandle != 0)
{
EventUnregister();
m_regHandle = 0;
}
}
// <SecurityKernel Critical="True" Ring="0">
// <UsesUnsafeCode Name="Parameter filterData of type: Void*" />
// <UsesUnsafeCode Name="Parameter callbackContext of type: Void*" />
// </SecurityKernel>
[System.Security.SecurityCritical]
unsafe void EtwEnableCallBack(
[In] ref System.Guid sourceId,
[In] int controlCode,
[In] byte setLevel,
[In] long anyKeyword,
[In] long allKeyword,
[In] UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData,
[In] void* callbackContext
)
{
ControllerCommand command = ControllerCommand.Update;
IDictionary<string, string> args = null;
byte[] data;
int keyIndex;
bool skipFinalOnControllerCommand = false;
EventSource.OutputDebugString(string.Format("EtwEnableCallBack(ctrl {0}, lvl {1}, any {2:x}, all {3:x})",
controlCode, setLevel, anyKeyword, allKeyword));
if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_ENABLE_PROVIDER)
{
m_enabled = true;
m_level = setLevel;
m_anyKeywordMask = anyKeyword;
m_allKeywordMask = allKeyword;
List<Tuple<SessionInfo, bool>> sessionsChanged = GetSessions();
foreach (var session in sessionsChanged)
{
int sessionChanged = session.Item1.sessionIdBit;
int etwSessionId = session.Item1.etwSessionId;
bool bEnabling = session.Item2;
EventSource.OutputDebugString(string.Format(CultureInfo.InvariantCulture, "EtwEnableCallBack: session changed {0}:{1}:{2}",
sessionChanged, etwSessionId, bEnabling));
skipFinalOnControllerCommand = true;
args = null; // reinitialize args for every session...
// if we get more than one session changed we have no way
// of knowing which one "filterData" belongs to
if (sessionsChanged.Count > 1)
filterData = null;
// read filter data only when a session is being *added*
if (bEnabling &&
GetDataFromController(etwSessionId, filterData, out command, out data, out keyIndex))
{
args = new Dictionary<string, string>(4);
while (keyIndex < data.Length)
{
int keyEnd = FindNull(data, keyIndex);
int valueIdx = keyEnd + 1;
int valueEnd = FindNull(data, valueIdx);
if (valueEnd < data.Length)
{
string key = System.Text.Encoding.UTF8.GetString(data, keyIndex, keyEnd - keyIndex);
string value = System.Text.Encoding.UTF8.GetString(data, valueIdx, valueEnd - valueIdx);
args[key] = value;
}
keyIndex = valueEnd + 1;
}
}
// execute OnControllerCommand once for every session that has changed.
try
{
OnControllerCommand(command, args, (bEnabling ? sessionChanged : -sessionChanged), etwSessionId);
}
catch (Exception)
{
// We want to ignore any failures that happen as a result of turning on this provider as to
// not crash the app.
}
}
}
else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_DISABLE_PROVIDER)
{
m_enabled = false;
m_level = 0;
m_anyKeywordMask = 0;
m_allKeywordMask = 0;
m_liveSessions = null;
}
else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_CAPTURE_STATE)
{
command = ControllerCommand.SendManifest;
}
else
return; // per spec you ignore commands you don't recognise.
try
{
if (!skipFinalOnControllerCommand)
OnControllerCommand(command, args, 0, 0);
}
catch (Exception)
{
// We want to ignore any failures that happen as a result of turning on this provider as to
// not crash the app.
}
}
// New in CLR4.0
protected virtual void OnControllerCommand(ControllerCommand command, IDictionary<string, string> arguments, int sessionId, int etwSessionId) { }
protected EventLevel Level { get { return (EventLevel)m_level; } set { m_level = (byte)value; } }
protected EventKeywords MatchAnyKeyword { get { return (EventKeywords)m_anyKeywordMask; } set { m_anyKeywordMask = (long)value; } }
protected EventKeywords MatchAllKeyword { get { return (EventKeywords)m_allKeywordMask; } set { m_allKeywordMask = (long)value; } }
static private int FindNull(byte[] buffer, int idx)
{
while (idx < buffer.Length && buffer[idx] != 0)
idx++;
return idx;
}
/// <summary>
/// Determines the ETW sessions that have been added and/or removed to the set of
/// sessions interested in the current provider. It does so by (1) enumerating over all
/// ETW sessions that enabled 'this.m_Guid' for the current process ID, and (2)
/// comparing the current list with a list it cached on the previous invocation.
///
/// The return value is a list of tuples, where the SessionInfo specifies the
/// ETW session that was added or remove, and the bool specifies whether the
/// session was added or whether it was removed from the set.
/// </summary>
[System.Security.SecuritySafeCritical]
private List<Tuple<SessionInfo, bool>> GetSessions()
{
List<SessionInfo> liveSessionList = null;
GetSessionInfo((Action<int, long>)
((etwSessionId, matchAllKeywords) =>
GetSessionInfoCallback(etwSessionId, matchAllKeywords, ref liveSessionList)));
List<Tuple<SessionInfo, bool>> changedSessionList = new List<Tuple<SessionInfo, bool>>();
// first look for sessions that have gone away (or have changed)
// (present in the m_liveSessions but not in the new liveSessionList)
if (m_liveSessions != null)
{
foreach(SessionInfo s in m_liveSessions)
{
int idx;
if ((idx = IndexOfSessionInList(liveSessionList, s.etwSessionId)) < 0 ||
(liveSessionList[idx].sessionIdBit != s.sessionIdBit))
changedSessionList.Add(Tuple.Create(s, false));
}
}
// next look for sessions that were created since the last callback (or have changed)
// (present in the new liveSessionList but not in m_liveSessions)
if (liveSessionList != null)
{
foreach (SessionInfo s in liveSessionList)
{
int idx;
if ((idx = IndexOfSessionInList(m_liveSessions, s.etwSessionId)) < 0 ||
(m_liveSessions[idx].sessionIdBit != s.sessionIdBit))
changedSessionList.Add(Tuple.Create(s, true));
}
}
m_liveSessions = liveSessionList;
return changedSessionList;
}
/// <summary>
/// This method is the callback used by GetSessions() when it calls into GetSessionInfo().
/// It updates a List<SessionInfo> based on the etwSessionId and matchAllKeywords that
/// GetSessionInfo() passes in.
/// </summary>
private static void GetSessionInfoCallback(int etwSessionId, long matchAllKeywords,
ref List<SessionInfo> sessionList)
{
uint sessionIdBitMask = (uint)SessionMask.FromEventKeywords((ulong)matchAllKeywords);
// an ETW controller that specifies more than the mandated bit for our EventSource
// will be ignored...
if (bitcount(sessionIdBitMask) > 1)
return;
if (sessionList == null)
sessionList = new List<SessionInfo>(8);
if (bitcount(sessionIdBitMask) == 1)
{
// activity-tracing-aware etw session
sessionList.Add(new SessionInfo(bitindex(sessionIdBitMask)+1, etwSessionId));
}
else
{
// legacy etw session
sessionList.Add(new SessionInfo(bitcount((uint)SessionMask.All)+1, etwSessionId));
}
}
/// <summary>
/// This method enumerates over all active ETW sessions that have enabled 'this.m_Guid'
/// for the current process ID, calling 'action' for each session, and passing it the
/// ETW session and the 'AllKeywords' the session enabled for the current provider.
/// </summary>
[System.Security.SecurityCritical]
private unsafe void GetSessionInfo(Action<int, long> action)
{
int buffSize = 256; // An initial guess that probably works most of the time.
byte* buffer;
for (; ; )
{
var space = stackalloc byte[buffSize];
buffer = space;
var hr = 0;
fixed (Guid* provider = &m_providerId)
{
hr = UnsafeNativeMethods.ManifestEtw.EnumerateTraceGuidsEx(UnsafeNativeMethods.ManifestEtw.TRACE_QUERY_INFO_CLASS.TraceGuidQueryInfo,
provider, sizeof(Guid), buffer, buffSize, ref buffSize);
}
if (hr == 0)
break;
if (hr != 122 /* ERROR_INSUFFICIENT_BUFFER */)
return;
}
var providerInfos = (UnsafeNativeMethods.ManifestEtw.TRACE_GUID_INFO*)buffer;
var providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&providerInfos[1];
int processId = (int)Win32Native.GetCurrentProcessId();
// iterate over the instances of the EventProvider in all processes
for (int i = 0; i < providerInfos->InstanceCount; i++)
{
if (providerInstance->Pid == processId)
{
var enabledInfos = (UnsafeNativeMethods.ManifestEtw.TRACE_ENABLE_INFO*)&providerInstance[1];
// iterate over the list of active ETW sessions "listening" to the current provider
for (int j = 0; j < providerInstance->EnableCount; j++)
action(enabledInfos[j].LoggerId, enabledInfos[j].MatchAllKeyword);
}
if (providerInstance->NextOffset == 0)
break;
Contract.Assert(0 <= providerInstance->NextOffset && providerInstance->NextOffset < buffSize);
var structBase = (byte*)providerInstance;
providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&structBase[providerInstance->NextOffset];
}
}
/// <summary>
/// Returns the index of the SesisonInfo from 'sessions' that has the specified 'etwSessionId'
/// or -1 if the value is not present.
/// <summary>
private static int IndexOfSessionInList(List<SessionInfo> sessions, int etwSessionId)
{
if (sessions == null)
return -1;
// for non-coreclr code we could use List<T>.FindIndex(Predicate<T>), but we need this to compile
// on coreclr as well
for (int i = 0; i < sessions.Count; ++i)
if (sessions[i].etwSessionId == etwSessionId)
return i;
return -1;
}
/// <summary>
/// Gets any data to be passed from the controller to the provider. It starts with what is passed
/// into the callback, but unfortunately this data is only present for when the provider is active
/// at the the time the controller issues the command. To allow for providers to activate after the
/// controller issued a command, we also check the registry and use that to get the data. The function
/// returns an array of bytes representing the data, the index into that byte array where the data
/// starts, and the command being issued associated with that data.
/// </summary>
[System.Security.SecurityCritical]
private unsafe bool GetDataFromController(int etwSessionId,
UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData, out ControllerCommand command, out byte[] data, out int dataStart)
{
data = null;
dataStart = 0;
if (filterData == null)
{
string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerId + "}";
if (System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8)
regKey = @"HKEY_LOCAL_MACHINE\Software" + @"\Wow6432Node" + regKey;
else
regKey = @"HKEY_LOCAL_MACHINE\Software" + regKey;
string valueName = "ControllerData_Session_" + etwSessionId.ToString(CultureInfo.InvariantCulture);
// we need to assert this permission for partial trust scenarios
new RegistryPermission(RegistryPermissionAccess.Read, regKey).Assert();
data = Microsoft.Win32.Registry.GetValue(regKey, valueName, null) as byte[];
if (data != null)
{
// We only used the persisted data from the registry for updates.
command = ControllerCommand.Update;
return true;
}
}
else
{
if (filterData->Ptr != 0 && 0 < filterData->Size && filterData->Size <= 1024)
{
data = new byte[filterData->Size];
Marshal.Copy((IntPtr)filterData->Ptr, data, 0, data.Length);
}
command = (ControllerCommand) filterData->Type;
return true;
}
command = ControllerCommand.Update;
return false;
}
/// <summary>
/// IsEnabled, method used to test if provider is enabled
/// </summary>
public bool IsEnabled()
{
return m_enabled;
}
/// <summary>
/// IsEnabled, method used to test if event is enabled
/// </summary>
/// <param name="Lvl">
/// Level to test
/// </param>
/// <param name="Keyword">
/// Keyword to test
/// </param>
public bool IsEnabled(byte level, long keywords)
{
//
// If not enabled at all, return false.
//
if (!m_enabled)
{
return false;
}
// This also covers the case of Level == 0.
if ((level <= m_level) ||
(m_level == 0))
{
//
// Check if Keyword is enabled
//
if ((keywords == 0) ||
(((keywords & m_anyKeywordMask) != 0) &&
((keywords & m_allKeywordMask) == m_allKeywordMask)))
{
return true;
}
}
return false;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
public static WriteEventErrorCode GetLastWriteEventError()
{
return s_returnCode;
}
//
// Helper function to set the last error on the thread
//
private static void SetLastError(int error)
{
switch (error)
{
case UnsafeNativeMethods.ManifestEtw.ERROR_ARITHMETIC_OVERFLOW:
case UnsafeNativeMethods.ManifestEtw.ERROR_MORE_DATA:
s_returnCode = WriteEventErrorCode.EventTooBig;
break;
case UnsafeNativeMethods.ManifestEtw.ERROR_NOT_ENOUGH_MEMORY:
s_returnCode = WriteEventErrorCode.NoFreeBuffers;
break;
}
}
// <SecurityKernel Critical="True" Ring="0">
// <UsesUnsafeCode Name="Local intptrPtr of type: IntPtr*" />
// <UsesUnsafeCode Name="Local intptrPtr of type: Int32*" />
// <UsesUnsafeCode Name="Local longptr of type: Int64*" />
// <UsesUnsafeCode Name="Local uintptr of type: UInt32*" />
// <UsesUnsafeCode Name="Local ulongptr of type: UInt64*" />
// <UsesUnsafeCode Name="Local charptr of type: Char*" />
// <UsesUnsafeCode Name="Local byteptr of type: Byte*" />
// <UsesUnsafeCode Name="Local shortptr of type: Int16*" />
// <UsesUnsafeCode Name="Local sbyteptr of type: SByte*" />
// <UsesUnsafeCode Name="Local ushortptr of type: UInt16*" />
// <UsesUnsafeCode Name="Local floatptr of type: Single*" />
// <UsesUnsafeCode Name="Local doubleptr of type: Double*" />
// <UsesUnsafeCode Name="Local boolptr of type: Boolean*" />
// <UsesUnsafeCode Name="Local guidptr of type: Guid*" />
// <UsesUnsafeCode Name="Local decimalptr of type: Decimal*" />
// <UsesUnsafeCode Name="Local booleanptr of type: Boolean*" />
// <UsesUnsafeCode Name="Parameter dataDescriptor of type: EventData*" />
// <UsesUnsafeCode Name="Parameter dataBuffer of type: Byte*" />
// </SecurityKernel>
[System.Security.SecurityCritical]
private static unsafe string EncodeObject(ref object data, EventData* dataDescriptor, byte* dataBuffer)
/*++
Routine Description:
This routine is used by WriteEvent to unbox the object type and
to fill the passed in ETW data descriptor.
Arguments:
data - argument to be decoded
dataDescriptor - pointer to the descriptor to be filled
dataBuffer - storage buffer for storing user data, needed because cant get the address of the object
Return Value:
null if the object is a basic type other than string. String otherwise
--*/
{
Again:
dataDescriptor->Reserved = 0;
string sRet = data as string;
if (sRet != null)
{
dataDescriptor->Size = (uint)((sRet.Length + 1) * 2);
return sRet;
}
if (data is IntPtr)
{
dataDescriptor->Size = (uint)sizeof(IntPtr);
IntPtr* intptrPtr = (IntPtr*)dataBuffer;
*intptrPtr = (IntPtr)data;
dataDescriptor->Ptr = (ulong)intptrPtr;
}
else if (data is int)
{
dataDescriptor->Size = (uint)sizeof(int);
int* intptr = (int*)dataBuffer;
*intptr = (int)data;
dataDescriptor->Ptr = (ulong)intptr;
}
else if (data is long)
{
dataDescriptor->Size = (uint)sizeof(long);
long* longptr = (long*)dataBuffer;
*longptr = (long)data;
dataDescriptor->Ptr = (ulong)longptr;
}
else if (data is uint)
{
dataDescriptor->Size = (uint)sizeof(uint);
uint* uintptr = (uint*)dataBuffer;
*uintptr = (uint)data;
dataDescriptor->Ptr = (ulong)uintptr;
}
else if (data is UInt64)
{
dataDescriptor->Size = (uint)sizeof(ulong);
UInt64* ulongptr = (ulong*)dataBuffer;
*ulongptr = (ulong)data;
dataDescriptor->Ptr = (ulong)ulongptr;
}
else if (data is char)
{
dataDescriptor->Size = (uint)sizeof(char);
char* charptr = (char*)dataBuffer;
*charptr = (char)data;
dataDescriptor->Ptr = (ulong)charptr;
}
else if (data is byte)
{
dataDescriptor->Size = (uint)sizeof(byte);
byte* byteptr = (byte*)dataBuffer;
*byteptr = (byte)data;
dataDescriptor->Ptr = (ulong)byteptr;
}
else if (data is short)
{
dataDescriptor->Size = (uint)sizeof(short);
short* shortptr = (short*)dataBuffer;
*shortptr = (short)data;
dataDescriptor->Ptr = (ulong)shortptr;
}
else if (data is sbyte)
{
dataDescriptor->Size = (uint)sizeof(sbyte);
sbyte* sbyteptr = (sbyte*)dataBuffer;
*sbyteptr = (sbyte)data;
dataDescriptor->Ptr = (ulong)sbyteptr;
}
else if (data is ushort)
{
dataDescriptor->Size = (uint)sizeof(ushort);
ushort* ushortptr = (ushort*)dataBuffer;
*ushortptr = (ushort)data;
dataDescriptor->Ptr = (ulong)ushortptr;
}
else if (data is float)
{
dataDescriptor->Size = (uint)sizeof(float);
float* floatptr = (float*)dataBuffer;
*floatptr = (float)data;
dataDescriptor->Ptr = (ulong)floatptr;
}
else if (data is double)
{
dataDescriptor->Size = (uint)sizeof(double);
double* doubleptr = (double*)dataBuffer;
*doubleptr = (double)data;
dataDescriptor->Ptr = (ulong)doubleptr;
}
else if (data is bool)
{
// WIN32 Bool is 4 bytes
dataDescriptor->Size = 4;
int* intptr = (int*)dataBuffer;
if (((bool)data))
{
*intptr = 1;
}
else
{
*intptr = 0;
}
dataDescriptor->Ptr = (ulong)intptr;
}
else if (data is Guid)
{
dataDescriptor->Size = (uint)sizeof(Guid);
Guid* guidptr = (Guid*)dataBuffer;
*guidptr = (Guid)data;
dataDescriptor->Ptr = (ulong)guidptr;
}
else if (data is decimal)
{
dataDescriptor->Size = (uint)sizeof(decimal);
decimal* decimalptr = (decimal*)dataBuffer;
*decimalptr = (decimal)data;
dataDescriptor->Ptr = (ulong)decimalptr;
}
else if (data is DateTime)
{
long dateTimeTicks = ((DateTime)data).ToFileTimeUtc();
dataDescriptor->Size = (uint)sizeof(long);
long* longptr = (long*)dataBuffer;
*longptr = dateTimeTicks;
dataDescriptor->Ptr = (ulong)longptr;
}
else
{
if (data is System.Enum)
{
Type underlyingType = Enum.GetUnderlyingType(data.GetType());
if (underlyingType == typeof(int))
{
data = ((IConvertible)data).ToInt32(null);
goto Again;
}
else if (underlyingType == typeof(long))
{
data = ((IConvertible)data).ToInt64(null);
goto Again;
}
}
//To our eyes, everything else is a just a string
if (data == null)
sRet = "";
else
sRet = data.ToString();
dataDescriptor->Size = (uint)((sRet.Length + 1) * 2);
return sRet;
}
return null;
}
/// <summary>
/// WriteEvent, method to write a parameters with event schema properties
/// </summary>
/// <param name="EventDescriptor">
/// Event Descriptor for this event.
/// </param>
// <SecurityKernel Critical="True" Ring="0">
// <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" />
// <UsesUnsafeCode Name="Local dataBuffer of type: Byte*" />
// <UsesUnsafeCode Name="Local pdata of type: Char*" />
// <UsesUnsafeCode Name="Local userData of type: EventData*" />
// <UsesUnsafeCode Name="Local userDataPtr of type: EventData*" />
// <UsesUnsafeCode Name="Local currentBuffer of type: Byte*" />
// <UsesUnsafeCode Name="Local v0 of type: Char*" />
// <UsesUnsafeCode Name="Local v1 of type: Char*" />
// <UsesUnsafeCode Name="Local v2 of type: Char*" />
// <UsesUnsafeCode Name="Local v3 of type: Char*" />
// <UsesUnsafeCode Name="Local v4 of type: Char*" />
// <UsesUnsafeCode Name="Local v5 of type: Char*" />
// <UsesUnsafeCode Name="Local v6 of type: Char*" />
// <UsesUnsafeCode Name="Local v7 of type: Char*" />
// <ReferencesCritical Name="Method: EncodeObject(Object&, EventData*, Byte*):String" Ring="1" />
// </SecurityKernel>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Performance-critical code")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
[System.Security.SecurityCritical]
internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* childActivityID, params object[] eventPayload)
{
int status = 0;
if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords))
{
int argCount = 0;
unsafe
{
argCount = eventPayload.Length;
if (argCount > s_etwMaxMumberArguments)
{
s_returnCode = WriteEventErrorCode.TooManyArgs;
return false;
}
uint totalEventSize = 0;
int index;
int stringIndex = 0;
List<int> stringPosition = new List<int>(s_etwAPIMaxStringCount);
List<string> dataString = new List<string>(s_etwAPIMaxStringCount);
EventData* userData = stackalloc EventData[argCount];
EventData* userDataPtr = (EventData*)userData;
byte* dataBuffer = stackalloc byte[s_basicTypeAllocationBufferSize * argCount]; // Assume 16 chars for non-string argument
byte* currentBuffer = dataBuffer;
//
// The loop below goes through all the arguments and fills in the data
// descriptors. For strings save the location in the dataString array.
// Calculates the total size of the event by adding the data descriptor
// size value set in EncodeObject method.
//
for (index = 0; index < eventPayload.Length; index++)
{
if (eventPayload[index] != null)
{
string isString;
isString = EncodeObject(ref eventPayload[index], userDataPtr, currentBuffer);
currentBuffer += s_basicTypeAllocationBufferSize;
totalEventSize += userDataPtr->Size;
userDataPtr++;
if (isString != null)
{
dataString.Add(isString);
stringPosition.Add(index);
stringIndex++;
}
}
else
{
s_returnCode = WriteEventErrorCode.NullInput;
return false;
}
}
if (totalEventSize > s_traceEventMaximumSize)
{
s_returnCode = WriteEventErrorCode.EventTooBig;
return false;
}
if (stringIndex < s_etwAPIMaxStringCount)
{
// Fast path: at most 8 string arguments
// ensure we have at least s_etwAPIMaxStringCount in dataString, so that
// the "fixed" statement below works
while (stringIndex < s_etwAPIMaxStringCount)
{
dataString.Add(null);
++stringIndex;
}
//
// now fix any string arguments and set the pointer on the data descriptor
//
fixed (char* v0 = dataString[0], v1 = dataString[1], v2 = dataString[2], v3 = dataString[3],
v4 = dataString[4], v5 = dataString[5], v6 = dataString[6], v7 = dataString[7])
{
userDataPtr = (EventData*)userData;
if (dataString[0] != null)
{
userDataPtr[stringPosition[0]].Ptr = (ulong)v0;
}
if (dataString[1] != null)
{
userDataPtr[stringPosition[1]].Ptr = (ulong)v1;
}
if (dataString[2] != null)
{
userDataPtr[stringPosition[2]].Ptr = (ulong)v2;
}
if (dataString[3] != null)
{
userDataPtr[stringPosition[3]].Ptr = (ulong)v3;
}
if (dataString[4] != null)
{
userDataPtr[stringPosition[4]].Ptr = (ulong)v4;
}
if (dataString[5] != null)
{
userDataPtr[stringPosition[5]].Ptr = (ulong)v5;
}
if (dataString[6] != null)
{
userDataPtr[stringPosition[6]].Ptr = (ulong)v6;
}
if (dataString[7] != null)
{
userDataPtr[stringPosition[7]].Ptr = (ulong)v7;
}
if (childActivityID == null)
status = UnsafeNativeMethods.ManifestEtw.EventWrite(m_regHandle, ref eventDescriptor, argCount, userData);
else
status = UnsafeNativeMethods.ManifestEtw.EventWriteTransfer(m_regHandle, ref eventDescriptor, null, childActivityID, argCount, userData);
}
}
else
{
// Slow path: use pinned handles
userDataPtr = (EventData*)userData;
GCHandle[] rgGCHandle = new GCHandle[stringIndex];
for (int i = 0; i < stringIndex; ++i)
{
rgGCHandle[i] = GCHandle.Alloc(dataString[i], GCHandleType.Pinned);
fixed (char* p = dataString[i])
userDataPtr[stringPosition[i]].Ptr = (ulong)p;
}
if (childActivityID == null)
status = UnsafeNativeMethods.ManifestEtw.EventWrite(m_regHandle, ref eventDescriptor, argCount, userData);
else
status = UnsafeNativeMethods.ManifestEtw.EventWriteTransfer(m_regHandle, ref eventDescriptor, null, childActivityID, argCount, userData);
for (int i = 0; i < stringIndex; ++i)
{
rgGCHandle[i].Free();
}
}
}
}
if (status != 0)
{
SetLastError((int)status);
return false;
}
return true;
}
/// <summary>
/// WriteEvent, method to be used by generated code on a derived class
/// </summary>
/// <param name="eventDescriptor">
/// Event Descriptor for this event.
/// </param>
/// <param name="childActivityID">
/// If this event is generating a child activity (WriteEventTransfer related activity) this is child activity
/// This can be null for events that do not generate a child activity.
/// </param>
/// <param name="dataCount">
/// number of event descriptors
/// </param>
/// <param name="data">
/// pointer do the event data
/// </param>
// <SecurityKernel Critical="True" Ring="0">
// <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" />
// </SecurityKernel>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
[System.Security.SecurityCritical]
internal unsafe protected bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* childActivityID, int dataCount, IntPtr data)
{
int status;
if (childActivityID == null)
{
status = UnsafeNativeMethods.ManifestEtw.EventWrite(m_regHandle, ref eventDescriptor, dataCount, (EventData*)data);
}
else
{
// activity transfers are supported only for events that specify the Send or Receive opcode
Contract.Assert((EventOpcode)eventDescriptor.Opcode == EventOpcode.Send ||
(EventOpcode)eventDescriptor.Opcode == EventOpcode.Receive);
status = UnsafeNativeMethods.ManifestEtw.EventWriteTransfer(m_regHandle, ref eventDescriptor, null, childActivityID, dataCount, (EventData*)data);
}
if (status != 0)
{
SetLastError(status);
return false;
}
return true;
}
[System.Security.SecurityCritical]
internal unsafe protected bool WriteEventString(EventLevel level, long keywords, string msg)
{
int status;
status = UnsafeNativeMethods.ManifestEtw.EventWriteString(m_regHandle, (byte) level, keywords, msg);
if (status != 0)
{
SetLastError(status);
return false;
}
return true;
}
// These are look-alikes to the Manifest based ETW OS APIs that have been shimmed to work
// either with Manifest ETW or Classic ETW (if Manifest based ETW is not available).
[SecurityCritical]
private unsafe uint EventRegister(ref Guid providerId, UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback)
{
m_providerId = providerId;
m_etwCallback = enableCallback;
return UnsafeNativeMethods.ManifestEtw.EventRegister(ref providerId, enableCallback, null, ref m_regHandle);
}
[SecurityCritical]
private uint EventUnregister()
{
uint status = UnsafeNativeMethods.ManifestEtw.EventUnregister(m_regHandle);
m_regHandle = 0;
return status;
}
static int[] nibblebits = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};
private static int bitcount(uint n)
{
int count = 0;
for(; n != 0; n = n >> 4)
count += nibblebits[n & 0x0f];
return count;
}
private static int bitindex(uint n)
{
Contract.Assert(bitcount(n) == 1);
int idx = 0;
while ((n & (1 << idx)) == 0)
idx++;
return idx;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter;
using Microsoft.Protocols.TestSuites.FileSharing.Common.TestSuite;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace Microsoft.Protocols.TestSuites.FileSharing.SMB2.TestSuite.ResilientHandle
{
[TestClass]
public class ResilientWithPersistentHandle : SMB2TestBase
{
public const LeaseStateValues LEASE_STATE = LeaseStateValues.SMB2_LEASE_READ_CACHING | LeaseStateValues.SMB2_LEASE_WRITE_CACHING | LeaseStateValues.SMB2_LEASE_HANDLE_CACHING;
#region Test Initialize and Cleanup
[ClassInitialize()]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
}
[ClassCleanup()]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
#region Test Case Initialize and Clean up
protected override void TestInitialize()
{
base.TestInitialize();
}
protected override void TestCleanup()
{
base.TestCleanup();
}
#endregion
#region Test Case
[TestMethod]
[TestCategory(TestCategories.Smb30)]
[TestCategory(TestCategories.CombinedFeature)]
[TestCategory(TestCategories.Positive)]
[Description("Verify that whether Open.IsResilient will impact persistent handle.")]
public void ResilientWithPersistentHandle_OpenFromDiffClient()
{
/// 1. Open Persistent Handle with lease
/// 2. Send Resiliency request
/// 3. Disconnect
/// 4. Open the same file from different client (different client guid)
/// 5. The expected result of OPEN is successful.
///
/// Covered TD, section
/// If Connection.Dialect is "3.000" and the request does not contain SMB2_CREATE_DURABLE_HANDLE_RECONNECT Create Context
/// or SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 Create Context, the server MUST look up an existing open in the
/// GlobalOpenTable where Open.FileName matches the file name in the Buffer field of the request. If an Open entry is found,
/// if Open.IsPersistent is TRUE, *Open.IsResilient is TRUE* and if Open.Connection is NULL, the server MUST fail the request with STATUS_FILE_NOT_AVAILABLE.
///
#region Check Applicability
TestConfig.CheckDialect(DialectRevision.Smb30);
TestConfig.CheckCapabilities(NEGOTIATE_Response_Capabilities_Values.GLOBAL_CAP_PERSISTENT_HANDLES);
#endregion
Smb2FunctionalClient client = new Smb2FunctionalClient(testConfig.Timeout, testConfig, this.Site);
Guid clientGuid = Guid.NewGuid();
Guid createGuid = Guid.NewGuid();
Guid leaseKey = Guid.NewGuid();
string fileName = "ResilientWithPersistentHandle_" + Guid.NewGuid() + ".txt";
FILEID fileId;
uint treeId;
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Open Persistent Handle with lease.");
OpenFile(
client,
clientGuid,
fileName,
true,
out createGuid,
out treeId,
out fileId);
// resiliency request
Packet_Header ioCtlHeader;
IOCTL_Response ioCtlResponse;
byte[] inputInResponse;
byte[] outputInResponse;
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"Send resiliency request with timeout {0} milliseconds", testConfig.MaxResiliencyTimeoutInSecond);
client.ResiliencyRequest(
treeId,
fileId,
testConfig.MaxResiliencyTimeoutInSecond,
(uint)Marshal.SizeOf(typeof(NETWORK_RESILIENCY_Request)),
out ioCtlHeader,
out ioCtlResponse,
out inputInResponse,
out outputInResponse
);
// Disconnect
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"Disconnect the resilient handle");
client.Disconnect();
// open from another client
Smb2FunctionalClient anotherClient = new Smb2FunctionalClient(testConfig.Timeout, testConfig, this.Site);
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"Open the same file from different client (different client guid), the expected result of OPEN is successful");
OpenFile(
anotherClient,
Guid.NewGuid(),
fileName,
false,
out createGuid,
out treeId,
out fileId);
}
#endregion
#region Private Methods
private void OpenFile(
Smb2FunctionalClient client,
Guid clientGuid,
string fileName,
bool isPersistentHandle,
out Guid createGuid,
out uint treeId,
out FILEID fileId)
{
// connect to share
ConnectToShare(
client,
clientGuid,
out treeId);
BaseTestSite.Log.Add(
LogEntryKind.Debug,
"Connect to share '{0}' on scaleout server '{1}'", testConfig.BasicFileShare, testConfig.SutComputerName);
#region Construct Create Context
List<Smb2CreateContextRequest> createContextList = new List<Smb2CreateContextRequest>();
createGuid = Guid.Empty;
if (isPersistentHandle)
{
// durable handle request context
createGuid = Guid.NewGuid();
createContextList.Add(new Smb2CreateDurableHandleRequestV2()
{
CreateGuid = createGuid,
Flags = CREATE_DURABLE_HANDLE_REQUEST_V2_Flags.DHANDLE_FLAG_PERSISTENT,
Timeout = 0 // default
});
}
#endregion
// open file
Smb2CreateContextResponse[] createContextResponses;
client.Create(
treeId,
fileName,
CreateOptions_Values.FILE_NON_DIRECTORY_FILE,
out fileId,
out createContextResponses,
createContexts: createContextList.ToArray<Smb2CreateContextRequest>()
);
BaseTestSite.Log.Add(
LogEntryKind.Debug,
"Create Open with file name '{0}'", fileName);
#region check whether Persistent Handle is created successfully with current status
if (isPersistentHandle)
{
BaseTestSite.Assert.IsTrue(
CheckDurableCreateContextResponse(createContextResponses),
"Create Response should contain Smb2CreateDurableHandleResponseV2.");
}
#endregion
}
private void ConnectToShare(
Smb2FunctionalClient client,
Guid clientGuid,
out uint treeId)
{
client.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.CAShareServerName, TestConfig.CAShareServerIP);
// Negotiate
client.Negotiate(
TestConfig.RequestDialects,
TestConfig.IsSMB1NegotiateEnabled,
capabilityValue: Capabilities_Values.GLOBAL_CAP_PERSISTENT_HANDLES,
clientGuid: clientGuid,
checker: (header, response) =>
{
BaseTestSite.Assert.AreEqual<NtStatus>(
NtStatus.STATUS_SUCCESS,
(NtStatus)header.Status,
"Negotiate should be successfully");
TestConfig.CheckNegotiateDialect(DialectRevision.Smb30, response);
TestConfig.CheckNegotiateCapabilities(NEGOTIATE_Response_Capabilities_Values.GLOBAL_CAP_PERSISTENT_HANDLES, response);
}
);
// SMB2 SESSION SETUP
client.SessionSetup(
TestConfig.DefaultSecurityPackage,
TestConfig.CAShareServerName,
TestConfig.AccountCredential,
TestConfig.UseServerGssToken);
// SMB2 Tree Connect
client.TreeConnect(
Smb2Utility.GetUncPath(TestConfig.CAShareServerName, TestConfig.CAShareName),
out treeId,
checker: (header, response) =>
{
BaseTestSite.Assert.AreEqual<NtStatus>(
NtStatus.STATUS_SUCCESS,
(NtStatus)header.Status,
"TreeConnect should be successfully");
// Check IsCA
BaseTestSite.Assert.IsTrue(
response.Capabilities.HasFlag(Share_Capabilities_Values.SHARE_CAP_CONTINUOUS_AVAILABILITY),
"Share should support capabilities of SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY ");
});
}
private bool CheckDurableCreateContextResponse(Smb2CreateContextResponse[] createContextResponses)
{
// check whether Persistent Handle is created successfully
foreach (Smb2CreateContextResponse contextResponse in createContextResponses)
{
Smb2CreateDurableHandleResponseV2 durableHandleResponse = contextResponse as Smb2CreateDurableHandleResponseV2;
if (durableHandleResponse != null)
{
BaseTestSite.Assert.IsTrue(
durableHandleResponse.Flags.HasFlag(CREATE_DURABLE_HANDLE_RESPONSE_V2_Flags.DHANDLE_FLAG_PERSISTENT),
"Flags in Smb2CreateDurableHandleResponseV2 should be Persistent flag");
return true;
}
}
return false;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.MachineLearning.WebServices
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// WebServicesOperations operations.
/// </summary>
internal partial class WebServicesOperations : IServiceOperations<AzureMLWebServicesManagementClient>, IWebServicesOperations
{
/// <summary>
/// Initializes a new instance of the WebServicesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal WebServicesOperations(AzureMLWebServicesManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AzureMLWebServicesManagementClient
/// </summary>
public AzureMLWebServicesManagementClient Client { get; private set; }
/// <summary>
/// Creates or updates a new Azure ML web service or update an existing one.
/// </summary>
/// <param name='createOrUpdatePayload'>
/// The payload to create or update the Azure ML web service.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<WebService>> CreateOrUpdateWithHttpMessagesAsync(WebService createOrUpdatePayload, string resourceGroupName, string webServiceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<WebService> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(
createOrUpdatePayload, resourceGroupName, webServiceName, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync(_response,
customHeaders,
cancellationToken);
}
/// <summary>
/// Creates or updates a new Azure ML web service or update an existing one.
/// </summary>
/// <param name='createOrUpdatePayload'>
/// The payload to create or update the Azure ML web service.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<WebService>> BeginCreateOrUpdateWithHttpMessagesAsync(WebService createOrUpdatePayload, string resourceGroupName, string webServiceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (createOrUpdatePayload == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "createOrUpdatePayload");
}
if (createOrUpdatePayload != null)
{
createOrUpdatePayload.Validate();
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (webServiceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "webServiceName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("createOrUpdatePayload", createOrUpdatePayload);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("webServiceName", webServiceName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/webServices/{webServiceName}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{webServiceName}", Uri.EscapeDataString(webServiceName));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(createOrUpdatePayload != null)
{
_requestContent = SafeJsonConvert.SerializeObject(createOrUpdatePayload, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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<WebService>();
_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 = SafeJsonConvert.DeserializeObject<WebService>(_responseContent, this.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 = SafeJsonConvert.DeserializeObject<WebService>(_responseContent, this.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>
/// Retrieve an Azure ML web service definition by its subscription, resource
/// group and name.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<WebService>> GetWithHttpMessagesAsync(string resourceGroupName, string webServiceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (webServiceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "webServiceName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// 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("webServiceName", webServiceName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/webServices/{webServiceName}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{webServiceName}", Uri.EscapeDataString(webServiceName));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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<WebService>();
_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 = SafeJsonConvert.DeserializeObject<WebService>(_responseContent, this.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>
/// Patch an existing Azure ML web service resource.
/// </summary>
/// <param name='patchPayload'>
/// The payload to patch the Azure ML web service with.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<WebService>> PatchWithHttpMessagesAsync(WebService patchPayload, string resourceGroupName, string webServiceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<WebService> _response = await BeginPatchWithHttpMessagesAsync(
patchPayload, resourceGroupName, webServiceName, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync(_response,
customHeaders,
cancellationToken);
}
/// <summary>
/// Patch an existing Azure ML web service resource.
/// </summary>
/// <param name='patchPayload'>
/// The payload to patch the Azure ML web service with.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<WebService>> BeginPatchWithHttpMessagesAsync(WebService patchPayload, string resourceGroupName, string webServiceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (patchPayload == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "patchPayload");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (webServiceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "webServiceName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("patchPayload", patchPayload);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("webServiceName", webServiceName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginPatch", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/webServices/{webServiceName}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{webServiceName}", Uri.EscapeDataString(webServiceName));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(patchPayload != null)
{
_requestContent = SafeJsonConvert.SerializeObject(patchPayload, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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<WebService>();
_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 = SafeJsonConvert.DeserializeObject<WebService>(_responseContent, this.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>
/// Remove an existing Azure ML web service.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> RemoveWithHttpMessagesAsync(string resourceGroupName, string webServiceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginRemoveWithHttpMessagesAsync(
resourceGroupName, webServiceName, customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// Remove an existing Azure ML web service.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginRemoveWithHttpMessagesAsync(string resourceGroupName, string webServiceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (webServiceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "webServiceName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// 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("webServiceName", webServiceName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginRemove", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/webServices/{webServiceName}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{webServiceName}", Uri.EscapeDataString(webServiceName));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 != 202 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
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>
/// Get the access keys of a particular Azure ML web service
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<WebServiceKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string webServiceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (webServiceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "webServiceName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// 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("webServiceName", webServiceName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListKeys", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/webServices/{webServiceName}/listKeys").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{webServiceName}", Uri.EscapeDataString(webServiceName));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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<WebServiceKeys>();
_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 = SafeJsonConvert.DeserializeObject<WebServiceKeys>(_responseContent, this.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>
/// Retrieve all Azure ML web services in a given resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='skiptoken'>
/// Continuation token for pagination.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<PaginatedWebServicesList>> ListInResourceGroupWithHttpMessagesAsync(string resourceGroupName, string skiptoken = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// 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("skiptoken", skiptoken);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListInResourceGroup", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/webServices").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (skiptoken != null)
{
_queryParameters.Add(string.Format("$skiptoken={0}", Uri.EscapeDataString(skiptoken)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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<PaginatedWebServicesList>();
_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 = SafeJsonConvert.DeserializeObject<PaginatedWebServicesList>(_responseContent, this.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>
/// Retrieve all Azure ML web services in the current Azure subscription.
/// </summary>
/// <param name='skiptoken'>
/// Continuation token for pagination.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<PaginatedWebServicesList>> ListWithHttpMessagesAsync(string skiptoken = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("skiptoken", skiptoken);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.MachineLearning/webServices").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (skiptoken != null)
{
_queryParameters.Add(string.Format("$skiptoken={0}", Uri.EscapeDataString(skiptoken)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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<PaginatedWebServicesList>();
_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 = SafeJsonConvert.DeserializeObject<PaginatedWebServicesList>(_responseContent, this.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;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.HSSF.Record.Chart
{
using System;
using System.Text;
using NPOI.HSSF.Record;
using NPOI.Util;
/**
* This record refers to a category or series axis and is used to specify label/tickmark frequency.<p/>
*
* @author Glen Stampoultzis (glens at apache.org)
*/
public class CategorySeriesAxisRecord : StandardRecord, ICloneable
{
public static short sid = 0x1020;
private static BitField valueAxisCrossing = BitFieldFactory.GetInstance(0x1);
private static BitField crossesFarRight = BitFieldFactory.GetInstance(0x2);
private static BitField reversed = BitFieldFactory.GetInstance(0x4);
private short field_1_crossingPoint;
private short field_2_labelFrequency;
private short field_3_tickMarkFrequency;
private short field_4_options;
public CategorySeriesAxisRecord()
{
}
public CategorySeriesAxisRecord(RecordInputStream in1)
{
field_1_crossingPoint = in1.ReadShort();
field_2_labelFrequency = in1.ReadShort();
field_3_tickMarkFrequency = in1.ReadShort();
field_4_options = in1.ReadShort();
}
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("[CATSERRANGE]\n");
buffer.Append(" .crossingPoint = ")
.Append("0x").Append(HexDump.ToHex(CrossingPoint))
.Append(" (").Append(CrossingPoint).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .labelFrequency = ")
.Append("0x").Append(HexDump.ToHex(LabelFrequency))
.Append(" (").Append(LabelFrequency).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .tickMarkFrequency = ")
.Append("0x").Append(HexDump.ToHex(TickMarkFrequency))
.Append(" (").Append(TickMarkFrequency).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .options = ")
.Append("0x").Append(HexDump.ToHex(Options))
.Append(" (").Append(Options).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .valueAxisCrossing = ").Append(IsValueAxisCrossing).Append('\n');
buffer.Append(" .crossesFarRight = ").Append(IsCrossesFarRight).Append('\n');
buffer.Append(" .reversed = ").Append(IsReversed).Append('\n');
buffer.Append("[/CATSERRANGE]\n");
return buffer.ToString();
}
public override void Serialize(ILittleEndianOutput out1)
{
out1.WriteShort(field_1_crossingPoint);
out1.WriteShort(field_2_labelFrequency);
out1.WriteShort(field_3_tickMarkFrequency);
out1.WriteShort(field_4_options);
}
protected override int DataSize
{
get
{
return 2 + 2 + 2 + 2;
}
}
public override short Sid
{
get
{
return sid;
}
}
public override object Clone()
{
CategorySeriesAxisRecord rec = new CategorySeriesAxisRecord();
rec.field_1_crossingPoint = field_1_crossingPoint;
rec.field_2_labelFrequency = field_2_labelFrequency;
rec.field_3_tickMarkFrequency = field_3_tickMarkFrequency;
rec.field_4_options = field_4_options;
return rec;
}
/**
* Get the crossing point field for the CategorySeriesAxis record.
*/
public short CrossingPoint
{
get
{
return field_1_crossingPoint;
}
set
{
this.field_1_crossingPoint = value;
}
}
/**
* Get the label frequency field for the CategorySeriesAxis record.
*/
public short LabelFrequency
{
get
{
return field_2_labelFrequency;
}
set
{
this.field_2_labelFrequency = value;
}
}
/**
* Get the tick mark frequency field for the CategorySeriesAxis record.
*/
public short TickMarkFrequency
{
get
{
return field_3_tickMarkFrequency;
}
set
{
this.field_3_tickMarkFrequency = value;
}
}
/**
* Get the options field for the CategorySeriesAxis record.
*/
public short Options
{
get
{
return field_4_options;
}
set
{
this.field_4_options = value;
}
}
/**
* Set true to indicate axis crosses between categories and false to cross axis midway
* @return the value axis crossing field value.
*/
public bool IsValueAxisCrossing
{
get
{
return valueAxisCrossing.IsSet(field_4_options);
}
set
{
field_4_options = valueAxisCrossing.SetShortBoolean(field_4_options, value);
}
}
/**
* axis crosses at the far right
* @return the crosses far right field value.
*/
public bool IsCrossesFarRight
{
get
{
return crossesFarRight.IsSet(field_4_options);
}
set
{
field_4_options = crossesFarRight.SetShortBoolean(field_4_options, value);
}
}
/**
* categories are displayed in reverse order
* @return the reversed field value.
*/
public bool IsReversed
{
get
{
return reversed.IsSet(field_4_options);
}
set
{
field_4_options = reversed.SetShortBoolean(field_4_options, value);
}
}
}
}
| |
// Copyright (c) 2013, Eberhard Beilharz
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using NUnit.Framework;
namespace TntMPDConverter
{
[TestFixture]
public class ReplacementManagerTests
{
[TestFixtureSetUp]
public void FixtureSetUp()
{
MyReplacementManager.Create();
}
[TestFixtureTearDown]
public void FixtureTearDown()
{
MyReplacementManager.Finish();
}
[Test]
public void ReplacementFile()
{
Assert.AreEqual(Path.Combine(Environment.CurrentDirectory, "replace.config"),
MyReplacementManager.OriginalReplacementFileName);
}
private void CreateComplexReplacementFile()
{
MyReplacementManager.CreateReplacementFile(@"
# Comment
[999]
Markus Mustermann=997; ""Mustermann, Markus""
F. Mueller=996; Mueller, Franz
Anton=995;Berta
[Replacements]
Umb. von Frieder Friederich=Friederich, Frieder
Berta=Caesar
[Regex]
Pattern=^Umb\..+Friederich$
Replace=Friederich, Frieder
[K715]
Include=^.+$
[K3224]
Exclude=Hugo");
}
[Test]
public void ReplacementInfo_General()
{
CreateComplexReplacementFile();
var info = MyReplacementManager.Instance.GetReplacementInfo();
Assert.AreEqual(3, info.Count);
Assert.IsTrue(info.ContainsKey(999));
Assert.IsTrue(info.ContainsKey(ReplacementManager.Replacements));
Assert.IsTrue(info.ContainsKey(ReplacementManager.RegexReplacements));
}
[Test]
public void ReplacementInfo_SpecificAccount()
{
CreateComplexReplacementFile();
var info = MyReplacementManager.Instance.GetReplacementInfo();
Assert.IsTrue(info.ContainsKey(999));
var value = info[999];
Assert.IsTrue(value.ContainsKey("Markus Mustermann"));
Assert.IsInstanceOf<ReplacementManager.NewDonor>(value["Markus Mustermann"]);
var newDonor = value["Markus Mustermann"] as ReplacementManager.NewDonor;
Assert.AreEqual(997, newDonor.DonorNo);
Assert.AreEqual("Mustermann, Markus", newDonor.Donor);
Assert.IsTrue(value.ContainsKey("F. Mueller"));
Assert.IsInstanceOf<ReplacementManager.NewDonor>(value["F. Mueller"]);
newDonor = value["F. Mueller"] as ReplacementManager.NewDonor;
Assert.AreEqual(996, newDonor.DonorNo);
Assert.AreEqual("Mueller, Franz", newDonor.Donor);
}
[Test]
public void ReplacementInfo_Replacements()
{
CreateComplexReplacementFile();
var info = MyReplacementManager.Instance.GetReplacementInfo();
Assert.IsTrue(info.ContainsKey(ReplacementManager.Replacements));
var value = info[ReplacementManager.Replacements];
Assert.IsTrue(value.ContainsKey("Berta"));
Assert.AreEqual("Caesar", value["Berta"].Donor);
}
[Test]
public void ReplacementInfo_Regex()
{
CreateComplexReplacementFile();
var info = MyReplacementManager.Instance.GetReplacementInfo();
Assert.IsTrue(info.ContainsKey(ReplacementManager.RegexReplacements));
var value = info[ReplacementManager.RegexReplacements];
Assert.AreEqual(1, value.Count);
Assert.IsTrue(value.ContainsKey("^Umb\\..+Friederich$"));
Assert.AreEqual("Friederich, Frieder", value["^Umb\\..+Friederich$"].Donor);
}
[Test]
public void ReplacementInfo_IncludeOtherProceeds()
{
// K715
CreateComplexReplacementFile();
var include = MyReplacementManager.Instance.GetIncludeInfo();
Assert.IsTrue(include.ContainsKey(715));
var includeList = include[715];
Assert.AreEqual(1, includeList.Count);
Assert.AreEqual("^.+$", includeList[0]);
}
[Test]
public void ReplacementInfo_ExcludeOtherTransfers()
{
// K3224
CreateComplexReplacementFile();
var exclude = MyReplacementManager.Instance.GetExcludeInfo();
Assert.IsTrue(exclude.ContainsKey(3224));
var excludeList = exclude[3224];
Assert.AreEqual(1, excludeList.Count);
Assert.AreEqual("Hugo", excludeList[0]);
}
[Test]
public void AccountSpecificReplacement()
{
MyReplacementManager.CreateReplacementFile(@"
# Comment
[999]
Markus Mustermann=997; ""Mustermann, Markus""
F. Mueller=996; Mueller, Franz
Anton=995;Berta");
var donation = new Donation(80, new DateTime(2010, 06, 01),
"ungen. ueberw. durch Markus Mustermann", 999);
MyReplacementManager.Instance.ApplyReplacements(donation);
AssertEx.DonationEqual(new Donation(80, new DateTime(2010, 06, 01), "Mustermann, Markus", 997),
donation);
}
[Test]
public void Replacements_AnonDonation()
{
MyReplacementManager.CreateReplacementFile(@"
# Comment
[999]
Markus Mustermann=997; ""Mustermann, Markus""
F. Mueller=996; Mueller, Franz
Anton=995;Berta
[Replacements]
Umb. von Frieder Friederich=Friederich, Frieder
Berta=Caesar");
var donation = new Donation(80, new DateTime(2010, 06, 01),
"ungen. ueberw. durch Anton", 999);
MyReplacementManager.Instance.ApplyReplacements(donation);
AssertEx.DonationEqual(new Donation(80, new DateTime(2010, 06, 01), "Caesar", 995),
donation);
}
[Test]
public void Regex_ReplaceEntireString()
{
MyReplacementManager.CreateReplacementFile(@"
[Regex]
Pattern=^Umb\..+Friederich$
Replace=Friederich, Frieder");
var donation = new Donation(0, DateTime.Now, "Umb. von Frieder Friederich", 0);
MyReplacementManager.Instance.ApplyReplacements(donation);
Assert.AreEqual("Friederich, Frieder", donation.Donor);
}
[Test]
public void Regex_UseSearchText()
{
MyReplacementManager.CreateReplacementFile(@"
[Regex]
Pattern=^.+(Frieder Friederich)$
Replace=$1");
var donation = new Donation(0, DateTime.Now, "Umb. von Frieder Friederich", 0);
MyReplacementManager.Instance.ApplyReplacements(donation);
Assert.AreEqual("Frieder Friederich", donation.Donor);
}
[Test]
public void Regex_ComplexPattern()
{
MyReplacementManager.CreateReplacementFile(@"
[Regex]
Pattern=^.+(F[^ ]+) (F[a-z]+)$
Replace=$2, $1");
var donation = new Donation(0, DateTime.Now, "Umb. von Frieder Friederich", 0);
MyReplacementManager.Instance.ApplyReplacements(donation);
Assert.AreEqual("Friederich, Frieder", donation.Donor);
}
[Test]
public void Regex_ReplacePartOfString()
{
MyReplacementManager.CreateReplacementFile(@"
[Regex]
Pattern=ie
Replace=ei");
var donation = new Donation(0, DateTime.Now, "Umb. von Frieder Friederich", 0);
MyReplacementManager.Instance.ApplyReplacements(donation);
Assert.AreEqual("Umb. von Freider Freiderich", donation.Donor);
}
[Test]
public void Regex_MultiplePatterns()
{
MyReplacementManager.CreateReplacementFile(@"
[Regex]
Pattern=ie
Replace=ei
Pattern=""Umb\. von ""
Replace=
Pattern=Frieder
Replace=Hugo
Pattern=r
Replace=x");
var donation = new Donation(0, DateTime.Now, "Umb. von Frieder Friederich", 0);
MyReplacementManager.Instance.ApplyReplacements(donation);
Assert.AreEqual("Fxeidex Fxeidexich", donation.Donor);
}
[Test]
public void K715_IncludeAll()
{
MyReplacementManager.CreateReplacementFile(@"
[K715]
Include=^.+$");
Assert.IsTrue(MyReplacementManager.Instance.IncludeEntry(
715, "Umb. von Frieder Friederich"));
}
[Test]
public void K715_IncludeSome()
{
MyReplacementManager.CreateReplacementFile(@"
[K715]
Include=Hugo");
Assert.IsFalse(MyReplacementManager.Instance.IncludeEntry(
715, "Umb. von Frieder Friederich"));
}
[Test]
public void K715_ExcludeAll()
{
MyReplacementManager.CreateReplacementFile("");
Assert.IsFalse(MyReplacementManager.Instance.IncludeEntry(
715, "Umb. von Frieder Friederich"));
}
[Test]
public void K3224_IncludeAll()
{
MyReplacementManager.CreateReplacementFile("");
Assert.IsFalse(MyReplacementManager.Instance.ExcludeEntry(
3224, "Umb. von Frieder Friederich"));
}
[Test]
public void K3224_IncludeSome()
{
MyReplacementManager.CreateReplacementFile(@"
[K3224]
Exclude=Hugo");
Assert.IsFalse(MyReplacementManager.Instance.ExcludeEntry(
3224, "Umb. von Frieder Friederich"));
}
[Test]
public void K3224_ExcludeAll()
{
MyReplacementManager.CreateReplacementFile(@"
[K3224]
Exclude=^.+$");
Assert.IsTrue(MyReplacementManager.Instance.ExcludeEntry(
3224, "Umb. von Frieder Friederich"));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Net.Http.Headers;
using System.Text;
namespace System.Net.Http
{
public class HttpResponseMessage : IDisposable
{
private const HttpStatusCode defaultStatusCode = HttpStatusCode.OK;
private HttpStatusCode _statusCode;
private HttpResponseHeaders _headers;
private string _reasonPhrase;
private HttpRequestMessage _requestMessage;
private Version _version;
private HttpContent _content;
private bool _disposed;
public Version Version
{
get { return _version; }
set
{
#if !PHONE
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
#endif
CheckDisposed();
_version = value;
}
}
internal void SetVersionWithoutValidation(Version value) => _version = value;
public HttpContent Content
{
get { return _content; }
set
{
CheckDisposed();
if (NetEventSource.IsEnabled)
{
if (value == null)
{
NetEventSource.ContentNull(this);
}
else
{
NetEventSource.Associate(this, value);
}
}
_content = value;
}
}
public HttpStatusCode StatusCode
{
get { return _statusCode; }
set
{
if (((int)value < 0) || ((int)value > 999))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposed();
_statusCode = value;
}
}
internal void SetStatusCodeWithoutValidation(HttpStatusCode value) => _statusCode = value;
public string ReasonPhrase
{
get
{
if (_reasonPhrase != null)
{
return _reasonPhrase;
}
// Provide a default if one was not set.
return HttpStatusDescription.Get(StatusCode);
}
set
{
if ((value != null) && ContainsNewLineCharacter(value))
{
throw new FormatException(SR.net_http_reasonphrase_format_error);
}
CheckDisposed();
_reasonPhrase = value; // It's OK to have a 'null' reason phrase.
}
}
internal void SetReasonPhraseWithoutValidation(string value) => _reasonPhrase = value;
public HttpResponseHeaders Headers
{
get
{
if (_headers == null)
{
_headers = new HttpResponseHeaders();
}
return _headers;
}
}
public HttpRequestMessage RequestMessage
{
get { return _requestMessage; }
set
{
CheckDisposed();
if (value != null) NetEventSource.Associate(this, value);
_requestMessage = value;
}
}
public bool IsSuccessStatusCode
{
get { return ((int)_statusCode >= 200) && ((int)_statusCode <= 299); }
}
public HttpResponseMessage()
: this(defaultStatusCode)
{
}
public HttpResponseMessage(HttpStatusCode statusCode)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, statusCode);
if (((int)statusCode < 0) || ((int)statusCode > 999))
{
throw new ArgumentOutOfRangeException(nameof(statusCode));
}
_statusCode = statusCode;
_version = HttpUtilities.DefaultResponseVersion;
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
public HttpResponseMessage EnsureSuccessStatusCode()
{
if (!IsSuccessStatusCode)
{
// Disposing the content should help users: If users call EnsureSuccessStatusCode(), an exception is
// thrown if the response status code is != 2xx. I.e. the behavior is similar to a failed request (e.g.
// connection failure). Users don't expect to dispose the content in this case: If an exception is
// thrown, the object is responsible fore cleaning up its state.
if (_content != null)
{
_content.Dispose();
}
throw new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_message_not_success_statuscode, (int)_statusCode,
ReasonPhrase));
}
return this;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("StatusCode: ");
sb.Append((int)_statusCode);
sb.Append(", ReasonPhrase: '");
sb.Append(ReasonPhrase ?? "<null>");
sb.Append("', Version: ");
sb.Append(_version);
sb.Append(", Content: ");
sb.Append(_content == null ? "<null>" : _content.GetType().ToString());
sb.Append(", Headers:\r\n");
sb.Append(HeaderUtilities.DumpHeaders(_headers, _content == null ? null : _content.Headers));
return sb.ToString();
}
private bool ContainsNewLineCharacter(string value)
{
foreach (char character in value)
{
if ((character == HttpRuleParser.CR) || (character == HttpRuleParser.LF))
{
return true;
}
}
return false;
}
#region IDisposable Members
protected virtual void Dispose(bool disposing)
{
// The reason for this type to implement IDisposable is that it contains instances of types that implement
// IDisposable (content).
if (disposing && !_disposed)
{
_disposed = true;
if (_content != null)
{
_content.Dispose();
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(this.GetType().ToString());
}
}
}
}
| |
//
// Copyright 2012-2013, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using Xamarin.Utilities;
using System.Net;
using System.Text;
namespace Xamarin.Auth
{
/// <summary>
/// Implements OAuth 2.0 implicit granting. http://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-4.2
/// </summary>
#if XAMARIN_AUTH_INTERNAL
internal class OAuth2Authenticator : WebRedirectAuthenticator
#else
public class OAuth2Authenticator : WebRedirectAuthenticator
#endif
{
string clientId;
string clientSecret;
string scope;
Uri authorizeUrl;
Uri redirectUrl;
Uri accessTokenUrl;
GetUsernameAsyncFunc getUsernameAsync;
string requestState;
bool reportedForgery = false;
/// <summary>
/// Initializes a new <see cref="Xamarin.Auth.OAuth2Authenticator"/>
/// that authenticates using implicit granting (token).
/// </summary>
/// <param name='clientId'>
/// Client identifier.
/// </param>
/// <param name='scope'>
/// Authorization scope.
/// </param>
/// <param name='authorizeUrl'>
/// Authorize URL.
/// </param>
/// <param name='redirectUrl'>
/// Redirect URL.
/// </param>
/// <param name='getUsernameAsync'>
/// Method used to fetch the username of an account
/// after it has been successfully authenticated.
/// </param>
public OAuth2Authenticator (string clientId, string scope, Uri authorizeUrl, Uri redirectUrl, GetUsernameAsyncFunc getUsernameAsync = null)
: this (redirectUrl)
{
if (string.IsNullOrEmpty (clientId)) {
throw new ArgumentException ("clientId must be provided", "clientId");
}
this.clientId = clientId;
this.scope = scope ?? "";
if (authorizeUrl == null) {
throw new ArgumentNullException ("authorizeUrl");
}
this.authorizeUrl = authorizeUrl;
if (redirectUrl == null) {
throw new ArgumentNullException ("redirectUrl");
}
this.redirectUrl = redirectUrl;
this.getUsernameAsync = getUsernameAsync;
this.accessTokenUrl = null;
}
/// <summary>
/// Initializes a new instance <see cref="Xamarin.Auth.OAuth2Authenticator"/>
/// that authenticates using authorization codes (code).
/// </summary>
/// <param name='clientId'>
/// Client identifier.
/// </param>
/// <param name='clientSecret'>
/// Client secret.
/// </param>
/// <param name='scope'>
/// Authorization scope.
/// </param>
/// <param name='authorizeUrl'>
/// Authorize URL.
/// </param>
/// <param name='redirectUrl'>
/// Redirect URL.
/// </param>
/// <param name='accessTokenUrl'>
/// URL used to request access tokens after an authorization code was received.
/// </param>
/// <param name='getUsernameAsync'>
/// Method used to fetch the username of an account
/// after it has been successfully authenticated.
/// </param>
public OAuth2Authenticator (string clientId, string clientSecret, string scope, Uri authorizeUrl, Uri redirectUrl, Uri accessTokenUrl, GetUsernameAsyncFunc getUsernameAsync = null)
: this (redirectUrl, clientSecret, accessTokenUrl)
{
if (string.IsNullOrEmpty (clientId)) {
throw new ArgumentException ("clientId must be provided", "clientId");
}
this.clientId = clientId;
if (string.IsNullOrEmpty (clientSecret)) {
throw new ArgumentException ("clientSecret must be provided", "clientSecret");
}
this.clientSecret = clientSecret;
this.scope = scope ?? "";
if (authorizeUrl == null) {
throw new ArgumentNullException ("authorizeUrl");
}
this.authorizeUrl = authorizeUrl;
if (redirectUrl == null) {
throw new ArgumentNullException ("redirectUrl");
}
this.redirectUrl = redirectUrl;
if (accessTokenUrl == null) {
throw new ArgumentNullException ("accessTokenUrl");
}
this.accessTokenUrl = accessTokenUrl;
this.getUsernameAsync = getUsernameAsync;
}
OAuth2Authenticator (Uri redirectUrl, string clientSecret = null, Uri accessTokenUrl = null)
: base (redirectUrl, redirectUrl)
{
if (redirectUrl == null) {
throw new ArgumentNullException ("redirectUrl");
}
this.redirectUrl = redirectUrl;
this.clientSecret = clientSecret;
this.accessTokenUrl = accessTokenUrl;
//
// Generate a unique state string to check for forgeries
//
var chars = new char[16];
var rand = new Random ();
for (var i = 0; i < chars.Length; i++) {
chars [i] = (char)rand.Next ((int)'a', (int)'z' + 1);
}
this.requestState = new string (chars);
}
bool IsImplicit { get { return accessTokenUrl == null; } }
/// <summary>
/// Method that returns the initial URL to be displayed in the web browser.
/// </summary>
/// <returns>
/// A task that will return the initial URL.
/// </returns>
public override Task<Uri> GetInitialUrlAsync ()
{
var url = new Uri (string.Format (
"{0}?client_id={1}&redirect_uri={2}&response_type={3}&scope={4}&state={5}",
authorizeUrl.AbsoluteUri,
Uri.EscapeDataString (clientId),
Uri.EscapeDataString (redirectUrl.AbsoluteUri),
IsImplicit ? "token" : "code",
Uri.EscapeDataString (scope),
Uri.EscapeDataString (requestState)));
var tcs = new TaskCompletionSource<Uri> ();
tcs.SetResult (url);
return tcs.Task;
}
/// <summary>
/// Raised when a new page has been loaded.
/// </summary>
/// <param name='url'>
/// URL of the page.
/// </param>
/// <param name='query'>
/// The parsed query of the URL.
/// </param>
/// <param name='fragment'>
/// The parsed fragment of the URL.
/// </param>
protected override void OnPageEncountered (Uri url, IDictionary<string, string> query, IDictionary<string, string> fragment)
{
var all = new Dictionary<string, string> (query);
foreach (var kv in fragment)
all [kv.Key] = kv.Value;
//
// Check for forgeries
//
if (all.ContainsKey ("state")) {
if (all ["state"] != requestState && !reportedForgery) {
reportedForgery = true;
OnError ("Invalid state from server. Possible forgery!");
return;
}
}
//
// Continue processing
//
base.OnPageEncountered (url, query, fragment);
}
/// <summary>
/// Raised when a new page has been loaded.
/// </summary>
/// <param name='url'>
/// URL of the page.
/// </param>
/// <param name='query'>
/// The parsed query string of the URL.
/// </param>
/// <param name='fragment'>
/// The parsed fragment of the URL.
/// </param>
protected override void OnRedirectPageLoaded (Uri url, IDictionary<string, string> query, IDictionary<string, string> fragment)
{
//
// Look for the access_token
//
if (fragment.ContainsKey ("access_token")) {
//
// We found an access_token
//
OnRetrievedAccountProperties (fragment);
} else if (!IsImplicit) {
//
// Look for the code
//
if (query.ContainsKey ("code")) {
var code = query ["code"];
RequestAccessTokenAsync (code).ContinueWith (task => {
if (task.IsFaulted) {
OnError (task.Exception);
} else {
OnRetrievedAccountProperties (task.Result);
}
}, TaskScheduler.FromCurrentSynchronizationContext ());
} else {
OnError ("Expected code in response, but did not receive one.");
return;
}
} else {
OnError ("Expected access_token in response, but did not receive one.");
return;
}
}
/// <summary>
/// Asynchronously requests an access token with an authorization <paramref name="code"/>.
/// </summary>
/// <returns>
/// A dictionary of data returned from the authorization request.
/// </returns>
/// <param name='code'>The authorization code.</param>
/// <remarks>Implements: http://tools.ietf.org/html/rfc6749#section-4.1</remarks>
Task<IDictionary<string,string>> RequestAccessTokenAsync (string code)
{
var queryValues = new Dictionary<string, string> {
{ "grant_type", "authorization_code" },
{ "code", code },
{ "redirect_uri", redirectUrl.AbsoluteUri },
{ "client_id", clientId },
};
if (!string.IsNullOrEmpty (clientSecret)) {
queryValues ["client_secret"] = clientSecret;
}
return RequestAccessTokenAsync (queryValues);
}
/// <summary>
/// Asynchronously makes a request to the access token URL with the given parameters.
/// </summary>
/// <param name="queryValues">The parameters to make the request with.</param>
/// <returns>The data provided in the response to the access token request.</returns>
protected async Task<IDictionary<string,string>> RequestAccessTokenAsync (IDictionary<string, string> queryValues)
{
var content = new FormUrlEncodedContent (queryValues);
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsync (accessTokenUrl, content).ConfigureAwait (false);
string text = await response.Content.ReadAsStringAsync().ConfigureAwait (false);
// Parse the response
var data = text.Contains ("{") ? WebEx.JsonDecode (text) : WebEx.FormDecode (text);
if (data.ContainsKey ("error")) {
throw new AuthException ("Error authenticating: " + data ["error"]);
} else if (data.ContainsKey ("access_token")) {
return data;
} else {
throw new AuthException ("Expected access_token in access token response, but did not receive one.");
}
}
/// <summary>
/// Event handler that is fired when an access token has been retreived.
/// </summary>
/// <param name='accountProperties'>
/// The retrieved account properties
/// </param>
protected virtual void OnRetrievedAccountProperties (IDictionary<string, string> accountProperties)
{
//
// Now we just need a username for the account
//
if (getUsernameAsync != null) {
getUsernameAsync (accountProperties).ContinueWith (task => {
if (task.IsFaulted) {
OnError (task.Exception);
} else {
OnSucceeded (task.Result, accountProperties);
}
}, TaskScheduler.FromCurrentSynchronizationContext ());
} else {
OnSucceeded ("", accountProperties);
}
}
public HttpWebClientFrameworkType HttpWebClientUsed
{
get;
set;
}
}
}
| |
/*
* 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 System;
using Lucene.Net.Support;
using NUnit.Framework;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
namespace Lucene.Net.Util
{
/// <version> $Id$
/// </version>
[TestFixture]
public class TestOpenBitSet:LuceneTestCase
{
internal System.Random rand;
internal virtual void DoGet(System.Collections.BitArray a, OpenBitSet b)
{
int max = a.Count;
for (int i = 0; i < max; i++)
{
Assert.AreEqual(a.Get(i) != b.Get(i), "mismatch: BitSet=[" + i + "]=" + a.Get(i));
}
}
internal virtual void DoNextSetBit(System.Collections.BitArray a, OpenBitSet b)
{
int aa = - 1, bb = - 1;
do
{
aa = BitSetSupport.NextSetBit(a, aa + 1);
bb = b.NextSetBit(bb + 1);
Assert.AreEqual(aa, bb);
}
while (aa >= 0);
}
// test interleaving different OpenBitSetIterator.next()/skipTo()
internal virtual void DoIterate(System.Collections.BitArray a, OpenBitSet b, int mode)
{
if (mode == 1)
DoIterate1(a, b);
if (mode == 2)
DoIterate2(a, b);
}
internal virtual void DoIterate1(System.Collections.BitArray a, OpenBitSet b)
{
int aa = - 1, bb = - 1;
OpenBitSetIterator iterator = new OpenBitSetIterator(b);
do
{
aa = BitSetSupport.NextSetBit(a, aa + 1);
bb = rand.NextDouble() > 0.5 ? iterator.NextDoc() : iterator.Advance(bb + 1);
Assert.AreEqual(aa == - 1?DocIdSetIterator.NO_MORE_DOCS:aa, bb);
}
while (aa >= 0);
}
internal virtual void DoIterate2(System.Collections.BitArray a, OpenBitSet b)
{
int aa = - 1, bb = - 1;
OpenBitSetIterator iterator = new OpenBitSetIterator(b);
do
{
aa = BitSetSupport.NextSetBit(a, aa + 1);
bb = rand.NextDouble() > 0.5 ? iterator.NextDoc() : iterator.Advance(bb + 1);
Assert.AreEqual(aa == - 1?DocIdSetIterator.NO_MORE_DOCS:aa, bb);
}
while (aa >= 0);
}
internal virtual void DoRandomSets(int maxSize, int iter, int mode)
{
System.Collections.BitArray a0 = null;
OpenBitSet b0 = null;
for (int i = 0; i < iter; i++)
{
int sz = rand.Next(maxSize);
System.Collections.BitArray a = new System.Collections.BitArray(sz);
OpenBitSet b = new OpenBitSet(sz);
// test the various ways of setting bits
if (sz > 0)
{
int nOper = rand.Next(sz);
for (int j = 0; j < nOper; j++)
{
int idx;
idx = rand.Next(sz);
a.Set(idx, true);
b.FastSet(idx);
idx = rand.Next(sz);
a.Set(idx, false);
b.FastClear(idx);
idx = rand.Next(sz);
a.Set(idx, !a.Get(idx));
b.FastFlip(idx);
bool val = b.FlipAndGet(idx);
bool val2 = b.FlipAndGet(idx);
Assert.IsTrue(val != val2);
val = b.GetAndSet(idx);
Assert.IsTrue(val2 == val);
Assert.IsTrue(b.Get(idx));
if (!val)
b.FastClear(idx);
Assert.IsTrue(b.Get(idx) == val);
}
}
// test that the various ways of accessing the bits are equivalent
DoGet(a, b);
// {{dougsale-2.4.0}}
//
// Java's java.util.BitSet automatically grows as needed - i.e., when a bit is referenced beyond
// the size of the BitSet, an exception isn't thrown - rather, the set grows to the size of the
// referenced bit.
//
// System.Collections.BitArray does not have this feature, and thus I've faked it here by
// "growing" the array explicitly when necessary (creating a new instance of the appropriate size
// and setting the appropriate bits).
//
// test ranges, including possible extension
int fromIndex, toIndex;
fromIndex = rand.Next(sz + 80);
toIndex = fromIndex + rand.Next((sz >> 1) + 1);
// {{dougsale-2.4.0}}:
// The following commented-out, compound statement's 'for loop' implicitly grows the Java BitSets 'a'
// and 'aa' to the same cardinality as 'j+1' when 'a.Count < j+1' and 'fromIndex < toIndex':
//BitArray aa = (BitArray)a.Clone(); for (int j = fromIndex; j < toIndex; j++) aa.Set(j, !a.Get(j));
// So, if necessary, lets explicitly grow 'a' now; then 'a' and its clone, 'aa', will be of the required size.
if (a.Count < toIndex && fromIndex < toIndex)
{
System.Collections.BitArray tmp = new System.Collections.BitArray(toIndex, false);
for (int k = 0; k < a.Count; k++)
tmp.Set(k, a.Get(k));
a = tmp;
}
// {{dougsale-2.4.0}}: now we can invoke this statement without going 'out-of-bounds'
System.Collections.BitArray aa = (System.Collections.BitArray)a.Clone(); for (int j = fromIndex; j < toIndex; j++) aa.Set(j, !a.Get(j));
OpenBitSet bb = (OpenBitSet)b.Clone(); bb.Flip(fromIndex, toIndex);
DoIterate(aa, bb, mode); // a problem here is from flip or doIterate
fromIndex = rand.Next(sz + 80);
toIndex = fromIndex + rand.Next((sz >> 1) + 1);
// {{dougsale-2.4.0}}:
// The following commented-out, compound statement's 'for loop' implicitly grows the Java BitSet 'aa'
// when 'a.Count < j+1' and 'fromIndex < toIndex'
//aa = (BitArray)a.Clone(); for (int j = fromIndex; j < toIndex; j++) aa.Set(j, false);
// So, if necessary, lets explicitly grow 'aa' now
if (a.Count < toIndex && fromIndex < toIndex)
{
aa = new System.Collections.BitArray(toIndex);
for (int k = 0; k < a.Count; k++)
aa.Set(k, a.Get(k));
}
else
{
aa = (System.Collections.BitArray)a.Clone();
}
for (int j = fromIndex; j < toIndex; j++) aa.Set(j, false);
bb = (OpenBitSet)b.Clone(); bb.Clear(fromIndex, toIndex);
DoNextSetBit(aa, bb); // a problem here is from clear() or nextSetBit
fromIndex = rand.Next(sz + 80);
toIndex = fromIndex + rand.Next((sz >> 1) + 1);
// {{dougsale-2.4.0}}:
// The following commented-out, compound statement's 'for loop' implicitly grows the Java BitSet 'aa'
// when 'a.Count < j+1' and 'fromIndex < toIndex'
//aa = (BitArray)a.Clone(); for (int j = fromIndex; j < toIndex; j++) aa.Set(j, false);
// So, if necessary, lets explicitly grow 'aa' now
if (a.Count < toIndex && fromIndex < toIndex)
{
aa = new System.Collections.BitArray(toIndex);
for (int k = 0; k < a.Count; k++)
aa.Set(k, a.Get(k));
}
else
{
aa = (System.Collections.BitArray)a.Clone();
}
for (int j = fromIndex; j < toIndex; j++) aa.Set(j, true);
bb = (OpenBitSet)b.Clone(); bb.Set(fromIndex, toIndex);
DoNextSetBit(aa, bb); // a problem here is from set() or nextSetBit
if (a0 != null)
{
Assert.AreEqual(a.Equals(a0), b.Equals(b0));
Assert.AreEqual(BitSetSupport.Cardinality(a), b.Cardinality());
// {{dougsale-2.4.0}}
//
// The Java code used java.util.BitSet, which grows as needed.
// When a bit, outside the dimension of the set is referenced,
// the set automatically grows to the necessary size. The
// new entries default to false.
//
// BitArray does not grow automatically and is not growable.
// Thus when BitArray instances of mismatched cardinality
// interact, we must first explicitly "grow" the smaller one.
//
// This growth is acheived by creating a new instance of the
// required size and copying the appropriate values.
//
//BitArray a_and = (BitArray)a.Clone(); a_and.And(a0);
//BitArray a_or = (BitArray)a.Clone(); a_or.Or(a0);
//BitArray a_xor = (BitArray)a.Clone(); a_xor.Xor(a0);
//BitArray a_andn = (BitArray)a.Clone(); for (int j = 0; j < a_andn.Count; j++) if (a0.Get(j)) a_andn.Set(j, false);
System.Collections.BitArray a_and;
System.Collections.BitArray a_or;
System.Collections.BitArray a_xor;
System.Collections.BitArray a_andn;
if (a.Count < a0.Count)
{
// the Java code would have implicitly resized 'a_and', 'a_or', 'a_xor', and 'a_andn'
// in this case, so we explicitly create a resized stand-in for 'a' here, allowing for
// a to keep its original size while 'a_and', 'a_or', 'a_xor', and 'a_andn' are resized
System.Collections.BitArray tmp = new System.Collections.BitArray(a0.Count, false);
for (int z = 0; z < a.Count; z++)
tmp.Set(z, a.Get(z));
a_and = (System.Collections.BitArray)tmp.Clone(); a_and.And(a0);
a_or = (System.Collections.BitArray)tmp.Clone(); a_or.Or(a0);
a_xor = (System.Collections.BitArray)tmp.Clone(); a_xor.Xor(a0);
a_andn = (System.Collections.BitArray)tmp.Clone(); for (int j = 0; j < a_andn.Count; j++) if (a0.Get(j)) a_andn.Set(j, false);
}
else if (a.Count > a0.Count)
{
// the Java code would have implicitly resized 'a0' in this case, so
// we explicitly do so here:
System.Collections.BitArray tmp = new System.Collections.BitArray(a.Count, false);
for (int z = 0; z < a0.Count; z++)
tmp.Set(z, a0.Get(z));
a0 = tmp;
a_and = (System.Collections.BitArray)a.Clone(); a_and.And(a0);
a_or = (System.Collections.BitArray)a.Clone(); a_or.Or(a0);
a_xor = (System.Collections.BitArray)a.Clone(); a_xor.Xor(a0);
a_andn = (System.Collections.BitArray)a.Clone(); for (int j = 0; j < a_andn.Count; j++) if (a0.Get(j)) a_andn.Set(j, false);
}
else
{
// 'a' and 'a0' are the same size, no explicit growing necessary
a_and = (System.Collections.BitArray)a.Clone(); a_and.And(a0);
a_or = (System.Collections.BitArray)a.Clone(); a_or.Or(a0);
a_xor = (System.Collections.BitArray)a.Clone(); a_xor.Xor(a0);
a_andn = (System.Collections.BitArray)a.Clone(); for (int j = 0; j < a_andn.Count; j++) if (a0.Get(j)) a_andn.Set(j, false);
}
OpenBitSet b_and = (OpenBitSet)b.Clone(); Assert.AreEqual(b, b_and); b_and.And(b0);
OpenBitSet b_or = (OpenBitSet)b.Clone(); b_or.Or(b0);
OpenBitSet b_xor = (OpenBitSet)b.Clone(); b_xor.Xor(b0);
OpenBitSet b_andn = (OpenBitSet)b.Clone(); b_andn.AndNot(b0);
DoIterate(a_and, b_and, mode);
DoIterate(a_or, b_or, mode);
DoIterate(a_xor, b_xor, mode);
DoIterate(a_andn, b_andn, mode);
Assert.AreEqual(BitSetSupport.Cardinality(a_and), b_and.Cardinality());
Assert.AreEqual(BitSetSupport.Cardinality(a_or), b_or.Cardinality());
Assert.AreEqual(BitSetSupport.Cardinality(a_xor), b_xor.Cardinality());
Assert.AreEqual(BitSetSupport.Cardinality(a_andn), b_andn.Cardinality());
// test non-mutating popcounts
Assert.AreEqual(b_and.Cardinality(), OpenBitSet.IntersectionCount(b, b0));
Assert.AreEqual(b_or.Cardinality(), OpenBitSet.UnionCount(b, b0));
Assert.AreEqual(b_xor.Cardinality(), OpenBitSet.XorCount(b, b0));
Assert.AreEqual(b_andn.Cardinality(), OpenBitSet.AndNotCount(b, b0));
}
a0 = a;
b0 = b;
}
}
// large enough to flush obvious bugs, small enough to run in <.5 sec as part of a
// larger testsuite.
[Test]
public virtual void TestSmall()
{
// TODO: fix for 64 bit tests.
if (IntPtr.Size == 4)
{
rand = NewRandom();
DoRandomSets(1200, 1000, 1);
DoRandomSets(1200, 1000, 2);
}
}
[Test]
public virtual void TestBig()
{
// uncomment to run a bigger test (~2 minutes).
// rand = newRandom();
// doRandomSets(2000,200000, 1);
// doRandomSets(2000,200000, 2);
}
[Test]
public virtual void TestEquals()
{
rand = NewRandom();
OpenBitSet b1 = new OpenBitSet(1111);
OpenBitSet b2 = new OpenBitSet(2222);
Assert.IsTrue(b1.Equals(b2));
Assert.IsTrue(b2.Equals(b1));
b1.Set(10);
Assert.IsFalse(b1.Equals(b2));
Assert.IsFalse(b2.Equals(b1));
b2.Set(10);
Assert.IsTrue(b1.Equals(b2));
Assert.IsTrue(b2.Equals(b1));
b2.Set(2221);
Assert.IsFalse(b1.Equals(b2));
Assert.IsFalse(b2.Equals(b1));
b1.Set(2221);
Assert.IsTrue(b1.Equals(b2));
Assert.IsTrue(b2.Equals(b1));
// try different type of object
Assert.IsFalse(b1.Equals(new System.Object()));
}
[Test]
public virtual void TestBitUtils()
{
rand = NewRandom();
long num = 100000;
Assert.AreEqual(5, BitUtil.Ntz(num));
Assert.AreEqual(5, BitUtil.Ntz2(num));
Assert.AreEqual(5, BitUtil.Ntz3(num));
num = 10;
Assert.AreEqual(1, BitUtil.Ntz(num));
Assert.AreEqual(1, BitUtil.Ntz2(num));
Assert.AreEqual(1, BitUtil.Ntz3(num));
for (int i = 0; i < 64; i++)
{
num = 1L << i;
Assert.AreEqual(i, BitUtil.Ntz(num));
Assert.AreEqual(i, BitUtil.Ntz2(num));
Assert.AreEqual(i, BitUtil.Ntz3(num));
}
}
[Test]
public void TestHashCodeEquals()
{
OpenBitSet bs1 = new OpenBitSet(200);
OpenBitSet bs2 = new OpenBitSet(64);
bs1.Set(3);
bs2.Set(3);
Assert.AreEqual(bs1, bs2);
Assert.AreEqual(bs1.GetHashCode(), bs2.GetHashCode());
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Diagnostics;
using System.IO;
using Gallio;
using Gallio.Common;
using Gallio.Common.Policies;
namespace Gallio.Runtime.ConsoleSupport
{
/// <summary>
/// An implementation of <see cref="IRichConsole" /> that targets the
/// native <see cref="Console" />.
/// </summary>
/// <remarks>
/// <para>
/// This implementation offers protection against redirection of the <see cref="Console.Out" />
/// and <see cref="Console.Error" /> streams. This object will continue to refer to the
/// standard output and error streams even if they are redirected after its initialization.
/// </para>
/// </remarks>
public sealed class NativeConsole : IRichConsole
{
/// <summary>
/// The application will forcibly terminate if the cancel key is pressed
/// <see cref="ForceQuitKeyPressRepetitions" /> times within no more than
/// <see cref="ForceQuitKeyPressTimeoutMilliseconds"/> milliseconds.
/// </summary>
public const int ForceQuitKeyPressRepetitions = 3;
/// <summary>
/// The application will forcibly terminate if the cancel key is pressed
/// <see cref="ForceQuitKeyPressRepetitions" /> times within no more than
/// <see cref="ForceQuitKeyPressTimeoutMilliseconds"/> milliseconds.
/// </summary>
public const int ForceQuitKeyPressTimeoutMilliseconds = 1000;
private static readonly NativeConsole instance = new NativeConsole();
private readonly TextWriter standardOutput;
private readonly TextWriter standardError;
private readonly object syncRoot = new object();
private bool isCancelationEnabled;
private bool isCanceled;
private event EventHandler cancelHandlers;
private Stopwatch repeatStart;
private int repeatCount;
private bool footerVisible = true;
private Action showFooter;
private Action hideFooter;
private int redirectedFlag;
private NativeConsole()
{
// FIXME: Assuming that the NativeConsole gets created before any output redirection occurs.
// If redirection has occurred, then we would need to use Console.OpenStandardOutput
// and Console.OpenStandardError to recover the original streams. However, this is
// not an issue at this time.
standardOutput = Console.Out;
standardError = Console.Error;
}
/// <summary>
/// Gets the singleton instance of the native console.
/// </summary>
public static NativeConsole Instance
{
get { return instance; }
}
/// <inheritdoc />
public bool IsCancelationEnabled
{
get { return isCancelationEnabled; }
set
{
lock (syncRoot)
{
if (IsRedirected || isCancelationEnabled == value)
return;
if (value)
{
Console.TreatControlCAsInput = false;
Console.CancelKeyPress += HandleCancelKeyPress;
isCancelationEnabled = true;
}
else
{
Console.CancelKeyPress -= HandleCancelKeyPress;
isCancelationEnabled = false;
}
}
}
}
/// <inheritdoc />
public object SyncRoot
{
get { return syncRoot; }
}
/// <inheritdoc />
public event EventHandler Cancel
{
add
{
lock (syncRoot)
{
cancelHandlers += value;
if (!isCanceled)
return;
}
value(null, EventArgs.Empty);
}
remove
{
lock (syncRoot)
{
cancelHandlers -= value;
}
}
}
/// <inheritdoc />
public bool IsCanceled
{
get
{
lock (syncRoot)
return isCanceled;
}
set
{
EventHandler currentCancelHandlers;
lock (syncRoot)
{
if (isCanceled == value)
return;
isCanceled = value;
if (!isCanceled)
return;
currentCancelHandlers = cancelHandlers;
}
EventHandlerPolicy.SafeInvoke(currentCancelHandlers, null, EventArgs.Empty);
}
}
/// <inheritdoc />
public bool IsRedirected
{
get
{
if (redirectedFlag == 0)
{
try
{
// Mono responds with a zero buffer with.
if (Console.BufferWidth <= 0)
{
redirectedFlag = 1;
}
else
{
redirectedFlag = -1;
}
// .Net will throw an IOException here.
GC.KeepAlive(Console.CursorVisible);
}
catch (IOException)
{
redirectedFlag = 1;
}
}
return redirectedFlag > 0;
}
}
/// <inheritdoc />
public TextWriter Error
{
get { return standardError; }
}
/// <inheritdoc />
public TextWriter Out
{
get { return standardOutput; }
}
/// <inheritdoc />
public ConsoleColor ForegroundColor
{
get { return Console.ForegroundColor; }
set { Console.ForegroundColor = value; }
}
/// <inheritdoc />
public int CursorLeft
{
get { return Console.CursorLeft; }
set { Console.CursorLeft = value; }
}
/// <inheritdoc />
public int CursorTop
{
get { return Console.CursorTop; }
set { Console.CursorTop = value; }
}
/// <inheritdoc />
public string Title
{
get { return Console.Title; }
set { Console.Title = value; }
}
/// <inheritdoc />
public int Width
{
get
{
return IsRedirected ? 80 : Console.BufferWidth;
}
}
/// <inheritdoc />
public bool FooterVisible
{
get { return footerVisible; }
set
{
lock (syncRoot)
{
if (footerVisible == value)
return;
footerVisible = value;
if (footerVisible)
{
if (showFooter != null)
showFooter();
}
else
{
if (hideFooter != null)
hideFooter();
}
}
}
}
/// <inheritdoc />
public void ResetColor()
{
Console.ResetColor();
}
/// <inheritdoc />
public void SetFooter(Action showFooter, Action hideFooter)
{
lock (syncRoot)
{
if (footerVisible && this.hideFooter != null)
this.hideFooter();
this.showFooter = showFooter;
this.hideFooter = hideFooter;
if (footerVisible && showFooter != null)
showFooter();
}
}
/// <inheritdoc />
public void Write(char c)
{
standardOutput.Write(c);
}
/// <inheritdoc />
public void Write(string str)
{
standardOutput.Write(str);
}
/// <inheritdoc />
public void WriteLine()
{
standardOutput.WriteLine();
}
/// <inheritdoc />
public void WriteLine(string str)
{
standardOutput.WriteLine(str);
}
private void HandleCancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
if (repeatCount != 0)
{
if (repeatStart.ElapsedMilliseconds > ForceQuitKeyPressTimeoutMilliseconds)
repeatCount = 0;
}
if (repeatCount == 0)
repeatStart = Stopwatch.StartNew();
repeatCount += 1;
if (repeatCount < ForceQuitKeyPressRepetitions)
e.Cancel = true;
IsCanceled = true;
}
}
}
| |
/*
* Copyright (C) 2003 Bruno Fernandez-Ruiz <brunofr@olympum.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.
*/
namespace Caffeine.Jni
{
using System;
using System.Runtime.InteropServices;
public class JField : JObject, IMember
{
JClass declaringClass;
string name;
bool isStatic;
internal JField (JClass declaringClass,
string name,
string sig,
bool isStatic,
IntPtr methodID)
: base (methodID)
{
this.declaringClass = declaringClass;
this.name = name;
this.isStatic = isStatic;
}
public JClass DeclaringClass {
get {
return declaringClass;
}
}
public string Name {
get {
return name;
}
}
[DllImport(JNIEnv.DLL_JAVA)]
static extern IntPtr GetStaticObjectField (IntPtr clazz, IntPtr fieldID);
[DllImport(JNIEnv.DLL_JAVA)]
static extern IntPtr GetObjectField (IntPtr obj, IntPtr fieldID);
public JObject GetObject (JObject obj)
{
IntPtr raw;
if (isStatic) {
raw = GetStaticObjectField (
DeclaringClass.Handle,
Handle);
} else {
if (obj == null) {
throw new NullReferenceException (Name);
} else {
raw = GetObjectField (obj.Handle, Handle);
}
}
return new JObject (raw);
}
[DllImport(JNIEnv.DLL_JAVA)]
static extern void SetStaticObjectField (IntPtr clazz, IntPtr fieldID, IntPtr value);
[DllImport(JNIEnv.DLL_JAVA)]
static extern void SetObjectField (IntPtr obj, IntPtr fieldID, IntPtr val);
public void SetObject (JObject obj, JObject value)
{
if (isStatic) {
SetStaticObjectField (
DeclaringClass.Handle,
Handle,
value.Handle);
} else {
if (obj == null) {
throw new NullReferenceException (Name);
} else {
SetObjectField (
obj.Handle,
Handle,
value.Handle);
}
}
JThrowable.CheckAndThrow ();
}
[DllImport(JNIEnv.DLL_JAVA)]
static extern bool GetStaticBooleanField (IntPtr clazz, IntPtr fieldID);
[DllImport(JNIEnv.DLL_JAVA)]
static extern bool GetBooleanField (IntPtr obj, IntPtr fieldID);
public bool GetBool (JObject obj)
{
bool r;
if (isStatic) {
r = GetStaticBooleanField (
DeclaringClass.Handle,
Handle);
} else {
if (obj == null) {
throw new NullReferenceException (Name);
} else {
r = GetBooleanField (obj.Handle, Handle);
}
}
JThrowable.CheckAndThrow ();
return r;
}
[DllImport(JNIEnv.DLL_JAVA)]
static extern void SetStaticBooleanField (IntPtr clazz, IntPtr fieldID, bool value);
[DllImport(JNIEnv.DLL_JAVA)]
static extern void SetBooleanField (IntPtr obj, IntPtr fieldID, bool val);
public void SetBool (JObject obj, bool value)
{
if (isStatic) {
SetStaticBooleanField (
DeclaringClass.Handle,
Handle,
value);
} else {
if (obj == null) {
throw new NullReferenceException (Name);
} else {
SetBooleanField (
obj.Handle,
Handle,
value);
}
}
JThrowable.CheckAndThrow ();
}
[DllImport(JNIEnv.DLL_JAVA)]
static extern byte GetStaticByteField (IntPtr clazz, IntPtr fieldID);
[DllImport(JNIEnv.DLL_JAVA)]
static extern byte GetByteField (IntPtr obj, IntPtr fieldID);
public byte GetByte (JObject obj)
{
byte r;
if (isStatic) {
r = GetStaticByteField (
DeclaringClass.Handle,
Handle);
} else {
if (obj == null) {
throw new NullReferenceException (Name);
} else {
r = GetByteField (obj.Handle, Handle);
}
}
JThrowable.CheckAndThrow ();
return r;
}
[DllImport(JNIEnv.DLL_JAVA)]
static extern void SetStaticByteField (IntPtr clazz, IntPtr fieldID, byte value);
[DllImport(JNIEnv.DLL_JAVA)]
static extern void SetByteField (IntPtr obj, IntPtr fieldID, byte val);
public void SetByte (JObject obj, byte value)
{
if (isStatic) {
SetStaticByteField (
DeclaringClass.Handle,
Handle,
value);
} else {
if (obj == null) {
throw new NullReferenceException (Name);
} else {
SetByteField (
obj.Handle,
Handle,
value);
}
}
JThrowable.CheckAndThrow ();
}
[DllImport(JNIEnv.DLL_JAVA)]
static extern ushort GetStaticCharField (IntPtr clazz, IntPtr fieldID);
[DllImport(JNIEnv.DLL_JAVA)]
static extern ushort GetCharField (IntPtr obj, IntPtr fieldID);
public char GetChar (JObject obj)
{
ushort r;
if (isStatic) {
r = GetStaticCharField (
DeclaringClass.Handle,
Handle);
} else {
if (obj == null) {
throw new NullReferenceException (Name);
} else {
r = GetCharField (obj.Handle, Handle);
}
}
JThrowable.CheckAndThrow ();
return (char) r;
}
[DllImport(JNIEnv.DLL_JAVA)]
static extern void SetStaticCharField (IntPtr clazz, IntPtr fieldID, char value);
[DllImport(JNIEnv.DLL_JAVA)]
static extern void SetCharField (IntPtr obj, IntPtr fieldID, char val);
public void SetChar (JObject obj, char value)
{
if (isStatic) {
SetStaticCharField (
DeclaringClass.Handle,
Handle,
value);
} else {
if (obj == null) {
throw new NullReferenceException (Name);
} else {
SetCharField (
obj.Handle,
Handle,
value);
}
}
JThrowable.CheckAndThrow ();
}
[DllImport(JNIEnv.DLL_JAVA)]
static extern short GetStaticShortField (IntPtr clazz, IntPtr fieldID);
[DllImport(JNIEnv.DLL_JAVA)]
static extern short GetShortField (IntPtr obj, IntPtr fieldID);
public short GetShort (JObject obj)
{
short r;
if (isStatic) {
r = GetStaticShortField (
DeclaringClass.Handle,
Handle);
} else {
if (obj == null) {
throw new NullReferenceException (Name);
} else {
r = GetShortField (obj.Handle, Handle);
}
}
JThrowable.CheckAndThrow ();
return r;
}
[DllImport(JNIEnv.DLL_JAVA)]
static extern void SetStaticShortField (IntPtr clazz, IntPtr fieldID, short value);
[DllImport(JNIEnv.DLL_JAVA)]
static extern void SetShortField (IntPtr obj, IntPtr fieldID, short val);
public void SetShort (JObject obj, short value)
{
if (isStatic) {
SetStaticShortField (
DeclaringClass.Handle,
Handle,
value);
} else {
if (obj == null) {
throw new NullReferenceException (Name);
} else {
SetShortField (
obj.Handle,
Handle,
value);
}
}
JThrowable.CheckAndThrow ();
}
[DllImport(JNIEnv.DLL_JAVA)]
static extern int GetStaticIntField (IntPtr clazz, IntPtr fieldID);
[DllImport(JNIEnv.DLL_JAVA)]
static extern int GetIntField (IntPtr obj, IntPtr fieldID);
public int GetInt (JObject obj)
{
int r;
if (isStatic) {
r = GetStaticIntField (
DeclaringClass.Handle,
Handle);
} else {
if (obj == null) {
throw new NullReferenceException (Name);
} else {
r = GetIntField (obj.Handle, Handle);
}
}
JThrowable.CheckAndThrow ();
return r;
}
[DllImport(JNIEnv.DLL_JAVA)]
static extern void SetStaticIntField (IntPtr clazz, IntPtr fieldID, int value);
[DllImport(JNIEnv.DLL_JAVA)]
static extern void SetIntField (IntPtr obj, IntPtr fieldID, int val);
public void SetInt (JObject obj, int value)
{
if (isStatic) {
SetStaticIntField (
DeclaringClass.Handle,
Handle,
value);
} else {
if (obj == null) {
throw new NullReferenceException (Name);
} else {
SetIntField (
obj.Handle,
Handle,
value);
}
}
JThrowable.CheckAndThrow ();
}
[DllImport(JNIEnv.DLL_JAVA)]
static extern long GetStaticLongField (IntPtr clazz, IntPtr fieldID);
[DllImport(JNIEnv.DLL_JAVA)]
static extern long GetLongField (IntPtr obj, IntPtr fieldID);
public long GetLong (JObject obj)
{
long r;
if (isStatic) {
r = GetStaticLongField (
DeclaringClass.Handle,
Handle);
} else {
if (obj == null) {
throw new NullReferenceException (Name);
} else {
r = GetLongField (obj.Handle, Handle);
}
}
JThrowable.CheckAndThrow ();
return r;
}
[DllImport(JNIEnv.DLL_JAVA)]
static extern void SetStaticLongField (IntPtr clazz, IntPtr fieldID, long value);
[DllImport(JNIEnv.DLL_JAVA)]
static extern void SetLongField (IntPtr obj, IntPtr fieldID, long val);
public void SetLong (JObject obj, long value)
{
if (isStatic) {
SetStaticLongField (
DeclaringClass.Handle,
Handle,
value);
} else {
if (obj == null) {
throw new NullReferenceException (Name);
} else {
SetLongField (
obj.Handle,
Handle,
value);
}
}
JThrowable.CheckAndThrow ();
}
[DllImport(JNIEnv.DLL_JAVA)]
static extern float GetStaticFloatField (IntPtr clazz, IntPtr fieldID);
[DllImport(JNIEnv.DLL_JAVA)]
static extern float GetFloatField (IntPtr obj, IntPtr fieldID);
public float GetFloat (JObject obj)
{
float r;
if (isStatic) {
r = GetStaticFloatField (
DeclaringClass.Handle,
Handle);
} else {
if (obj == null) {
throw new NullReferenceException (Name);
} else {
r = GetFloatField (obj.Handle, Handle);
}
}
JThrowable.CheckAndThrow ();
return r;
}
[DllImport(JNIEnv.DLL_JAVA)]
static extern void SetStaticFloatField (IntPtr clazz, IntPtr fieldID, float value);
[DllImport(JNIEnv.DLL_JAVA)]
static extern void SetFloatField (IntPtr obj, IntPtr fieldID, float val);
public void SetFloat (JObject obj, float value)
{
if (isStatic) {
SetStaticFloatField (
DeclaringClass.Handle,
Handle,
value);
} else {
if (obj == null) {
throw new NullReferenceException (Name);
} else {
SetFloatField (
obj.Handle,
Handle,
value);
}
}
JThrowable.CheckAndThrow ();
}
[DllImport(JNIEnv.DLL_JAVA)]
static extern double GetStaticDoubleField (IntPtr clazz, IntPtr fieldID);
[DllImport(JNIEnv.DLL_JAVA)]
static extern double GetDoubleField (IntPtr obj, IntPtr fieldID);
public double GetDouble (JObject obj)
{
double r;
if (isStatic) {
r = GetStaticDoubleField (
DeclaringClass.Handle,
Handle);
} else {
if (obj == null) {
throw new NullReferenceException (Name);
} else {
r = GetDoubleField (obj.Handle, Handle);
}
}
JThrowable.CheckAndThrow ();
return r;
}
[DllImport(JNIEnv.DLL_JAVA)]
static extern void SetStaticDoubleField (IntPtr clazz, IntPtr fieldID, double value);
[DllImport(JNIEnv.DLL_JAVA)]
static extern void SetDoubleField (IntPtr obj, IntPtr fieldID, double val);
public void SetDouble (JObject obj, double value)
{
if (isStatic) {
SetStaticDoubleField (
DeclaringClass.Handle,
Handle,
value);
} else {
if (obj == null) {
throw new NullReferenceException (Name);
} else {
SetDoubleField (
obj.Handle,
Handle,
value);
}
}
JThrowable.CheckAndThrow ();
}
[DllImport(JNIEnv.DLL_JAVA)]
static extern IntPtr FromReflectedField (IntPtr field);
[DllImport(JNIEnv.DLL_JAVA)]
static extern IntPtr ToReflectedField (IntPtr cls, IntPtr fieldID, bool isStatic);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.