context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using EncompassRest.Loans.Enums; namespace EncompassRest.Loans { /// <summary> /// LoanEstimate1 /// </summary> public sealed partial class LoanEstimate1 : DirtyExtensibleObject, IIdentifiable { private DirtyValue<StringEnumValue<TermType>>? _adjustsTermType; private DirtyValue<string?>? _changedCircumstanceComments; private DirtyValue<DateTime?>? _closingCostEstimateExpirationDate; private DirtyValue<string?>? _closingCostEstimateExpirationDateUI; private DirtyValue<string?>? _closingCostEstimateExpirationTime; private DirtyValue<string?>? _closingCostEstimateExpirationTimeUI; private DirtyValue<string?>? _closingCostEstimateExpirationTimeZone; private DirtyValue<string?>? _closingCostEstimateExpirationTimeZoneUI; private DirtyValue<StringEnumValue<Conversion>>? _conversionBegin; private DirtyValue<StringEnumValue<Conversion>>? _conversionEnd; private DirtyValue<string?>? _disclosureBy; private DirtyValue<DateTime?>? _disclosureClosingCostExpDate; private DirtyValue<string?>? _disclosureClosingCostExpTime; private DirtyValue<string?>? _disclosureClosingCostExpTimeZone; private DirtyValue<string?>? _disclosureComments; private DirtyValue<DateTime?>? _disclosureLastSentDate; private DirtyValue<DateTime?>? _disclosureReceivedDate; private DirtyValue<string?>? _disclosureSentMethod; private DirtyValue<decimal?>? _estimatedTaxesInsuranceAssessments; private DirtyValue<string?>? _estimatedTaxesInsuranceAssessmentsUI; private DirtyValue<decimal?>? _highestMonthlyPI; private DirtyValue<string?>? _id; private DirtyValue<string?>? _inEscrowHomeownerInsurance; private DirtyValue<string?>? _inEscrowOther; private DirtyValue<string?>? _inEscrowPropertyTaxes; private DirtyValue<decimal?>? _initialMonthlyPaymentFor10000Loan; private DirtyValue<decimal?>? _initialMonthlyPaymentFor60000Loan; private DirtyValue<string?>? _interestRateAdjustsEveryYears; private DirtyValue<int?>? _interestRateAdjustsInYear; private DirtyValue<StringEnumValue<MonthOrYear>>? _interestRateAdjustsStartingInType; private DirtyValue<int?>? _interestRateAfterAdjustment; private DirtyValue<StringEnumValue<CanGoOrGoes>>? _interestRateCanGoGoes; private DirtyValue<DateTime?>? _lEDateIssued; private DirtyValue<StringEnumValue<CanGoOrGoes>>? _loanAmountCanGoGoes; private DirtyValue<StringEnumValue<CanIncreaseOrIncreases>>? _loanAmountCanIncreaseOrIncreases; private DirtyValue<string?>? _loanProduct; private DirtyValue<StringEnumValue<LoanEstimate1LoanPurpose>>? _loanPurpose; private DirtyValue<int?>? _loanTermMonths; private DirtyValue<int?>? _loanTermYears; private DirtyValue<decimal?>? _maximumMonthlyPaymentFor10000Loan; private DirtyValue<int?>? _maximumPaymentMonth; private DirtyValue<StringEnumValue<MonthOrYear>>? _monthlyPIAdjustedInDateType; private DirtyValue<string?>? _monthlyPIAdjustsEveryYears; private DirtyValue<int?>? _monthlyPIAdjustsInYear; private DirtyValue<StringEnumValue<MonthOrYear>>? _monthlyPIAdjustsStartingInType; private DirtyValue<StringEnumValue<TermType>>? _monthlyPIAdjustsTermType; private DirtyValue<int?>? _monthlyPIAfterAdjustment; private DirtyValue<StringEnumValue<CanGoOrGoes>>? _monthlyPICanGoGoes; private DirtyValue<StringEnumValue<MonthOrYear>>? _monthlyPIInterestOnlyDateType; private DirtyValue<int?>? _monthlyPIInterestOnlyUntilYear; private DirtyValue<int?>? _pPC1EstimatedEscrowAmount; private DirtyValue<string?>? _pPC1EstimatedEscrowAmountUI; private DirtyValue<bool?>? _pPC1InterestOnly; private DirtyValue<decimal?>? _pPC1MaximumMonthlyPayment; private DirtyValue<string?>? _pPC1MaximumMonthlyPaymentUI; private DirtyValue<decimal?>? _pPC1MaximumPIPayment; private DirtyValue<string?>? _pPC1MaximumPIPaymentUI; private DirtyValue<int?>? _pPC1MIAmount; private DirtyValue<string?>? _pPC1MIAmountUI; private DirtyValue<int?>? _pPC1MinimumMonthlyPayment; private DirtyValue<string?>? _pPC1MinimumMonthlyPaymentUI; private DirtyValue<decimal?>? _pPC1MinimumPIPayment; private DirtyValue<string?>? _pPC1MinimumPIPaymentUI; private DirtyValue<int?>? _pPC1Year; private DirtyValue<int?>? _pPC2EstimatedEscrowAmount; private DirtyValue<string?>? _pPC2EstimatedEscrowAmountUI; private DirtyValue<bool?>? _pPC2InterestOnly; private DirtyValue<decimal?>? _pPC2MaximumMonthlyPayment; private DirtyValue<string?>? _pPC2MaximumMonthlyPaymentUI; private DirtyValue<decimal?>? _pPC2MaximumPIPayment; private DirtyValue<string?>? _pPC2MaximumPIPaymentUI; private DirtyValue<int?>? _pPC2MIAmount; private DirtyValue<string?>? _pPC2MIAmountUI; private DirtyValue<int?>? _pPC2MinimumMonthlyPayment; private DirtyValue<string?>? _pPC2MinimumMonthlyPaymentUI; private DirtyValue<decimal?>? _pPC2MinimumPIPayment; private DirtyValue<string?>? _pPC2MinimumPIPaymentUI; private DirtyValue<int?>? _pPC2YearFrom; private DirtyValue<int?>? _pPC2YearTo; private DirtyValue<int?>? _pPC3EstimatedEscrowAmount; private DirtyValue<string?>? _pPC3EstimatedEscrowAmountUI; private DirtyValue<bool?>? _pPC3InterestOnly; private DirtyValue<decimal?>? _pPC3MaximumMonthlyPayment; private DirtyValue<string?>? _pPC3MaximumMonthlyPaymentUI; private DirtyValue<decimal?>? _pPC3MaximumPIPayment; private DirtyValue<string?>? _pPC3MaximumPIPaymentUI; private DirtyValue<int?>? _pPC3MIAmount; private DirtyValue<string?>? _pPC3MIAmountUI; private DirtyValue<int?>? _pPC3MinimumMonthlyPayment; private DirtyValue<string?>? _pPC3MinimumMonthlyPaymentUI; private DirtyValue<decimal?>? _pPC3MinimumPIPayment; private DirtyValue<string?>? _pPC3MinimumPIPaymentUI; private DirtyValue<int?>? _pPC3YearFrom; private DirtyValue<int?>? _pPC3YearTo; private DirtyValue<int?>? _pPC4EstimatedEscrowAmount; private DirtyValue<string?>? _pPC4EstimatedEscrowAmountUI; private DirtyValue<bool?>? _pPC4InterestOnly; private DirtyValue<decimal?>? _pPC4MaximumMonthlyPayment; private DirtyValue<string?>? _pPC4MaximumMonthlyPaymentUI; private DirtyValue<decimal?>? _pPC4MaximumPIPayment; private DirtyValue<string?>? _pPC4MaximumPIPaymentUI; private DirtyValue<int?>? _pPC4MIAmount; private DirtyValue<string?>? _pPC4MIAmountUI; private DirtyValue<int?>? _pPC4MinimumMonthlyPayment; private DirtyValue<string?>? _pPC4MinimumMonthlyPaymentUI; private DirtyValue<decimal?>? _pPC4MinimumPIPayment; private DirtyValue<string?>? _pPC4MinimumPIPaymentUI; private DirtyValue<int?>? _pPC4YearFrom; private DirtyValue<int?>? _pPC4YearTo; private DirtyValue<bool?>? _pPEstimatedEscrowIndicator; private DirtyValue<int?>? _prepaymentPenaltyPayOffDuringYear; private DirtyValue<StringEnumValue<TermType>>? _prepaymentPenaltyPayOffInDateType; private DirtyValue<string?>? _prepaymentPenaltyPayOffInFirstYear; private DirtyValue<bool?>? _rangePaymentIndicatorC1; private DirtyValue<bool?>? _rangePaymentIndicatorC2; private DirtyValue<bool?>? _rangePaymentIndicatorC3; private DirtyValue<bool?>? _rangePaymentIndicatorC4; private DirtyValue<string?>? _rateLockExpirationTime; private DirtyValue<string?>? _rateLockExpirationTimeZone; private DirtyValue<string?>? _reasonChangedCircumstanceFlags; private DirtyValue<bool?>? _reasonDelayedSettlement; private DirtyValue<bool?>? _reasonEligibility; private DirtyValue<bool?>? _reasonExpiration; private DirtyValue<bool?>? _reasonInterestRate; private DirtyValue<bool?>? _reasonOther; private DirtyValue<string?>? _reasonOtherDescription; private DirtyValue<bool?>? _reasonRevisions; private DirtyValue<bool?>? _reasonSettlementCharges; private DirtyValue<decimal?>? _totalEstimatedCashClose; private DirtyValue<int?>? _yearsToRecast; /// <summary> /// Loan Estimate - Interest Rate - Adjusts Every Months/Year/Years [LE1.X14] /// </summary> [LoanFieldProperty(MissingOptionsJson = "[\"Month\"]")] public StringEnumValue<TermType> AdjustsTermType { get => _adjustsTermType; set => SetField(ref _adjustsTermType, value); } /// <summary> /// Comments [LE1.X86] /// </summary> public string? ChangedCircumstanceComments { get => _changedCircumstanceComments; set => SetField(ref _changedCircumstanceComments, value); } /// <summary> /// Loan Estimate - Closing Costs Estimate Expiration Date [LE1.X28] /// </summary> public DateTime? ClosingCostEstimateExpirationDate { get => _closingCostEstimateExpirationDate; set => SetField(ref _closingCostEstimateExpirationDate, value); } /// <summary> /// Loan Estimate - Closing Costs Estimate Expiration Date UI Value [LE1.XD28] /// </summary> public string? ClosingCostEstimateExpirationDateUI { get => _closingCostEstimateExpirationDateUI; set => SetField(ref _closingCostEstimateExpirationDateUI, value); } /// <summary> /// Loan Estimate - Closing Costs Estimate Expiration Time [LE1.X8] /// </summary> public string? ClosingCostEstimateExpirationTime { get => _closingCostEstimateExpirationTime; set => SetField(ref _closingCostEstimateExpirationTime, value); } /// <summary> /// Loan Estimate - Closing Costs Estimate Expiration Time UI Value [LE1.XD8] /// </summary> public string? ClosingCostEstimateExpirationTimeUI { get => _closingCostEstimateExpirationTimeUI; set => SetField(ref _closingCostEstimateExpirationTimeUI, value); } /// <summary> /// Loan Estimate - Closing Costs Estimate Expiration Time Zone [LE1.X9] /// </summary> public string? ClosingCostEstimateExpirationTimeZone { get => _closingCostEstimateExpirationTimeZone; set => SetField(ref _closingCostEstimateExpirationTimeZone, value); } /// <summary> /// Loan Estimate - Closing Costs Estimate Expiration Time Zone UI Value [LE1.XD9] /// </summary> public string? ClosingCostEstimateExpirationTimeZoneUI { get => _closingCostEstimateExpirationTimeZoneUI; set => SetField(ref _closingCostEstimateExpirationTimeZoneUI, value); } /// <summary> /// Conversion Begin Period [LE1.X96] /// </summary> public StringEnumValue<Conversion> ConversionBegin { get => _conversionBegin; set => SetField(ref _conversionBegin, value); } /// <summary> /// Conversion End Period [LE1.X97] /// </summary> public StringEnumValue<Conversion> ConversionEnd { get => _conversionEnd; set => SetField(ref _conversionEnd, value); } /// <summary> /// Loan Estimate - Disclosure By [LE1.X34] /// </summary> public string? DisclosureBy { get => _disclosureBy; set => SetField(ref _disclosureBy, value); } /// <summary> /// Loan Estimate - Disclosure Closing Cost Exp. Date [LE1.X36] /// </summary> public DateTime? DisclosureClosingCostExpDate { get => _disclosureClosingCostExpDate; set => SetField(ref _disclosureClosingCostExpDate, value); } /// <summary> /// Loan Estimate - Disclosure Expiration Time [LE1.X37] /// </summary> public string? DisclosureClosingCostExpTime { get => _disclosureClosingCostExpTime; set => SetField(ref _disclosureClosingCostExpTime, value); } /// <summary> /// Loan Estimate - Disclosure Expiration Time Zone [LE1.X38] /// </summary> public string? DisclosureClosingCostExpTimeZone { get => _disclosureClosingCostExpTimeZone; set => SetField(ref _disclosureClosingCostExpTimeZone, value); } /// <summary> /// Loan Estimate - Disclosure Comments [LE1.X40] /// </summary> public string? DisclosureComments { get => _disclosureComments; set => SetField(ref _disclosureComments, value); } /// <summary> /// Loan Estimate - Disclosure Last Sent Date [LE1.X33] /// </summary> public DateTime? DisclosureLastSentDate { get => _disclosureLastSentDate; set => SetField(ref _disclosureLastSentDate, value); } /// <summary> /// Loan Estimate - Disclosure Received Date [LE1.X39] /// </summary> public DateTime? DisclosureReceivedDate { get => _disclosureReceivedDate; set => SetField(ref _disclosureReceivedDate, value); } /// <summary> /// Loan Estimate - Disclosure Sent Method [LE1.X35] /// </summary> public string? DisclosureSentMethod { get => _disclosureSentMethod; set => SetField(ref _disclosureSentMethod, value); } /// <summary> /// Loan Estimate - Estimated Taxes, Insurance and Assessments [LE1.X29] /// </summary> public decimal? EstimatedTaxesInsuranceAssessments { get => _estimatedTaxesInsuranceAssessments; set => SetField(ref _estimatedTaxesInsuranceAssessments, value); } /// <summary> /// Loan Estimate - Estimated Taxes, Insurance and Assessments UI Value [LE1.XD29] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? EstimatedTaxesInsuranceAssessmentsUI { get => _estimatedTaxesInsuranceAssessmentsUI; set => SetField(ref _estimatedTaxesInsuranceAssessmentsUI, value); } /// <summary> /// Loan Estimate - Monthly Principal and Interest Will be Adjusted in Year [LE1.X24] /// </summary> public decimal? HighestMonthlyPI { get => _highestMonthlyPI; set => SetField(ref _highestMonthlyPI, value); } /// <summary> /// LoanEstimate1 Id /// </summary> public string? Id { get => _id; set => SetField(ref _id, value); } /// <summary> /// Loan Estimate - In Escrow Homeowner Insurance [LE1.X31] /// </summary> public string? InEscrowHomeownerInsurance { get => _inEscrowHomeownerInsurance; set => SetField(ref _inEscrowHomeownerInsurance, value); } /// <summary> /// Loan Estimate - In Escrow Other [LE1.X32] /// </summary> public string? InEscrowOther { get => _inEscrowOther; set => SetField(ref _inEscrowOther, value); } /// <summary> /// Loan Estimate - In Escrow Property Taxes [LE1.X30] /// </summary> public string? InEscrowPropertyTaxes { get => _inEscrowPropertyTaxes; set => SetField(ref _inEscrowPropertyTaxes, value); } /// <summary> /// The calculated initial monthly payment for a $10,000 loan [LE1.X92] /// </summary> public decimal? InitialMonthlyPaymentFor10000Loan { get => _initialMonthlyPaymentFor10000Loan; set => SetField(ref _initialMonthlyPaymentFor10000Loan, value); } /// <summary> /// The calculation initial monthly payment for a $60,000 loan [LE1.X95] /// </summary> public decimal? InitialMonthlyPaymentFor60000Loan { get => _initialMonthlyPaymentFor60000Loan; set => SetField(ref _initialMonthlyPaymentFor60000Loan, value); } /// <summary> /// Loan Estimate - Interest Rate will Adjusts Every [LE1.X13] /// </summary> public string? InterestRateAdjustsEveryYears { get => _interestRateAdjustsEveryYears; set => SetField(ref _interestRateAdjustsEveryYears, value); } /// <summary> /// Loan Estimate - Interest Rate Will be Adjusted in Year [LE1.X18] /// </summary> public int? InterestRateAdjustsInYear { get => _interestRateAdjustsInYear; set => SetField(ref _interestRateAdjustsInYear, value); } /// <summary> /// Loan Estimate - Interest Rate - Adjusts Starting in [LE1.X15] /// </summary> public StringEnumValue<MonthOrYear> InterestRateAdjustsStartingInType { get => _interestRateAdjustsStartingInType; set => SetField(ref _interestRateAdjustsStartingInType, value); } /// <summary> /// Loan Estimate - Interest Rate After Adjustment [LE1.X16] /// </summary> public int? InterestRateAfterAdjustment { get => _interestRateAfterAdjustment; set => SetField(ref _interestRateAfterAdjustment, value); } /// <summary> /// Loan Estimate - Interest Rate Can go or Goes [LE1.X17] /// </summary> public StringEnumValue<CanGoOrGoes> InterestRateCanGoGoes { get => _interestRateCanGoGoes; set => SetField(ref _interestRateCanGoGoes, value); } /// <summary> /// Loan Estimate - LE Date Issued [LE1.X1] /// </summary> public DateTime? LEDateIssued { get => _lEDateIssued; set => SetField(ref _lEDateIssued, value); } /// <summary> /// Loan Estimate - Loan Amount Can go or Goes [LE1.X10] /// </summary> public StringEnumValue<CanGoOrGoes> LoanAmountCanGoGoes { get => _loanAmountCanGoGoes; set => SetField(ref _loanAmountCanGoGoes, value); } /// <summary> /// Loan Estimate - Loan Amount Can increase or Increases [LE1.X11] /// </summary> public StringEnumValue<CanIncreaseOrIncreases> LoanAmountCanIncreaseOrIncreases { get => _loanAmountCanIncreaseOrIncreases; set => SetField(ref _loanAmountCanIncreaseOrIncreases, value); } /// <summary> /// Product Description [LE1.X5] /// </summary> public string? LoanProduct { get => _loanProduct; set => SetField(ref _loanProduct, value); } /// <summary> /// Loan Estimate - Loan Purpose [LE1.X4] /// </summary> public StringEnumValue<LoanEstimate1LoanPurpose> LoanPurpose { get => _loanPurpose; set => SetField(ref _loanPurpose, value); } /// <summary> /// Loan Estimate - Loan Term Months [LE1.X3] /// </summary> public int? LoanTermMonths { get => _loanTermMonths; set => SetField(ref _loanTermMonths, value); } /// <summary> /// Loan Estimate - Loan Term Years [LE1.X2] /// </summary> public int? LoanTermYears { get => _loanTermYears; set => SetField(ref _loanTermYears, value); } /// <summary> /// The calculated maximum monthly payment for a $10,000 loan [LE1.X93] /// </summary> public decimal? MaximumMonthlyPaymentFor10000Loan { get => _maximumMonthlyPaymentFor10000Loan; set => SetField(ref _maximumMonthlyPaymentFor10000Loan, value); } /// <summary> /// The calculated month in which the maximum monthly payment will go into effect [LE1.X94] /// </summary> public int? MaximumPaymentMonth { get => _maximumPaymentMonth; set => SetField(ref _maximumPaymentMonth, value); } /// <summary> /// Loan Estimate - Monthly Principal and Interest - Will be Adjusted in Year/Month [LE1.X88] /// </summary> public StringEnumValue<MonthOrYear> MonthlyPIAdjustedInDateType { get => _monthlyPIAdjustedInDateType; set => SetField(ref _monthlyPIAdjustedInDateType, value); } /// <summary> /// Loan Estimate - Monthly Principal and Interest will Adjusts Every [LE1.X19] /// </summary> public string? MonthlyPIAdjustsEveryYears { get => _monthlyPIAdjustsEveryYears; set => SetField(ref _monthlyPIAdjustsEveryYears, value); } /// <summary> /// Loan Estimate - Monthly Principal and Interest Will be Adjusted in Year [LE1.X25] /// </summary> public int? MonthlyPIAdjustsInYear { get => _monthlyPIAdjustsInYear; set => SetField(ref _monthlyPIAdjustsInYear, value); } /// <summary> /// Loan Estimate - Monthly Principal and Interest - Adjusts Starting in [LE1.X21] /// </summary> public StringEnumValue<MonthOrYear> MonthlyPIAdjustsStartingInType { get => _monthlyPIAdjustsStartingInType; set => SetField(ref _monthlyPIAdjustsStartingInType, value); } /// <summary> /// Loan Estimate - Monthly Principal and Interest - Adjusts Every Months/Year/Years [LE1.X20] /// </summary> public StringEnumValue<TermType> MonthlyPIAdjustsTermType { get => _monthlyPIAdjustsTermType; set => SetField(ref _monthlyPIAdjustsTermType, value); } /// <summary> /// Loan Estimate - Monthly Principal and Interest - After Adjustment [LE1.X22] /// </summary> public int? MonthlyPIAfterAdjustment { get => _monthlyPIAfterAdjustment; set => SetField(ref _monthlyPIAfterAdjustment, value); } /// <summary> /// Loan Estimate - Monthly Principal and Interest Can go or Goes [LE1.X23] /// </summary> public StringEnumValue<CanGoOrGoes> MonthlyPICanGoGoes { get => _monthlyPICanGoGoes; set => SetField(ref _monthlyPICanGoGoes, value); } /// <summary> /// Loan Estimate - Monthly Principal and Interest - Interest Only in Year/Month [LE1.X89] /// </summary> public StringEnumValue<MonthOrYear> MonthlyPIInterestOnlyDateType { get => _monthlyPIInterestOnlyDateType; set => SetField(ref _monthlyPIInterestOnlyDateType, value); } /// <summary> /// Loan Estimate - Monthly Principal and Interest - Includes only interest and no principal until year [LE1.X26] /// </summary> public int? MonthlyPIInterestOnlyUntilYear { get => _monthlyPIInterestOnlyUntilYear; set => SetField(ref _monthlyPIInterestOnlyUntilYear, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Estimated Escrow Amount [LE1.X46] /// </summary> public int? PPC1EstimatedEscrowAmount { get => _pPC1EstimatedEscrowAmount; set => SetField(ref _pPC1EstimatedEscrowAmount, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Estimated Escrow Amount UI Value [LE1.XD46] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC1EstimatedEscrowAmountUI { get => _pPC1EstimatedEscrowAmountUI; set => SetField(ref _pPC1EstimatedEscrowAmountUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Interest Only [LE1.X44] /// </summary> public bool? PPC1InterestOnly { get => _pPC1InterestOnly; set => SetField(ref _pPC1InterestOnly, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Maximum Monthly Payment [LE1.X48] /// </summary> public decimal? PPC1MaximumMonthlyPayment { get => _pPC1MaximumMonthlyPayment; set => SetField(ref _pPC1MaximumMonthlyPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Maximum Monthly Payment UI Value [LE1.XD48] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC1MaximumMonthlyPaymentUI { get => _pPC1MaximumMonthlyPaymentUI; set => SetField(ref _pPC1MaximumMonthlyPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Maximum Principal and Interest Payment [LE1.X43] /// </summary> public decimal? PPC1MaximumPIPayment { get => _pPC1MaximumPIPayment; set => SetField(ref _pPC1MaximumPIPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Maximum Principal and Interest Payment UI Value [LE1.XD43] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC1MaximumPIPaymentUI { get => _pPC1MaximumPIPaymentUI; set => SetField(ref _pPC1MaximumPIPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Mortgage Insurance Amount [LE1.X45] /// </summary> public int? PPC1MIAmount { get => _pPC1MIAmount; set => SetField(ref _pPC1MIAmount, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Mortgage Insurance Amount UI Value [LE1.XD45] /// </summary> public string? PPC1MIAmountUI { get => _pPC1MIAmountUI; set => SetField(ref _pPC1MIAmountUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Minimum Monthly Payment [LE1.X47] /// </summary> public int? PPC1MinimumMonthlyPayment { get => _pPC1MinimumMonthlyPayment; set => SetField(ref _pPC1MinimumMonthlyPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Minimum Monthly Payment UI Value [LE1.XD47] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC1MinimumMonthlyPaymentUI { get => _pPC1MinimumMonthlyPaymentUI; set => SetField(ref _pPC1MinimumMonthlyPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Minimum Principal and Interest Payment [LE1.X42] /// </summary> public decimal? PPC1MinimumPIPayment { get => _pPC1MinimumPIPayment; set => SetField(ref _pPC1MinimumPIPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Minimum Principal and Interest Payment UI Value [LE1.XD42] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC1MinimumPIPaymentUI { get => _pPC1MinimumPIPaymentUI; set => SetField(ref _pPC1MinimumPIPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Year [LE1.X41] /// </summary> public int? PPC1Year { get => _pPC1Year; set => SetField(ref _pPC1Year, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Estimated Escrow Amount [LE1.X55] /// </summary> public int? PPC2EstimatedEscrowAmount { get => _pPC2EstimatedEscrowAmount; set => SetField(ref _pPC2EstimatedEscrowAmount, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Estimated Escrow Amount UI Value [LE1.XD55] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC2EstimatedEscrowAmountUI { get => _pPC2EstimatedEscrowAmountUI; set => SetField(ref _pPC2EstimatedEscrowAmountUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Interest Only [LE1.X53] /// </summary> public bool? PPC2InterestOnly { get => _pPC2InterestOnly; set => SetField(ref _pPC2InterestOnly, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Maximum Monthly Payment [LE1.X57] /// </summary> public decimal? PPC2MaximumMonthlyPayment { get => _pPC2MaximumMonthlyPayment; set => SetField(ref _pPC2MaximumMonthlyPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Maximum Monthly Payment UI Value [LE1.XD57] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC2MaximumMonthlyPaymentUI { get => _pPC2MaximumMonthlyPaymentUI; set => SetField(ref _pPC2MaximumMonthlyPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Maximum Principal and Interest Payment [LE1.X52] /// </summary> public decimal? PPC2MaximumPIPayment { get => _pPC2MaximumPIPayment; set => SetField(ref _pPC2MaximumPIPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Maximum Principal and Interest Payment UI Value [LE1.XD52] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC2MaximumPIPaymentUI { get => _pPC2MaximumPIPaymentUI; set => SetField(ref _pPC2MaximumPIPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Mortgage Insurance Amount [LE1.X54] /// </summary> public int? PPC2MIAmount { get => _pPC2MIAmount; set => SetField(ref _pPC2MIAmount, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Mortgage Insurance Amount UI Value [LE1.XD54] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC2MIAmountUI { get => _pPC2MIAmountUI; set => SetField(ref _pPC2MIAmountUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Minimum Monthly Payment [LE1.X56] /// </summary> public int? PPC2MinimumMonthlyPayment { get => _pPC2MinimumMonthlyPayment; set => SetField(ref _pPC2MinimumMonthlyPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Minimum Monthly Payment UI Value [LE1.XD56] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC2MinimumMonthlyPaymentUI { get => _pPC2MinimumMonthlyPaymentUI; set => SetField(ref _pPC2MinimumMonthlyPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Minimum Principal and Interest Payment [LE1.X51] /// </summary> public decimal? PPC2MinimumPIPayment { get => _pPC2MinimumPIPayment; set => SetField(ref _pPC2MinimumPIPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Minimum Principal and Interest Payment UI Value [LE1.XD51] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC2MinimumPIPaymentUI { get => _pPC2MinimumPIPaymentUI; set => SetField(ref _pPC2MinimumPIPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Year From [LE1.X49] /// </summary> public int? PPC2YearFrom { get => _pPC2YearFrom; set => SetField(ref _pPC2YearFrom, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Year To [LE1.X50] /// </summary> public int? PPC2YearTo { get => _pPC2YearTo; set => SetField(ref _pPC2YearTo, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Estimated Escrow Amount [LE1.X64] /// </summary> public int? PPC3EstimatedEscrowAmount { get => _pPC3EstimatedEscrowAmount; set => SetField(ref _pPC3EstimatedEscrowAmount, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Estimated Escrow Amount UI Value [LE1.XD64] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC3EstimatedEscrowAmountUI { get => _pPC3EstimatedEscrowAmountUI; set => SetField(ref _pPC3EstimatedEscrowAmountUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Interest Only [LE1.X62] /// </summary> public bool? PPC3InterestOnly { get => _pPC3InterestOnly; set => SetField(ref _pPC3InterestOnly, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Maximum Monthly Payment [LE1.X66] /// </summary> public decimal? PPC3MaximumMonthlyPayment { get => _pPC3MaximumMonthlyPayment; set => SetField(ref _pPC3MaximumMonthlyPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Maximum Monthly Payment UI Value [LE1.XD66] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC3MaximumMonthlyPaymentUI { get => _pPC3MaximumMonthlyPaymentUI; set => SetField(ref _pPC3MaximumMonthlyPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Maximum Principal and Interest Payment [LE1.X61] /// </summary> public decimal? PPC3MaximumPIPayment { get => _pPC3MaximumPIPayment; set => SetField(ref _pPC3MaximumPIPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Maximum Principal and Interest Payment UI Value [LE1.XD61] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC3MaximumPIPaymentUI { get => _pPC3MaximumPIPaymentUI; set => SetField(ref _pPC3MaximumPIPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Mortgage Insurance Amount [LE1.X63] /// </summary> public int? PPC3MIAmount { get => _pPC3MIAmount; set => SetField(ref _pPC3MIAmount, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Mortgage Insurance Amount UI Value [LE1.XD63] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC3MIAmountUI { get => _pPC3MIAmountUI; set => SetField(ref _pPC3MIAmountUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Minimum Monthly Payment [LE1.X65] /// </summary> public int? PPC3MinimumMonthlyPayment { get => _pPC3MinimumMonthlyPayment; set => SetField(ref _pPC3MinimumMonthlyPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Minimum Monthly Payment UI Value [LE1.XD65] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC3MinimumMonthlyPaymentUI { get => _pPC3MinimumMonthlyPaymentUI; set => SetField(ref _pPC3MinimumMonthlyPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Minimum Principal and Interest Payment [LE1.X60] /// </summary> public decimal? PPC3MinimumPIPayment { get => _pPC3MinimumPIPayment; set => SetField(ref _pPC3MinimumPIPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Minimum Principal and Interest Payment UI Value [LE1.XD60] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC3MinimumPIPaymentUI { get => _pPC3MinimumPIPaymentUI; set => SetField(ref _pPC3MinimumPIPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Year From [LE1.X58] /// </summary> public int? PPC3YearFrom { get => _pPC3YearFrom; set => SetField(ref _pPC3YearFrom, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Year To [LE1.X59] /// </summary> public int? PPC3YearTo { get => _pPC3YearTo; set => SetField(ref _pPC3YearTo, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Estimated Escrow Amount [LE1.X73] /// </summary> public int? PPC4EstimatedEscrowAmount { get => _pPC4EstimatedEscrowAmount; set => SetField(ref _pPC4EstimatedEscrowAmount, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Estimated Escrow Amount UI Value [LE1.XD73] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC4EstimatedEscrowAmountUI { get => _pPC4EstimatedEscrowAmountUI; set => SetField(ref _pPC4EstimatedEscrowAmountUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Interest Only [LE1.X71] /// </summary> public bool? PPC4InterestOnly { get => _pPC4InterestOnly; set => SetField(ref _pPC4InterestOnly, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Maximum Monthly Payment [LE1.X75] /// </summary> public decimal? PPC4MaximumMonthlyPayment { get => _pPC4MaximumMonthlyPayment; set => SetField(ref _pPC4MaximumMonthlyPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Maximum Monthly Payment UI Value [LE1.XD75] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC4MaximumMonthlyPaymentUI { get => _pPC4MaximumMonthlyPaymentUI; set => SetField(ref _pPC4MaximumMonthlyPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Maximum Principal and Interest Payment [LE1.X70] /// </summary> public decimal? PPC4MaximumPIPayment { get => _pPC4MaximumPIPayment; set => SetField(ref _pPC4MaximumPIPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Maximum Principal and Interest Payment UI Value [LE1.XD70] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC4MaximumPIPaymentUI { get => _pPC4MaximumPIPaymentUI; set => SetField(ref _pPC4MaximumPIPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Mortgage Insurance Amount [LE1.X72] /// </summary> public int? PPC4MIAmount { get => _pPC4MIAmount; set => SetField(ref _pPC4MIAmount, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Mortgage Insurance Amount UI Value [LE1.XD72] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC4MIAmountUI { get => _pPC4MIAmountUI; set => SetField(ref _pPC4MIAmountUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Minimum Monthly Payment [LE1.X74] /// </summary> public int? PPC4MinimumMonthlyPayment { get => _pPC4MinimumMonthlyPayment; set => SetField(ref _pPC4MinimumMonthlyPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Minimum Monthly Payment UI Value [LE1.XD74] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC4MinimumMonthlyPaymentUI { get => _pPC4MinimumMonthlyPaymentUI; set => SetField(ref _pPC4MinimumMonthlyPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Minimum Principal and Interest Payment [LE1.X69] /// </summary> public decimal? PPC4MinimumPIPayment { get => _pPC4MinimumPIPayment; set => SetField(ref _pPC4MinimumPIPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Minimum Principal and Interest Payment UI Value [LE1.XD69] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC4MinimumPIPaymentUI { get => _pPC4MinimumPIPaymentUI; set => SetField(ref _pPC4MinimumPIPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Year From [LE1.X67] /// </summary> public int? PPC4YearFrom { get => _pPC4YearFrom; set => SetField(ref _pPC4YearFrom, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Year To [LE1.X68] /// </summary> public int? PPC4YearTo { get => _pPC4YearTo; set => SetField(ref _pPC4YearTo, value); } /// <summary> /// Loan Estimate - Projected Calculation - Estimated Escrow Indicator [LE1.X77] /// </summary> public bool? PPEstimatedEscrowIndicator { get => _pPEstimatedEscrowIndicator; set => SetField(ref _pPEstimatedEscrowIndicator, value); } /// <summary> /// Loan Estimate - Prepayment Penalty - If you pay off the loan during the first [LE1.X27] /// </summary> public int? PrepaymentPenaltyPayOffDuringYear { get => _prepaymentPenaltyPayOffDuringYear; set => SetField(ref _prepaymentPenaltyPayOffDuringYear, value); } /// <summary> /// Loan Estimate - Prepayment Penalty - In Year/Month [LE1.X91] /// </summary> [LoanFieldProperty(MissingOptionsJson = "[\"Month\"]")] public StringEnumValue<TermType> PrepaymentPenaltyPayOffInDateType { get => _prepaymentPenaltyPayOffInDateType; set => SetField(ref _prepaymentPenaltyPayOffInDateType, value); } /// <summary> /// Loan Estimate - Prepayment Penalty - In First Year [LE1.XD27] /// </summary> public string? PrepaymentPenaltyPayOffInFirstYear { get => _prepaymentPenaltyPayOffInFirstYear; set => SetField(ref _prepaymentPenaltyPayOffInFirstYear, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Range Payment Indicator [LE1.XD1] /// </summary> [LoanFieldProperty(ReadOnly = true)] public bool? RangePaymentIndicatorC1 { get => _rangePaymentIndicatorC1; set => SetField(ref _rangePaymentIndicatorC1, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Range Payment Indicator [LE1.XD2] /// </summary> [LoanFieldProperty(ReadOnly = true)] public bool? RangePaymentIndicatorC2 { get => _rangePaymentIndicatorC2; set => SetField(ref _rangePaymentIndicatorC2, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Range Payment Indicator [LE1.XD3] /// </summary> [LoanFieldProperty(ReadOnly = true)] public bool? RangePaymentIndicatorC3 { get => _rangePaymentIndicatorC3; set => SetField(ref _rangePaymentIndicatorC3, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Range Payment Indicator [LE1.XD4] /// </summary> [LoanFieldProperty(ReadOnly = true)] public bool? RangePaymentIndicatorC4 { get => _rangePaymentIndicatorC4; set => SetField(ref _rangePaymentIndicatorC4, value); } /// <summary> /// Loan Estimate - Rate Lock Expiration Time [LE1.X6] /// </summary> public string? RateLockExpirationTime { get => _rateLockExpirationTime; set => SetField(ref _rateLockExpirationTime, value); } /// <summary> /// Loan Estimate - Rate Lock Expiration Time Zone [LE1.X7] /// </summary> public string? RateLockExpirationTimeZone { get => _rateLockExpirationTimeZone; set => SetField(ref _rateLockExpirationTimeZone, value); } /// <summary> /// Loan Estimate - Reason Changed Circumstance Flags [LE1.X90] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? ReasonChangedCircumstanceFlags { get => _reasonChangedCircumstanceFlags; set => SetField(ref _reasonChangedCircumstanceFlags, value); } /// <summary> /// Delayed Settlement on Construction Loans [LE1.X83] /// </summary> public bool? ReasonDelayedSettlement { get => _reasonDelayedSettlement; set => SetField(ref _reasonDelayedSettlement, value); } /// <summary> /// Changed Circumstance - Eligibility [LE1.X79] /// </summary> public bool? ReasonEligibility { get => _reasonEligibility; set => SetField(ref _reasonEligibility, value); } /// <summary> /// Expiration (Intent to Proceed received after 10 business days) [LE1.X82] /// </summary> public bool? ReasonExpiration { get => _reasonExpiration; set => SetField(ref _reasonExpiration, value); } /// <summary> /// Interest Rate dependent charges (Rate Lock) [LE1.X81] /// </summary> public bool? ReasonInterestRate { get => _reasonInterestRate; set => SetField(ref _reasonInterestRate, value); } /// <summary> /// Other [LE1.X84] /// </summary> public bool? ReasonOther { get => _reasonOther; set => SetField(ref _reasonOther, value); } /// <summary> /// Other Description [LE1.X85] /// </summary> public string? ReasonOtherDescription { get => _reasonOtherDescription; set => SetField(ref _reasonOtherDescription, value); } /// <summary> /// Revisions requested by the consumer [LE1.X80] /// </summary> public bool? ReasonRevisions { get => _reasonRevisions; set => SetField(ref _reasonRevisions, value); } /// <summary> /// Changed Circumstance - Settlement Charges [LE1.X78] /// </summary> public bool? ReasonSettlementCharges { get => _reasonSettlementCharges; set => SetField(ref _reasonSettlementCharges, value); } /// <summary> /// Total Estimated Cash to Close [LE1.X87] /// </summary> public decimal? TotalEstimatedCashClose { get => _totalEstimatedCashClose; set => SetField(ref _totalEstimatedCashClose, value); } /// <summary> /// Loan Estimate - Year Until [LE1.X12] /// </summary> public int? YearsToRecast { get => _yearsToRecast; set => SetField(ref _yearsToRecast, value); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace NS_GuiItems { [AddComponentMenu("GuiItems/GuiItemsDrawer")] public class GuiItemsDrawer : MonoBehaviour { /// <summary> /// The default GUISkin applied on the GuiItem elements to draw. /// </summary> public GUISkin thisGuiSkin; /// <summary> /// Ideal resolution of the interface. /// </summary> static public Vector2 DesignResolution { get { return instance.designResolution; } } [SerializeField] private Vector2 designResolution = new Vector2(1920f, 1080f); /// <summary> /// This value is used when you want to horizontally position a single interface item /// using a position obtained from Camera.main.WorldToScreenPoint(). /// /// For example, we obtain a position on screen with Camera.main.WorldToScreenPoint(). /// Then we divide x and y of the position to get values relative to the screen size, in [0.0-1.0] range. /// Then we multiply x by GuiAreaWidth and y by GuiAreaHeight. /// Then we have the correct position usable within a GuiItemsDrawer screen drawing. /// /// It is recommended to use RelativeToPixels() instead. /// </summary> public static int GuiAreaWidth { get { return (int)(DesignResolution.x * FittingRatio.x); } } /// <summary> /// This value is used when you want to horizontally position a single interface item /// using a position obtained from Camera.main.WorldToScreenPoint() or by other means. /// /// For example, we obtain a position on screen with Camera.main.WorldToScreenPoint(). /// Then we divide x and y of the position to get values relative to the screen size, in [0.0-1.0] range. /// Then we multiply x by GuiAreaWidth and y by GuiAreaHeight. /// Then we have the correct position usable within a GuiItemsDrawer screen drawing. /// /// It is recommended to use RelativeToPixels() instead. /// </summary> public static int GuiAreaHeight { get { return (int)(DesignResolution.y * FittingRatio.y); } } /// <summary> /// Indicates if the mouse is over any GuiItem from the associated GuiItemsCollection. /// </summary> public bool MouseOverGuiItems { get { return mouseOverGuiItems; } } /// <summary> /// Indicates if the mouse is over any interactive GuiItem from the associated GuiItemsCollection. /// </summary> public bool MouseOverInteractiveGuiItem { get { return mouseOverInteractiveGuiItem; } } private bool mouseOverGuiItems; private bool mouseOverInteractiveGuiItem; /// <summary> /// GuiItemsCollections to draw. /// </summary> public List<GuiItemsCollection> guiItemsOrder; /// <summary> /// Unique instance. /// </summary> static public GuiItemsDrawer instance; void Awake() { mouseOverGuiItems = false; mouseOverInteractiveGuiItem = false; // Initialize the list guiItemsOrder = new List<GuiItemsCollection>(); DontDestroyOnLoad(gameObject); } void OnEnable() { instance = this; } void OnGUI() { // Clean the list guiItemsOrder.RemoveAll(item => item == null); // Save the original GUI matrix Matrix4x4 matrixBackup = GUI.matrix; // If defined, use thisGuiSkin GUISkin defaultSkin = null; if(thisGuiSkin) { defaultSkin = GUI.skin; GUI.skin = thisGuiSkin; } foreach(GuiItemsCollection g in guiItemsOrder) { if(g.enabled) { g.Draw(); } } // Restore matrix from backup GUI.matrix = matrixBackup; // Look if mouse cursor is over GuiItemsCollection and a GuiItem mouseOverGuiItems = false; mouseOverInteractiveGuiItem = false; // No need to continue if guiItemsOrder list is empty if(guiItemsOrder.Count != 0) { foreach(GuiItemsCollection g in guiItemsOrder) { // No need to check is this GuiItemsCollection has draw = false if(!g.draw) continue; foreach(GuiItemsCollection.GuiItem item in g.items) { // If the GuiItem is disabled, do not check it if(!item.enabled) continue; if((item.thisItemType != GuiItemsCollection.GuiItem.itemType.BEGIN_HORIZONTAL) && (item.thisItemType != GuiItemsCollection.GuiItem.itemType.BEGIN_VERTICAL) && (item.thisItemType != GuiItemsCollection.GuiItem.itemType.BEGIN_SCROLL_VIEW)) { if(item.hover) { mouseOverGuiItems = true; break; } } } if(mouseOverGuiItems) { break; } } // Look if the mouse cursor is over an interactive GuiItem foreach(GuiItemsCollection g in guiItemsOrder) { // No need to check is this GuiItemsCollection has draw = false if(!g.draw) continue; foreach(GuiItemsCollection.GuiItem item in g.items) { // If the GuiItem is disabled, do not check it if(!item.enabled) continue; switch(item.thisItemType) { case GuiItemsCollection.GuiItem.itemType.BUTTON: case GuiItemsCollection.GuiItem.itemType.PASSWORD_FIELD: case GuiItemsCollection.GuiItem.itemType.REPEAT_BUTTON: case GuiItemsCollection.GuiItem.itemType.SELECTION_GRID: case GuiItemsCollection.GuiItem.itemType.TEXT_AREA: case GuiItemsCollection.GuiItem.itemType.TEXT_FIELD: case GuiItemsCollection.GuiItem.itemType.TOGGLE: case GuiItemsCollection.GuiItem.itemType.TOOLBAR: if(item.hover) { mouseOverInteractiveGuiItem = true; } break; } if(mouseOverInteractiveGuiItem) break; } if(mouseOverInteractiveGuiItem) break; } } // Reset the default GUI skin if thisGuiSkin has been defined if(defaultSkin) { GUI.skin = defaultSkin; } } void Update() { // Clean the list guiItemsOrder.RemoveAll(item => item == null); foreach(GuiItemsCollection g in guiItemsOrder) { if(g.enabled) { foreach(GuiItemsCollection.GuiItem gi in g.items) { if(gi.loop) { // Animate looping labels gi.loopOffset += gi.loopScrollSpeed * Time.deltaTime; // Limit loopOffset to limit copies count if(gi.loopOffset < -gi.LoopLabelRect.width) gi.loopOffset += gi.LoopLabelRect.width; if(gi.loopOffset > gi.LoopLabelRect.width) gi.loopOffset -= gi.LoopLabelRect.width; } } } } } static public void ReferenceCollection(GuiItemsCollection collection) { if(!instance) { Debug.LogError("No GuiItemsDrawer object instantiated. Please instantiate a single GuiItemsDrawer object like the one in the GuiItems/GameObjects folder in your scene."); return; } if(!instance.guiItemsOrder.Contains(collection)) { // Reference this GuiItemsCollection in the list, from greater depth to lesser if(instance.guiItemsOrder.Count == 0) { instance.guiItemsOrder.Add(collection); } else { for(int i = 0; i < instance.guiItemsOrder.Count; i++) { if(instance.guiItemsOrder[i].depth <= collection.depth) { instance.guiItemsOrder.Insert(i, collection); break; } if(i == instance.guiItemsOrder.Count - 1) { instance.guiItemsOrder.Add(collection); break; } } } } } /// <summary> /// Values used for GuiItem scaling (position and size) from design resolution /// to current resolution. /// </summary> static public Vector2 FittingRatio { get { // Ratio lets us know if the screen is "horizontally-driven" or "vertically-driven" Vector2 ratio = new Vector2((float)Screen.width / DesignResolution.x, (float)Screen.height / DesignResolution.y); Vector2 correction = Vector2.one; if(ratio.x < ratio.y) { // Horizontally-driven correction.y = ratio.y / ratio.x; } else if(ratio.x > ratio.y) { // Vertically-driven correction.x = ratio.x / ratio.y; } return correction; } } /// <summary> /// Converts a Rect with relative values to absolute values (in pixels) which can /// be used in GuiItemsDrawer display mode. /// </summary> /// <param name="_relativeRect">Relative rect in percentage (values between 0 and 1, usually).</param> /// <returns>Absolute rect in pixels.</returns> static public Rect RelativeToPixels(Rect _relativeRect) { _relativeRect.width *= GuiItemsDrawer.GuiAreaWidth; _relativeRect.height *= GuiItemsDrawer.GuiAreaHeight; _relativeRect.x *= GuiItemsDrawer.GuiAreaWidth; _relativeRect.y *= GuiItemsDrawer.GuiAreaHeight; return _relativeRect; } /// <summary> /// Converts a Vector2 with relative values to absolute values (in pixels) which can /// be used in GuiItemsDrawer display mode. /// </summary> /// <param name="relativeValue">Relative Vector2 (values between 0 and 1, usually).</param> /// <returns>Absolute Vector2 in pixels.</returns> static public Vector2 RelativeToPixels(Vector2 _relativeVector2) { _relativeVector2.x *= GuiItemsDrawer.GuiAreaWidth; _relativeVector2.y *= GuiItemsDrawer.GuiAreaHeight; return _relativeVector2; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Xunit; namespace System.Reflection.Tests { public static class ConstructorInfoTests { public static IEnumerable<object[]> Equality_TestData() { ConstructorInfo[] methodSampleConstructors1 = GetConstructors(typeof(ConstructorInfoInvokeSample)); ConstructorInfo[] methodSampleConstructors2 = GetConstructors(typeof(ConstructorInfoInvokeSample)); yield return new object[] { methodSampleConstructors1[0], methodSampleConstructors2[0], true }; yield return new object[] { methodSampleConstructors1[1], methodSampleConstructors2[1], true }; yield return new object[] { methodSampleConstructors1[2], methodSampleConstructors2[2], true }; yield return new object[] { methodSampleConstructors1[1], methodSampleConstructors2[2], false }; } [Theory] [MemberData(nameof(Equality_TestData))] public static void Test_Equality(ConstructorInfo constructorInfo1, ConstructorInfo constructorInfo2, bool expected) { Assert.Equal(expected, constructorInfo1 == constructorInfo2); Assert.NotEqual(expected, constructorInfo1 != constructorInfo2); } [Fact] public static void Verify_Invoke_ReturnsNewObject() { ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample)); Assert.Equal(cis.Length, 3); ConstructorInfoInvokeSample obj = (ConstructorInfoInvokeSample)cis[0].Invoke(null); Assert.NotNull(obj); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Invoking static constructors not supported on UapAot")] public static void TestInvoke_Nullery() { ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoClassA)); Object obj = cis[0].Invoke(null, new object[] { }); Assert.Null(obj); } [Fact] public static void TestInvokeNeg() { ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoClassA)); Object obj = null; Assert.Throws<MemberAccessException>(() => { obj = cis[0].Invoke(new object[] { }); }); Assert.Null(obj); } [Fact] public static void TestInvoke_1DArray() { ConstructorInfo[] cis = GetConstructors(typeof(System.Object[])); object[] arr = null; //Test data for array length int[] arraylength = { 1, 2, 99, 65535 }; //try to invoke Array ctors with different lengths foreach (int length in arraylength) { //create big Array with elements arr = (object[])cis[0].Invoke(new Object[] { length }); Assert.NotNull(arr); Assert.Equal(arr.Length, length); } } [Fact] public static void TestInvoke_1DArrayWithNegativeLength() { ConstructorInfo[] cis = GetConstructors(typeof(System.Object[])); object[] arr = null; //Test data for array length int[] arraylength = { -1, -2, -99 }; //try to invoke Array ctors with different lengths foreach (int length in arraylength) { //create big Array with elements Assert.Throws<OverflowException>(() => { arr = (object[])cis[0].Invoke(new Object[] { length }); }); } } [Fact] public static void TestInvokeWithOneParam() { ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample)); //try to invoke Array ctors with one param ConstructorInfoInvokeSample obj = null; obj = (ConstructorInfoInvokeSample)cis[1].Invoke(new object[] { 100 }); Assert.NotNull(obj); Assert.Equal(obj.intValue, 100); } [Fact] public static void TestInvokeWithTwoParams() { ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample)); //try to invoke Array ctors with one param ConstructorInfoInvokeSample obj = null; obj = (ConstructorInfoInvokeSample)cis[2].Invoke(new object[] { 101, "hello" }); Assert.NotNull(obj); Assert.Equal(obj.intValue, 101); Assert.Equal(obj.strValue, "hello"); } [Fact] public static void TestInvoke_NoParamsProvided() { ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample)); //try to invoke Array ctors with one param ConstructorInfoInvokeSample obj = null; Assert.Throws<TargetParameterCountException>(() => { obj = (ConstructorInfoInvokeSample)cis[2].Invoke(new object[] { }); }); } [Fact] public static void TestInvoke_ParamMismatch() { ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample)); //try to invoke Array ctors with one param ConstructorInfoInvokeSample obj = null; Assert.Throws<TargetParameterCountException>(() => { obj = (ConstructorInfoInvokeSample)cis[2].Invoke(new object[] { 121 }); }); } [Fact] public static void TestInvoke_WrongParamType() { ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample)); //try to invoke Array ctors with one param ConstructorInfoInvokeSample obj = null; AssertExtensions.Throws<ArgumentException>(null, () => { obj = (ConstructorInfoInvokeSample)cis[1].Invoke(new object[] { "hello" }); }); } [Fact] public static void TestInvoke_ConstructorOnExistingInstance() { ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample)); //try to invoke Array ctors with one param ConstructorInfoInvokeSample obj1 = new ConstructorInfoInvokeSample(100, "hello"); ConstructorInfoInvokeSample obj2 = null; obj2 = (ConstructorInfoInvokeSample)cis[2].Invoke(obj1, new object[] { 999, "initialized" }); Assert.Null(obj2); Assert.Equal(obj1.intValue, 999); Assert.Equal(obj1.strValue, "initialized"); } [Fact] public static void TestInvoke_AbstractConstructor() { ConstructorInfo[] cis = GetConstructors(typeof(Base)); Object obj = null; Assert.Throws<MemberAccessException>(() => { obj = (Base)cis[0].Invoke(new object[] { }); }); } [Fact] public static void TestInvoke_DerivedConstructor() { ConstructorInfo[] cis = GetConstructors(typeof(Derived)); Derived obj = null; obj = (Derived)cis[0].Invoke(new object[] { }); Assert.NotNull(obj); } [Fact] public static void TestInvoke_Struct() { ConstructorInfo[] cis = GetConstructors(typeof(MyStruct)); MyStruct obj; obj = (MyStruct)cis[0].Invoke(new object[] { 1, 2 }); Assert.NotNull(obj); Assert.Equal(obj.x, 1); Assert.Equal(obj.y, 2); } public static ConstructorInfo[] GetConstructors(Type type) { return type.GetTypeInfo().DeclaredConstructors.ToArray(); } } //Metadata for Reflection public class ConstructorInfoInvokeSample { public int intValue = 0; public string strValue = ""; public ConstructorInfoInvokeSample() { } public ConstructorInfoInvokeSample(int i) { this.intValue = i; } public ConstructorInfoInvokeSample(int i, string s) { this.intValue = i; this.strValue = s; } public string Method1(DateTime t) { return ""; } } public static class ConstructorInfoClassA { static ConstructorInfoClassA() { } } public abstract class Base { public Base() { } } public class Derived : Base { public Derived() { } } public struct MyStruct { public int x; public int y; public MyStruct(int p1, int p2) { x = p1; y = p2; } }; }
/* * 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. */ #pragma warning disable 649 #pragma warning disable 169 namespace Apache.Ignite.Core.Tests.Compute { using System; using System.Collections.Generic; using System.Linq; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Resource; using NUnit.Framework; /// <summary> /// Test for task and job adapter. /// </summary> public class TaskAdapterTest : AbstractTaskTest { /// <summary> /// Constructor. /// </summary> public TaskAdapterTest() : base(false) { } /// <summary> /// Constructor. /// </summary> /// <param name="fork">Fork flag.</param> protected TaskAdapterTest(bool fork) : base(fork) { } /// <summary> /// Test for task adapter. /// </summary> [Test] public void TestTaskAdapter() { Assert.AreEqual(3, Grid1.GetCluster().GetNodes().Count); HashSet<Guid> allNodes = new HashSet<Guid>(); for (int i = 0; i < 20 && allNodes.Count < GetServerCount(); i++) { HashSet<Guid> res = Grid1.GetCompute().Execute(new TestSplitTask(), 1); Assert.AreEqual(1, res.Count); allNodes.UnionWith(res); } Assert.AreEqual(GetServerCount(), allNodes.Count); HashSet<Guid> res2 = Grid1.GetCompute().Execute<int, Guid, HashSet<Guid>>(typeof(TestSplitTask), 3); Assert.IsTrue(res2.Count > 0); Grid1.GetCompute().Execute(new TestSplitTask(), 100); Assert.AreEqual(GetServerCount(), allNodes.Count); } /// <summary> /// Test for job adapter. /// </summary> [Test] public void TestSerializableJobAdapter() { for (int i = 0; i < 10; i++) { bool res = Grid1.GetCompute().Execute(new TestJobAdapterTask(), true); Assert.IsTrue(res); } } /// <summary> /// Test for job adapter. /// </summary> [Test] public void TestBinarizableJobAdapter() { for (int i = 0; i < 10; i++) { bool res = Grid1.GetCompute().Execute(new TestJobAdapterTask(), false); Assert.IsTrue(res); } } /// <summary> /// Test task. /// </summary> public class TestSplitTask : ComputeTaskSplitAdapter<int, Guid, HashSet<Guid>> { [InstanceResource] private readonly IIgnite _ignite; /** <inheritDoc /> */ override protected ICollection<IComputeJob<Guid>> Split(int gridSize, int arg) { Assert.AreEqual(_ignite.GetCluster().GetNodes().Count(x => !x.IsClient), gridSize); int jobsNum = arg; Assert.IsTrue(jobsNum > 0); var jobs = new List<IComputeJob<Guid>>(jobsNum); for (int i = 0; i < jobsNum; i++) jobs.Add(new NodeIdJob()); return jobs; } /** <inheritDoc /> */ override public HashSet<Guid> Reduce(IList<IComputeJobResult<Guid>> results) { HashSet<Guid> nodes = new HashSet<Guid>(); foreach (var res in results) { Guid id = res.Data; Assert.NotNull(id); nodes.Add(id); } return nodes; } } /// <summary> /// Test task. /// </summary> public class TestJobAdapterTask : ComputeTaskSplitAdapter<bool, bool, bool> { /** <inheritDoc /> */ override protected ICollection<IComputeJob<bool>> Split(int gridSize, bool arg) { bool serializable = arg; ICollection<IComputeJob<bool>> jobs = new List<IComputeJob<bool>>(1); if (serializable) jobs.Add(new SerializableJob(100, "str")); else jobs.Add(new BinarizableJob(100, "str")); return jobs; } /** <inheritDoc /> */ override public bool Reduce(IList<IComputeJobResult<bool>> results) { Assert.AreEqual(1, results.Count); Assert.IsTrue(results[0].Data); return true; } } /// <summary> /// Test job. /// </summary> [Serializable] public class NodeIdJob : IComputeJob<Guid> { [InstanceResource] private IIgnite _grid = null; /** <inheritDoc /> */ public Guid Execute() { Assert.NotNull(_grid); return _grid.GetCluster().GetLocalNode().Id; } /** <inheritDoc /> */ public void Cancel() { // No-op. } } /// <summary> /// Test serializable job. /// </summary> [Serializable] public class SerializableJob : ComputeJobAdapter<bool> { [InstanceResource] private IIgnite _grid = null; public SerializableJob(params object[] args) : base(args) { // No-op. } /** <inheritDoc /> */ override public bool Execute() { Assert.IsFalse(IsCancelled()); Cancel(); Assert.IsTrue(IsCancelled()); Assert.NotNull(_grid); int arg1 = GetArgument<int>(0); Assert.AreEqual(100, arg1); string arg2 = GetArgument<string>(1); Assert.AreEqual("str", arg2); return true; } } /// <summary> /// Test binary job. /// </summary> public class BinarizableJob : ComputeJobAdapter<bool> { [InstanceResource] private IIgnite _grid; public BinarizableJob(params object[] args) : base(args) { // No-op. } /** <inheritDoc /> */ override public bool Execute() { Assert.IsFalse(IsCancelled()); Cancel(); Assert.IsTrue(IsCancelled()); Assert.NotNull(_grid); int arg1 = GetArgument<int>(0); Assert.AreEqual(100, arg1); string arg2 = GetArgument<string>(1); Assert.AreEqual("str", arg2); return true; } } } }
#define IOS_ID using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; #if UNITY_EDITOR using UnityEditor; #endif namespace GameAnalyticsSDK { /// <summary> /// The Settings object contains an array of options which allows you to customize your use of GameAnalytics. Most importantly you will need to fill in your Game Key and Secret Key on the Settings object to use the service. /// </summary> /// public class Settings : ScriptableObject { /// <summary> /// Types of help given in the help box of the GA inspector /// </summary> public enum HelpTypes { None, IncludeSystemSpecsHelp, ProvideCustomUserID} ; public enum MessageTypes { None, Error, Info, Warning} ; /// <summary> /// A message and message type for the help box displayed on the GUI inspector /// </summary> public struct HelpInfo { public string Message; public MessageTypes MsgType; public HelpTypes HelpType; } #region public static values /// <summary> /// The version of the GA Unity Wrapper plugin /// </summary> [HideInInspector] public static string VERSION = "2.4.2"; #endregion #region public values public int TotalMessagesSubmitted; public int TotalMessagesFailed; public int DesignMessagesSubmitted; public int DesignMessagesFailed; public int QualityMessagesSubmitted; public int QualityMessagesFailed; public int ErrorMessagesSubmitted; public int ErrorMessagesFailed; public int BusinessMessagesSubmitted; public int BusinessMessagesFailed; public int UserMessagesSubmitted; public int UserMessagesFailed; public string CustomArea = string.Empty; [SerializeField] private string[] gameKey = CreateStringArrayWithEmptyStrings(NumberOfPlatforms); [SerializeField] private string[] secretKey = CreateStringArrayWithEmptyStrings(NumberOfPlatforms); [SerializeField] public string[] Build = CreateStringArrayWithPlatformStrings(NumberOfPlatforms); [SerializeField] public string[] SelectedPlatformStudio = CreateStringArrayWithEmptyStrings(NumberOfPlatforms); [SerializeField] public string[] SelectedPlatformGame = CreateStringArrayWithEmptyStrings(NumberOfPlatforms); [SerializeField] public int[] SelectedPlatformGameID = CreateIntArrayWithIDs(NumberOfPlatforms, -1); [SerializeField] public int[] SelectedStudio = CreateIntArrayWithIDs(NumberOfPlatforms, 0); [SerializeField] public int[] SelectedGame = CreateIntArrayWithIDs(NumberOfPlatforms, 0); public string NewVersion = ""; public string Changes = ""; public bool SignUpOpen = true; public string FirstName = ""; public string LastName = ""; public string StudioName = ""; public string GameName = ""; public string PasswordConfirm = ""; public bool EmailOptIn = true; public string EmailGA = ""; [System.NonSerialized] public string PasswordGA = ""; [System.NonSerialized] public string TokenGA = ""; [System.NonSerialized] public string ExpireTime = ""; [System.NonSerialized] public string LoginStatus = "Not logged in."; [System.NonSerialized] public bool JustSignedUp = false; [System.NonSerialized] public bool HideSignupWarning = false; public bool IntroScreen = true; [System.NonSerialized] public List<Studio> Studios; public bool InfoLogEditor = true; public bool InfoLogBuild = true; public bool VerboseLogBuild = false; public bool SendExampleGameDataToMyGame = false; //public bool UseBundleVersion = false; public bool InternetConnectivity; public List<string> CustomDimensions01 = new List<string>(); public List<string> CustomDimensions02 = new List<string>(); public List<string> CustomDimensions03 = new List<string>(); public List<string> ResourceItemTypes = new List<string>(); public List<string> ResourceCurrencies = new List<string>(); public GAPlatform LastCreatedGamePlatform; //These values are used for the GA_Inspector only public enum InspectorStates { Account, Basic, Debugging, Pref } private static string[] CreateStringArrayWithEmptyStrings(int size) { string[] result = new string[size]; for(int i = 0; i < size; ++i) { result[i] = ""; } return result; } private static string[] CreateStringArrayWithPlatformStrings(int size) { string[] result = new string[size]; for(int i = 0; i < size; ++i) { result[i] = "1.0"; } return result; } private static int[] CreateIntArrayWithIDs(int size, int value) { int[] result = new int[size]; for(int i = 0; i < size; ++i) { result[i] = value; } return result; } public InspectorStates CurrentInspectorState; public List<HelpTypes> ClosedHints = new List<HelpTypes>(); public bool DisplayHints; public Vector2 DisplayHintsScrollState; public Texture2D Logo; public Texture2D UpdateIcon; public Texture2D InfoIcon; public Texture2D DeleteIcon; public Texture2D GameIcon; public Texture2D HomeIcon; public Texture2D InstrumentIcon; public Texture2D QuestionIcon; public Texture2D UserIcon; public Texture2D AmazonIcon; public Texture2D GooglePlayIcon; public Texture2D iosIcon; public Texture2D macIcon; public Texture2D windowsPhoneIcon; [System.NonSerialized] public GUIStyle SignupButton; public bool SubmitErrors = true; public int MaxErrorCount = 10; public bool SubmitFpsAverage = true; public bool SubmitFpsCritical = true; public int FpsCriticalThreshold = 20; public int FpsCirticalSubmitInterval = 1; public bool[] PlatformFoldOut = new bool[NumberOfPlatforms]; public bool CustomDimensions01FoldOut = false; public bool CustomDimensions02FoldOut = false; public bool CustomDimensions03FoldOut = false; public bool ResourceItemTypesFoldOut = false; public bool ResourceCurrenciesFoldOut = false; private const int NumberOfPlatforms = 2; #endregion #region public methods /// <summary> /// Sets a custom user ID. /// Make sure each user has a unique user ID. This is useful if you have your own log-in system with unique user IDs. /// NOTE: Only use this method if you have enabled "Custom User ID" on the GA inspector! /// </summary> /// <param name="customID"> /// The custom user ID - this should be unique for each user /// </param> public void SetCustomUserID(string customID) { if(customID != string.Empty) { // Set custom ID native } } public bool IsGameKeyValid(int index, string value) { bool valid = true; for(int i = 0; i < NumberOfPlatforms; ++i) { if(index != i) { if(value.Equals(this.gameKey[i])) { valid = false; break; } } } return valid; } public bool IsSecretKeyValid(int index, string value) { bool valid = true; for(int i = 0; i < NumberOfPlatforms; ++i) { if(index != i) { if(value.Equals(this.secretKey[i])) { valid = false; break; } } } return valid; } public void UpdateGameKey(int index, string value) { if(!string.IsNullOrEmpty(value)) { bool valid = this.IsGameKeyValid(index, value); if(valid) { this.gameKey[index] = value; } else if(this.gameKey[index].Equals(value)) { this.gameKey[index] = ""; } } else { this.gameKey[index] = value; } } public void UpdateSecretKey(int index, string value) { if(!string.IsNullOrEmpty(value)) { bool valid = this.IsSecretKeyValid(index, value); if(valid) { this.secretKey[index] = value; } else if(this.secretKey[index].Equals(value)) { this.secretKey[index] = ""; } } else { this.secretKey[index] = value; } } public string GetGameKey(int index) { return this.gameKey[index]; } public string GetSecretKey(int index) { return this.secretKey[index]; } /// <summary> /// Sets a custom area string. An area is often just a level, but you can set it to whatever makes sense for your game. F.x. in a big open world game you will probably need custom areas to identify regions etc. /// By default, if no custom area is set, the Application.loadedLevelName string is used. /// </summary> /// <param name="customID"> /// The custom area. /// </param> public void SetCustomArea(string customArea) { // Set custom area native } public void SetKeys(string gamekey, string secretkey) { // set keys native } #endregion } //[System.Serializable] public class Studio { public string Name { get; private set; } public string ID { get; private set; } //[SerializeField] public List<Game> Games { get; private set; } public Studio(string name, string id, List<Game> games) { Name = name; ID = id; Games = games; } public static string[] GetStudioNames(List<Studio> studios, bool addFirstEmpty = true) { if(studios == null) { return new string[] { "-" }; } if(addFirstEmpty) { string[] names = new string[studios.Count + 1]; names[0] = "-"; string spaceAdd = ""; for(int i = 0; i < studios.Count; i++) { names[i + 1] = studios[i].Name + spaceAdd; spaceAdd += " "; } return names; } else { string[] names = new string[studios.Count]; string spaceAdd = ""; for(int i = 0; i < studios.Count; i++) { names[i] = studios[i].Name + spaceAdd; spaceAdd += " "; } return names; } } public static string[] GetGameNames(int index, List<Studio> studios) { if(studios == null || studios[index].Games == null) { return new string[] { "-" }; } string[] names = new string[studios[index].Games.Count + 1]; names[0] = "-"; string spaceAdd = ""; for(int i = 0; i < studios[index].Games.Count; i++) { names[i + 1] = studios[index].Games[i].Name + spaceAdd; spaceAdd += " "; } return names; } } public class Game { public string Name { get; private set; } public int ID { get; private set; } public string GameKey { get; private set; } public string SecretKey { get; private set; } public Game(string name, int id, string gameKey, string secretKey) { Name = name; ID = id; GameKey = gameKey; SecretKey = secretKey; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.InteropServices; using System.Text; namespace System.Security.Principal { // // Identifier authorities // internal enum IdentifierAuthority : long { NullAuthority = 0, WorldAuthority = 1, LocalAuthority = 2, CreatorAuthority = 3, NonUniqueAuthority = 4, NTAuthority = 5, SiteServerAuthority = 6, InternetSiteAuthority = 7, ExchangeAuthority = 8, ResourceManagerAuthority = 9, } // // SID name usage // internal enum SidNameUse { User = 1, Group = 2, Domain = 3, Alias = 4, WellKnownGroup = 5, DeletedAccount = 6, Invalid = 7, Unknown = 8, Computer = 9, } // // Well-known SID types // public enum WellKnownSidType { NullSid = 0, WorldSid = 1, LocalSid = 2, CreatorOwnerSid = 3, CreatorGroupSid = 4, CreatorOwnerServerSid = 5, CreatorGroupServerSid = 6, NTAuthoritySid = 7, DialupSid = 8, NetworkSid = 9, BatchSid = 10, InteractiveSid = 11, ServiceSid = 12, AnonymousSid = 13, ProxySid = 14, EnterpriseControllersSid = 15, SelfSid = 16, AuthenticatedUserSid = 17, RestrictedCodeSid = 18, TerminalServerSid = 19, RemoteLogonIdSid = 20, LogonIdsSid = 21, LocalSystemSid = 22, LocalServiceSid = 23, NetworkServiceSid = 24, BuiltinDomainSid = 25, BuiltinAdministratorsSid = 26, BuiltinUsersSid = 27, BuiltinGuestsSid = 28, BuiltinPowerUsersSid = 29, BuiltinAccountOperatorsSid = 30, BuiltinSystemOperatorsSid = 31, BuiltinPrintOperatorsSid = 32, BuiltinBackupOperatorsSid = 33, BuiltinReplicatorSid = 34, BuiltinPreWindows2000CompatibleAccessSid = 35, BuiltinRemoteDesktopUsersSid = 36, BuiltinNetworkConfigurationOperatorsSid = 37, AccountAdministratorSid = 38, AccountGuestSid = 39, AccountKrbtgtSid = 40, AccountDomainAdminsSid = 41, AccountDomainUsersSid = 42, AccountDomainGuestsSid = 43, AccountComputersSid = 44, AccountControllersSid = 45, AccountCertAdminsSid = 46, AccountSchemaAdminsSid = 47, AccountEnterpriseAdminsSid = 48, AccountPolicyAdminsSid = 49, AccountRasAndIasServersSid = 50, NtlmAuthenticationSid = 51, DigestAuthenticationSid = 52, SChannelAuthenticationSid = 53, ThisOrganizationSid = 54, OtherOrganizationSid = 55, BuiltinIncomingForestTrustBuildersSid = 56, BuiltinPerformanceMonitoringUsersSid = 57, BuiltinPerformanceLoggingUsersSid = 58, BuiltinAuthorizationAccessSid = 59, WinBuiltinTerminalServerLicenseServersSid = 60, MaxDefined = WinBuiltinTerminalServerLicenseServersSid, } // // This class implements revision 1 SIDs // NOTE: The SecurityIdentifier class is immutable and must remain this way // public sealed class SecurityIdentifier : IdentityReference, IComparable<SecurityIdentifier> { #region Public Constants // // Identifier authority must be at most six bytes long // internal static readonly long MaxIdentifierAuthority = 0xFFFFFFFFFFFF; // // Maximum number of subauthorities in a SID // internal static readonly byte MaxSubAuthorities = 15; // // Minimum length of a binary representation of a SID // public static readonly int MinBinaryLength = 1 + 1 + 6; // Revision (1) + subauth count (1) + identifier authority (6) // // Maximum length of a binary representation of a SID // public static readonly int MaxBinaryLength = 1 + 1 + 6 + MaxSubAuthorities * 4; // 4 bytes for each subauth #endregion #region Private Members // // Immutable properties of a SID // private IdentifierAuthority _identifierAuthority; private int[] _subAuthorities; private byte[] _binaryForm; private SecurityIdentifier _accountDomainSid; private bool _accountDomainSidInitialized = false; // // Computed attributes of a SID // private string _sddlForm = null; #endregion #region Constructors // // Shared constructor logic // NOTE: subauthorities are really unsigned integers, but due to CLS // lack of support for unsigned integers the caller must perform // the typecast // private void CreateFromParts(IdentifierAuthority identifierAuthority, int[] subAuthorities) { if (subAuthorities == null) { throw new ArgumentNullException(nameof(subAuthorities)); } Contract.EndContractBlock(); // // Check the number of subauthorities passed in // if (subAuthorities.Length > MaxSubAuthorities) { throw new ArgumentOutOfRangeException( "subAuthorities.Length", subAuthorities.Length, SR.Format(SR.IdentityReference_InvalidNumberOfSubauthorities, MaxSubAuthorities)); } // // Identifier authority is at most 6 bytes long // if (identifierAuthority < 0 || (long)identifierAuthority > MaxIdentifierAuthority) { throw new ArgumentOutOfRangeException( nameof(identifierAuthority), identifierAuthority, SR.IdentityReference_IdentifierAuthorityTooLarge); } // // Create a local copy of the data passed in // _identifierAuthority = identifierAuthority; _subAuthorities = new int[subAuthorities.Length]; subAuthorities.CopyTo(_subAuthorities, 0); // // Compute and store the binary form // // typedef struct _SID { // UCHAR Revision; // UCHAR SubAuthorityCount; // SID_IDENTIFIER_AUTHORITY IdentifierAuthority; // ULONG SubAuthority[ANYSIZE_ARRAY] // } SID, *PISID; // byte i; _binaryForm = new byte[1 + 1 + 6 + 4 * this.SubAuthorityCount]; // // First two bytes contain revision and subauthority count // _binaryForm[0] = Revision; _binaryForm[1] = (byte)this.SubAuthorityCount; // // Identifier authority takes up 6 bytes // for (i = 0; i < 6; i++) { _binaryForm[2 + i] = (byte)((((ulong)_identifierAuthority) >> ((5 - i) * 8)) & 0xFF); } // // Subauthorities go last, preserving big-endian representation // for (i = 0; i < this.SubAuthorityCount; i++) { byte shift; for (shift = 0; shift < 4; shift += 1) { _binaryForm[8 + 4 * i + shift] = (byte)(((ulong)_subAuthorities[i]) >> (shift * 8)); } } } private void CreateFromBinaryForm(byte[] binaryForm, int offset) { // // Give us something to work with // if (binaryForm == null) { throw new ArgumentNullException(nameof(binaryForm)); } // // Negative offsets are not allowed // if (offset < 0) { throw new ArgumentOutOfRangeException( nameof(offset), offset, SR.ArgumentOutOfRange_NeedNonNegNum); } // // At least a minimum-size SID should fit in the buffer // if (binaryForm.Length - offset < SecurityIdentifier.MinBinaryLength) { throw new ArgumentOutOfRangeException( nameof(binaryForm), SR.ArgumentOutOfRange_ArrayTooSmall); } Contract.EndContractBlock(); IdentifierAuthority Authority; int[] SubAuthorities; // // Extract the elements of a SID // if (binaryForm[offset] != Revision) { // // Revision is incorrect // throw new ArgumentException( SR.IdentityReference_InvalidSidRevision, nameof(binaryForm)); } // // Insist on the correct number of subauthorities // if (binaryForm[offset + 1] > MaxSubAuthorities) { throw new ArgumentException( SR.Format(SR.IdentityReference_InvalidNumberOfSubauthorities, MaxSubAuthorities), nameof(binaryForm)); } // // Make sure the buffer is big enough // int Length = 1 + 1 + 6 + 4 * binaryForm[offset + 1]; if (binaryForm.Length - offset < Length) { throw new ArgumentException( SR.ArgumentOutOfRange_ArrayTooSmall, nameof(binaryForm)); } Authority = (IdentifierAuthority)( (((long)binaryForm[offset + 2]) << 40) + (((long)binaryForm[offset + 3]) << 32) + (((long)binaryForm[offset + 4]) << 24) + (((long)binaryForm[offset + 5]) << 16) + (((long)binaryForm[offset + 6]) << 8) + (((long)binaryForm[offset + 7]))); SubAuthorities = new int[binaryForm[offset + 1]]; // // Subauthorities are represented in big-endian format // for (byte i = 0; i < binaryForm[offset + 1]; i++) { SubAuthorities[i] = (int)( (((uint)binaryForm[offset + 8 + 4 * i + 0]) << 0) + (((uint)binaryForm[offset + 8 + 4 * i + 1]) << 8) + (((uint)binaryForm[offset + 8 + 4 * i + 2]) << 16) + (((uint)binaryForm[offset + 8 + 4 * i + 3]) << 24)); } CreateFromParts(Authority, SubAuthorities); return; } // // Constructs a SecurityIdentifier object from its string representation // Returns 'null' if string passed in is not a valid SID // NOTE: although there is a P/Invoke call involved in the implementation of this method, // there is no security risk involved, so no security demand is being made. // public SecurityIdentifier(string sddlForm) { byte[] resultSid; // // Give us something to work with // if (sddlForm == null) { throw new ArgumentNullException(nameof(sddlForm)); } Contract.EndContractBlock(); // // Call into the underlying O/S conversion routine // int Error = Win32.CreateSidFromString(sddlForm, out resultSid); if (Error == Interop.mincore.Errors.ERROR_INVALID_SID) { throw new ArgumentException(SR.Argument_InvalidValue, nameof(sddlForm)); } else if (Error == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY) { throw new OutOfMemoryException(); } else if (Error != Interop.mincore.Errors.ERROR_SUCCESS) { Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.CreateSidFromString returned unrecognized error {0}", Error)); throw new Win32Exception(Error); } CreateFromBinaryForm(resultSid, 0); } // // Constructs a SecurityIdentifier object from its binary representation // public SecurityIdentifier(byte[] binaryForm, int offset) { CreateFromBinaryForm(binaryForm, offset); } // // Constructs a SecurityIdentifier object from an IntPtr // public SecurityIdentifier(IntPtr binaryForm) : this(binaryForm, true) { } internal SecurityIdentifier(IntPtr binaryForm, bool noDemand) : this(Win32.ConvertIntPtrSidToByteArraySid(binaryForm), 0) { } // // Constructs a well-known SID // The 'domainSid' parameter is optional and only used // by the well-known types that require it // NOTE: although there is a P/Invoke call involved in the implementation of this constructor, // there is no security risk involved, so no security demand is being made. // public SecurityIdentifier(WellKnownSidType sidType, SecurityIdentifier domainSid) { // // sidType must not be equal to LogonIdsSid // if (sidType == WellKnownSidType.LogonIdsSid) { throw new ArgumentException(SR.IdentityReference_CannotCreateLogonIdsSid, nameof(sidType)); } Contract.EndContractBlock(); byte[] resultSid; int Error; // // sidType should not exceed the max defined value // if ((sidType < WellKnownSidType.NullSid) || (sidType > WellKnownSidType.MaxDefined)) { throw new ArgumentException(SR.Argument_InvalidValue, nameof(sidType)); } // // for sidType between 38 to 50, the domainSid parameter must be specified // if ((sidType >= WellKnownSidType.AccountAdministratorSid) && (sidType <= WellKnownSidType.AccountRasAndIasServersSid)) { if (domainSid == null) { throw new ArgumentNullException(nameof(domainSid), SR.Format(SR.IdentityReference_DomainSidRequired, sidType)); } // // verify that the domain sid is a valid windows domain sid // to do that we call GetAccountDomainSid and the return value should be the same as the domainSid // SecurityIdentifier resultDomainSid; int ErrorCode; ErrorCode = Win32.GetWindowsAccountDomainSid(domainSid, out resultDomainSid); if (ErrorCode == Interop.mincore.Errors.ERROR_INSUFFICIENT_BUFFER) { throw new OutOfMemoryException(); } else if (ErrorCode == Interop.mincore.Errors.ERROR_NON_ACCOUNT_SID) { // this means that the domain sid is not valid throw new ArgumentException(SR.IdentityReference_NotAWindowsDomain, nameof(domainSid)); } else if (ErrorCode != Interop.mincore.Errors.ERROR_SUCCESS) { Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.GetWindowsAccountDomainSid returned unrecognized error {0}", ErrorCode)); throw new Win32Exception(ErrorCode); } // // if domainSid is passed in as S-1-5-21-3-4-5-6, the above api will return S-1-5-21-3-4-5 as the domainSid // Since these do not match S-1-5-21-3-4-5-6 is not a valid domainSid (wrong number of subauthorities) // if (resultDomainSid != domainSid) { throw new ArgumentException(SR.IdentityReference_NotAWindowsDomain, nameof(domainSid)); } } Error = Win32.CreateWellKnownSid(sidType, domainSid, out resultSid); if (Error == Interop.mincore.Errors.ERROR_INVALID_PARAMETER) { throw new ArgumentException(new Win32Exception(Error).Message, "sidType/domainSid"); } else if (Error != Interop.mincore.Errors.ERROR_SUCCESS) { Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.CreateWellKnownSid returned unrecognized error {0}", Error)); throw new Win32Exception(Error); } CreateFromBinaryForm(resultSid, 0); } internal SecurityIdentifier(SecurityIdentifier domainSid, uint rid) { int i; int[] SubAuthorities = new int[domainSid.SubAuthorityCount + 1]; for (i = 0; i < domainSid.SubAuthorityCount; i++) { SubAuthorities[i] = domainSid.GetSubAuthority(i); } SubAuthorities[i] = (int)rid; CreateFromParts(domainSid.IdentifierAuthority, SubAuthorities); } internal SecurityIdentifier(IdentifierAuthority identifierAuthority, int[] subAuthorities) { CreateFromParts(identifierAuthority, subAuthorities); } #endregion #region Static Properties // // Revision is always '1' // internal static byte Revision { get { return 1; } } #endregion #region Non-static Properties // // This is for internal consumption only, hence it is marked 'internal' // Making this call public would require a deep copy of the data to // prevent the caller from messing with the internal representation. // internal byte[] BinaryForm { get { return _binaryForm; } } internal IdentifierAuthority IdentifierAuthority { get { return _identifierAuthority; } } internal int SubAuthorityCount { get { return _subAuthorities.Length; } } public int BinaryLength { get { return _binaryForm.Length; } } // // Returns the domain portion of a SID or null if the specified // SID is not an account SID // NOTE: although there is a P/Invoke call involved in the implementation of this method, // there is no security risk involved, so no security demand is being made. // public SecurityIdentifier AccountDomainSid { get { if (!_accountDomainSidInitialized) { _accountDomainSid = GetAccountDomainSid(); _accountDomainSidInitialized = true; } return _accountDomainSid; } } #endregion #region Inherited properties and methods public override bool Equals(object o) { return (this == o as SecurityIdentifier); // invokes operator== } public bool Equals(SecurityIdentifier sid) { return (this == sid); // invokes operator== } public override int GetHashCode() { int hashCode = ((long)this.IdentifierAuthority).GetHashCode(); for (int i = 0; i < SubAuthorityCount; i++) { hashCode ^= this.GetSubAuthority(i); } return hashCode; } public override string ToString() { if (_sddlForm == null) { StringBuilder result = new StringBuilder(); // // Typecasting of _IdentifierAuthority to a long below is important, since // otherwise you would see this: "S-1-NTAuthority-32-544" // result.AppendFormat("S-1-{0}", (long)_identifierAuthority); for (int i = 0; i < SubAuthorityCount; i++) { result.AppendFormat("-{0}", (uint)(_subAuthorities[i])); } _sddlForm = result.ToString(); } return _sddlForm; } public override string Value { get { return ToString().ToUpperInvariant(); } } internal static bool IsValidTargetTypeStatic(Type targetType) { if (targetType == typeof(NTAccount)) { return true; } else if (targetType == typeof(SecurityIdentifier)) { return true; } else { return false; } } public override bool IsValidTargetType(Type targetType) { return IsValidTargetTypeStatic(targetType); } internal SecurityIdentifier GetAccountDomainSid() { SecurityIdentifier ResultSid; int Error; Error = Win32.GetWindowsAccountDomainSid(this, out ResultSid); if (Error == Interop.mincore.Errors.ERROR_INSUFFICIENT_BUFFER) { throw new OutOfMemoryException(); } else if (Error == Interop.mincore.Errors.ERROR_NON_ACCOUNT_SID) { ResultSid = null; } else if (Error != Interop.mincore.Errors.ERROR_SUCCESS) { Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.GetWindowsAccountDomainSid returned unrecognized error {0}", Error)); throw new Win32Exception(Error); } return ResultSid; } public bool IsAccountSid() { if (!_accountDomainSidInitialized) { _accountDomainSid = GetAccountDomainSid(); _accountDomainSidInitialized = true; } if (_accountDomainSid == null) { return false; } return true; } public override IdentityReference Translate(Type targetType) { if (targetType == null) { throw new ArgumentNullException(nameof(targetType)); } Contract.EndContractBlock(); if (targetType == typeof(SecurityIdentifier)) { return this; // assumes SecurityIdentifier objects are immutable } else if (targetType == typeof(NTAccount)) { IdentityReferenceCollection irSource = new IdentityReferenceCollection(1); irSource.Add(this); IdentityReferenceCollection irTarget; irTarget = SecurityIdentifier.Translate(irSource, targetType, true); return irTarget[0]; } else { throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, nameof(targetType)); } } #endregion #region Operators public static bool operator ==(SecurityIdentifier left, SecurityIdentifier right) { object l = left; object r = right; if (l == r) { return true; } else if (l == null || r == null) { return false; } else { return (left.CompareTo(right) == 0); } } public static bool operator !=(SecurityIdentifier left, SecurityIdentifier right) { return !(left == right); } #endregion #region IComparable implementation public int CompareTo(SecurityIdentifier sid) { if (sid == null) { throw new ArgumentNullException(nameof(sid)); } Contract.EndContractBlock(); if (this.IdentifierAuthority < sid.IdentifierAuthority) { return -1; } if (this.IdentifierAuthority > sid.IdentifierAuthority) { return 1; } if (this.SubAuthorityCount < sid.SubAuthorityCount) { return -1; } if (this.SubAuthorityCount > sid.SubAuthorityCount) { return 1; } for (int i = 0; i < this.SubAuthorityCount; i++) { int diff = this.GetSubAuthority(i) - sid.GetSubAuthority(i); if (diff != 0) { return diff; } } return 0; } #endregion #region Public Methods internal int GetSubAuthority(int index) { return _subAuthorities[index]; } // // Determines whether this SID is a well-known SID of the specified type // // NOTE: although there is a P/Invoke call involved in the implementation of this method, // there is no security risk involved, so no security demand is being made. // public bool IsWellKnown(WellKnownSidType type) { return Win32.IsWellKnownSid(this, type); } public void GetBinaryForm(byte[] binaryForm, int offset) { _binaryForm.CopyTo(binaryForm, offset); } // // NOTE: although there is a P/Invoke call involved in the implementation of this method, // there is no security risk involved, so no security demand is being made. // public bool IsEqualDomainSid(SecurityIdentifier sid) { return Win32.IsEqualDomainSid(this, sid); } private static IdentityReferenceCollection TranslateToNTAccounts(IdentityReferenceCollection sourceSids, out bool someFailed) { if (sourceSids == null) { throw new ArgumentNullException(nameof(sourceSids)); } if (sourceSids.Count == 0) { throw new ArgumentException(SR.Arg_EmptyCollection, nameof(sourceSids)); } Contract.EndContractBlock(); IntPtr[] SidArrayPtr = new IntPtr[sourceSids.Count]; GCHandle[] HandleArray = new GCHandle[sourceSids.Count]; SafeLsaPolicyHandle LsaHandle = SafeLsaPolicyHandle.InvalidHandle; SafeLsaMemoryHandle ReferencedDomainsPtr = SafeLsaMemoryHandle.InvalidHandle; SafeLsaMemoryHandle NamesPtr = SafeLsaMemoryHandle.InvalidHandle; try { // // Pin all elements in the array of SIDs // int currentSid = 0; foreach (IdentityReference id in sourceSids) { SecurityIdentifier sid = id as SecurityIdentifier; if (sid == null) { throw new ArgumentException(SR.Argument_ImproperType, nameof(sourceSids)); } HandleArray[currentSid] = GCHandle.Alloc(sid.BinaryForm, GCHandleType.Pinned); SidArrayPtr[currentSid] = HandleArray[currentSid].AddrOfPinnedObject(); currentSid++; } // // Open LSA policy (for lookup requires it) // LsaHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES); // // Perform the actual lookup // someFailed = false; uint ReturnCode; ReturnCode = Interop.mincore.LsaLookupSids(LsaHandle, sourceSids.Count, SidArrayPtr, ref ReferencedDomainsPtr, ref NamesPtr); // // Make a decision regarding whether it makes sense to proceed // based on the return code and the value of the forceSuccess argument // if (ReturnCode == Interop.StatusOptions.STATUS_NO_MEMORY || ReturnCode == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES) { throw new OutOfMemoryException(); } else if (ReturnCode == Interop.StatusOptions.STATUS_ACCESS_DENIED) { throw new UnauthorizedAccessException(); } else if (ReturnCode == Interop.StatusOptions.STATUS_NONE_MAPPED || ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED) { someFailed = true; } else if (ReturnCode != 0) { int win32ErrorCode = Interop.mincore.RtlNtStatusToDosError(unchecked((int)ReturnCode)); Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Interop.LsaLookupSids returned {0}", win32ErrorCode)); throw new Win32Exception(win32ErrorCode); } NamesPtr.Initialize((uint)sourceSids.Count, (uint)Marshal.SizeOf<Interop.LSA_TRANSLATED_NAME>()); Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr); // // Interpret the results and generate NTAccount objects // IdentityReferenceCollection Result = new IdentityReferenceCollection(sourceSids.Count); if (ReturnCode == 0 || ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED) { // // Interpret the results and generate NT Account objects // Interop.LSA_REFERENCED_DOMAIN_LIST rdl = ReferencedDomainsPtr.Read<Interop.LSA_REFERENCED_DOMAIN_LIST>(0); string[] ReferencedDomains = new string[rdl.Entries]; for (int i = 0; i < rdl.Entries; i++) { Interop.LSA_TRUST_INFORMATION ti = (Interop.LSA_TRUST_INFORMATION)Marshal.PtrToStructure<Interop.LSA_TRUST_INFORMATION>(new IntPtr((long)rdl.Domains + i * Marshal.SizeOf<Interop.LSA_TRUST_INFORMATION>())); ReferencedDomains[i] = Marshal.PtrToStringUni(ti.Name.Buffer, ti.Name.Length / sizeof(char)); } Interop.LSA_TRANSLATED_NAME[] translatedNames = new Interop.LSA_TRANSLATED_NAME[sourceSids.Count]; NamesPtr.ReadArray(0, translatedNames, 0, translatedNames.Length); for (int i = 0; i < sourceSids.Count; i++) { Interop.LSA_TRANSLATED_NAME Ltn = translatedNames[i]; switch ((SidNameUse)Ltn.Use) { case SidNameUse.User: case SidNameUse.Group: case SidNameUse.Alias: case SidNameUse.Computer: case SidNameUse.WellKnownGroup: string account = Marshal.PtrToStringUni(Ltn.Name.Buffer, Ltn.Name.Length / sizeof(char)); ; string domain = ReferencedDomains[Ltn.DomainIndex]; Result.Add(new NTAccount(domain, account)); break; default: someFailed = true; Result.Add(sourceSids[i]); break; } } } else { for (int i = 0; i < sourceSids.Count; i++) { Result.Add(sourceSids[i]); } } return Result; } finally { for (int i = 0; i < sourceSids.Count; i++) { if (HandleArray[i].IsAllocated) { HandleArray[i].Free(); } } LsaHandle.Dispose(); ReferencedDomainsPtr.Dispose(); NamesPtr.Dispose(); } } internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceSids, Type targetType, bool forceSuccess) { bool SomeFailed = false; IdentityReferenceCollection Result; Result = Translate(sourceSids, targetType, out SomeFailed); if (forceSuccess && SomeFailed) { IdentityReferenceCollection UnmappedIdentities = new IdentityReferenceCollection(); foreach (IdentityReference id in Result) { if (id.GetType() != targetType) { UnmappedIdentities.Add(id); } } throw new IdentityNotMappedException(SR.IdentityReference_IdentityNotMapped, UnmappedIdentities); } return Result; } internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceSids, Type targetType, out bool someFailed) { if (sourceSids == null) { throw new ArgumentNullException(nameof(sourceSids)); } Contract.EndContractBlock(); if (targetType == typeof(NTAccount)) { return TranslateToNTAccounts(sourceSids, out someFailed); } throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, nameof(targetType)); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace CH08___Input_Keyboard { public struct Bullet { // active = on-screen, not active = available to reuse public bool Active; // current location on the screen public Vector2 Location; // delta X and delta Y for this bullet public Vector2 Motion; // current image rotation angle (spinning bullets) public float Angle; } /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; // screen constants const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; // movement and rotation constants const float DELTA_ROTATE = 12.0f; const float DELTA_MOVE = 2.0f; // handy constant for sin and cos const double ToRadians = Math.PI / 180.0; // the only game texture Texture2D m_texGame; // individual game images Rectangle m_rectShip = new Rectangle(1, 1, 62, 62); Rectangle m_rectBullet = new Rectangle(65, 1, 62, 62); Rectangle m_rectGraph = new Rectangle(0, 64, 50, 50); // max num active bullets const int BULLET_MAX = 75; // frames to wait between shots const int BULLET_DELAY = 9; // number of frames until next shot can be fired int m_nBulletCountDown = 0; // array to track bullets Bullet[] m_Bullets = new Bullet[BULLET_MAX]; // top, left of first graph tile Vector2 m_GraphOrigin = Vector2.Zero; // center of the ship image Vector2 m_CenterShip = new Vector2(31, 31); // rotation of the ship float m_angle = 0.0f; // center of the bullet image Vector2 m_CenterBullet = new Vector2(31, 31); // center of the screen Vector2 m_CenterScreen = new Vector2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2); public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // use a fixed frame rate of 30 frames per second IsFixedTimeStep = true; TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 33); // init back buffer graphics.PreferredBackBufferHeight = SCREEN_HEIGHT; graphics.PreferredBackBufferWidth = SCREEN_WIDTH; graphics.PreferMultiSampling = false; graphics.ApplyChanges(); // init bullet array for (int i = 0; i < m_Bullets.Length; i++) { m_Bullets[i].Active = false; } base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); m_texGame = Content.Load<Texture2D>(@"media\game"); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // get keyboard state once per frame KeyboardState keyState = Keyboard.GetState(); // exit the game? if (keyState.IsKeyDown(Keys.Escape)) { this.Exit(); } // turn the ship? if (keyState.IsKeyDown(Keys.Left)) { TurnShip(-DELTA_ROTATE); } if (keyState.IsKeyDown(Keys.Right)) { TurnShip(DELTA_ROTATE); } // move the ship? float fMove = 0.0f; if (keyState.IsKeyDown(Keys.Down)) { fMove = DELTA_MOVE; } if (keyState.IsKeyDown(Keys.Up)) { fMove = -DELTA_MOVE; } MoveShip(fMove); // fire delay if (m_nBulletCountDown > 0) { m_nBulletCountDown--; } // fire bullet? if (keyState.IsKeyDown(Keys.Space)) { Shoot(); } base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { graphics.GraphicsDevice.Clear(Color.CornflowerBlue); // start drawing our images spriteBatch.Begin(); // draw game objects DrawBackground(spriteBatch); DrawBullets(spriteBatch); DrawShip(spriteBatch); // let batch know that we're done spriteBatch.End(); base.Draw(gameTime); } // fill screen with graph tile, offset by ship movement private void DrawBackground(SpriteBatch batch) { // round to nearest whole pixel float ox = (float)Math.Round(m_GraphOrigin.X); float oy = (float)Math.Round(m_GraphOrigin.Y); // temp variable used by batch.Draw() Vector2 v = Vector2.Zero; for (float y = oy; y < SCREEN_HEIGHT; y += 50) { // row by row v.Y = y; for (float x = ox; x < SCREEN_WIDTH; x += 50) { // column by column v.X = x; batch.Draw(m_texGame, v, m_rectGraph, Color.White); } } } // render each active bullet private void DrawBullets(SpriteBatch batch) { // scan entire list of bullets foreach (Bullet b in m_Bullets) { // only draw active bullets if (b.Active) { double angle = b.Angle * ToRadians; batch.Draw( m_texGame, // bullet texture b.Location, // bullet x, y m_rectBullet, // bullet source rect Color.White, // no tint (float)(angle), // bullet rotation m_CenterBullet, // center of bullet 1.0f, // don't scale SpriteEffects.None, // no effect 0.0f); // topmost layer } } } // render the ship, rotated private void DrawShip(SpriteBatch batch) { batch.Draw( m_texGame, // ship texture m_CenterScreen, // ship x, y m_rectShip, // ship source rect Color.White, // no tint (float)(m_angle * ToRadians), // ship rotation m_CenterShip, // center of ship 1.0f, // don't scale SpriteEffects.None, // no effect 0.0f); // topmost layer } // rotate the ship private void TurnShip(float delta) { m_angle += delta; } // move the ship (actually, move the world while // the ship stands still) private void MoveShip(float delta) { // distance to travel per frame, split into X and Y float dx = delta * (float)Math.Cos(m_angle * ToRadians); float dy = delta * (float)Math.Sin(m_angle * ToRadians); // update graph m_GraphOrigin.X += dx; m_GraphOrigin.Y += dy; // make sure x is between -50 and 0 while (m_GraphOrigin.X < -50) { m_GraphOrigin.X += 50.0f; } while (m_GraphOrigin.X > 0) { m_GraphOrigin.X -= 50.0f; } // make sure y is between -50 and 0 while (m_GraphOrigin.Y < -50) { m_GraphOrigin.Y += 50.0f; } while (m_GraphOrigin.Y > 0) { m_GraphOrigin.Y -= 50.0f; } UpdateBullets(dx, dy); } // update location of any active bullets private void UpdateBullets(float dxShip, float dyShip) { // for every bullet ... for (int i = 0; i < m_Bullets.Length; i++) { // only update active bullets if (m_Bullets[i].Active) { // see if the bullet has left the screen bool bDead = false; bDead = m_Bullets[i].Location.X < -64; bDead |= m_Bullets[i].Location.X > SCREEN_WIDTH + 64; bDead |= m_Bullets[i].Location.Y < -64; bDead |= m_Bullets[i].Location.Y > SCREEN_HEIGHT + 64; if (bDead) { // bullet is off-screen, mark for reuse m_Bullets[i].Active = false; } else { // move the bullet. since the ship is // stationary and the background moves, // be sure to account to recent ship // movements m_Bullets[i].Location.X += dxShip + m_Bullets[i].Motion.X; m_Bullets[i].Location.Y += dyShip + m_Bullets[i].Motion.Y; // rotate the bullet m_Bullets[i].Angle += 20.0f; } } } } // try to create a new on-screen bullet private void Shoot() { // make sure we don't inject too many bullets at once if (m_nBulletCountDown == 0) { // scan list of bullets for an available slot for (int i = 0; i < m_Bullets.Length; i++) { // can't use a bullet that's already on-screen if (!m_Bullets[i].Active) { // start at the center of the screen m_Bullets[i].Location = m_CenterScreen; // calc distance to travel per frame, // split into X and Y float dx = 3.0f * (float)Math.Cos(m_angle * ToRadians); float dy = 3.0f * (float)Math.Sin(m_angle * ToRadians); // set bullet into motion m_Bullets[i].Motion = new Vector2(dx, dy); // init rotation m_Bullets[i].Angle = 0.0f; // mark as active so we stop ignoring it m_Bullets[i].Active = true; // reset delay counter m_nBulletCountDown = BULLET_DELAY; // we're done, so exit the loop break; } } } } } }
// // MediaPlayer.cs // // Authors: // John Millikin <jmillikin@gmail.com> // Bertrand Lorentz <bertrand.lorentz@gmail.com> // // Copyright (C) 2009 John Millikin // Copyright (C) 2010 Bertrand Lorentz // // 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 NDesk.DBus; using Hyena; using Banshee.Gui; using Banshee.MediaEngine; using Banshee.PlaybackController; using Banshee.ServiceStack; namespace Banshee.Mpris { public class MediaPlayer : IMediaPlayer, IPlayer, IProperties { private static string mediaplayer_interface_name = "org.mpris.MediaPlayer2"; private static string player_interface_name = "org.mpris.MediaPlayer2.Player"; private PlaybackControllerService playback_service; private PlayerEngineService engine_service; private Dictionary<string, object> changed_properties; private List<string> invalidated_properties; private static ObjectPath path = new ObjectPath ("/org/mpris/MediaPlayer2"); public static ObjectPath Path { get { return path; } } private event PropertiesChangedHandler properties_changed; event PropertiesChangedHandler IProperties.PropertiesChanged { add { properties_changed += value; } remove { properties_changed -= value; } } private event DBusPlayerSeekedHandler dbus_seeked; event DBusPlayerSeekedHandler IPlayer.Seeked { add { dbus_seeked += value; } remove { dbus_seeked -= value; } } public MediaPlayer () { playback_service = ServiceManager.PlaybackController; engine_service = ServiceManager.PlayerEngine; changed_properties = new Dictionary<string, object> (); invalidated_properties = new List<string> (); } #region IMediaPlayer public bool CanQuit { get { return true; } } public bool CanRaise { get { return true; } } public bool HasTrackList { get { return false; } } public string Identity { get { return "Banshee"; } } public string DesktopEntry { get { return "banshee-1"; } } // This is just a list of commonly supported MIME types. // We don't know exactly which ones are supported by the PlayerEngine private static string [] supported_mimetypes = { "application/ogg", "audio/flac", "audio/mp3", "audio/mp4", "audio/mpeg", "audio/ogg", "audio/vorbis", "audio/wav", "audio/x-flac", "audio/x-vorbis+ogg", "video/avi", "video/mp4", "video/mpeg" }; public string [] SupportedMimeTypes { get { return supported_mimetypes; } } public string [] SupportedUriSchemes { get { return (string [])ServiceManager.PlayerEngine.ActiveEngine.SourceCapabilities; } } public void Raise () { if (!CanRaise) { return; } ServiceManager.Get<GtkElementsService> ().PrimaryWindow.SetVisible (true); } public void Quit () { if (!CanQuit) { return; } Application.Shutdown (); } #endregion #region IPlayer public bool CanControl { get { return true; } } // We don't really know if we can actually go next or previous public bool CanGoNext { get { return CanControl; } } public bool CanGoPrevious { get { return CanControl; } } public bool CanPause { get { return engine_service.CanPause; } } public bool CanPlay { get { return CanControl; } } public bool CanSeek { get { return engine_service.CanSeek; } } public double MaximumRate { get { return 1.0; } } public double MinimumRate { get { return 1.0; } } public double Rate { get { return 1.0; } set {} } public bool Shuffle { get { return !(playback_service.ShuffleMode == "off"); } set { playback_service.ShuffleMode = value ? "song" : "off"; } } public string LoopStatus { get { string loop_status; switch (playback_service.RepeatMode) { case PlaybackRepeatMode.None: loop_status = "None"; break; case PlaybackRepeatMode.RepeatSingle: loop_status = "Track"; break; case PlaybackRepeatMode.RepeatAll: loop_status = "Playlist"; break; default: loop_status = "None"; break; } return loop_status; } set { switch (value) { case "None": playback_service.RepeatMode = PlaybackRepeatMode.None; break; case "Track": playback_service.RepeatMode = PlaybackRepeatMode.RepeatSingle; break; case "Playlist": playback_service.RepeatMode = PlaybackRepeatMode.RepeatAll; break; } } } public string PlaybackStatus { get { string status; switch (engine_service.CurrentState) { case PlayerState.Playing: status = "Playing"; break; case PlayerState.Paused: status = "Paused"; break; default: status = "Stopped"; break; } return status; } } public IDictionary<string, object> Metadata { get { var metadata = new Metadata (playback_service.CurrentTrack); return metadata.DataStore; } } public double Volume { get { return engine_service.Volume / 100.0; } set { engine_service.Volume = (ushort)Math.Round (value * 100); } } // Position is expected in microseconds public long Position { get { return (long)engine_service.Position * 1000; } } public void Next () { playback_service.Next (); } public void Previous () { playback_service.Previous (); } public void Pause () { engine_service.Pause (); } public void PlayPause () { engine_service.TogglePlaying (); } public void Stop () { engine_service.Close (); } public void Play () { engine_service.Play (); } public void SetPosition (string trackid, long position) { if (!CanSeek) { return; } if (String.IsNullOrEmpty (trackid) || trackid != (string)Metadata["trackid"]) { return; } // position is in microseconds, we speak in milliseconds long position_ms = position / 1000; if (position_ms < 0 || position_ms > playback_service.CurrentTrack.Duration.TotalMilliseconds) { return; } engine_service.Position = (uint)position_ms; } public void Seek (long position) { if (!CanSeek) { return; } // position is in microseconds, relative to the current position and can be negative long new_pos = (int)engine_service.Position + (position / 1000); if (new_pos < 0) { engine_service.Position = 0; } else { engine_service.Position = (uint)new_pos; } } public void OpenUri (string uri) { engine_service.Open (new SafeUri (uri)); engine_service.Play (); } #endregion #region Signals public void HandlePropertiesChange () { PropertiesChangedHandler handler = properties_changed; if (handler != null) { lock (changed_properties) { // Properties that trigger this signal are all on the Player interface handler (player_interface_name, changed_properties, invalidated_properties.ToArray ()); changed_properties.Clear (); invalidated_properties.Clear (); } } } public void HandleSeek () { DBusPlayerSeekedHandler dbus_handler = dbus_seeked; if (dbus_handler != null) { dbus_handler (Position); } } public void AddPropertyChange (params PlayerProperties [] properties) { lock (changed_properties) { foreach (PlayerProperties prop in properties) { string prop_name = prop.ToString (); changed_properties[prop_name] = Get (player_interface_name, prop_name); } } // TODO We could check if a property really has changed and only fire the event in that case HandlePropertiesChange (); } #endregion #region Dbus.Properties private static string [] mediaplayer_properties = { "CanQuit", "CanRaise", "HasTrackList", "Identity", "DesktopEntry", "SupportedMimeTypes", "SupportedUriSchemes" }; private static string [] player_properties = { "CanControl", "CanGoNext", "CanGoPrevious", "CanPause", "CanPlay", "CanSeek", "LoopStatus", "MaximumRate", "Metadata", "MinimumRate", "PlaybackStatus", "Position", "Rate", "Shuffle", "Volume" }; public object Get (string interface_name, string propname) { if (interface_name == mediaplayer_interface_name) { switch (propname) { case "CanQuit": return CanQuit; case "CanRaise": return CanRaise; case "HasTrackList": return HasTrackList; case "Identity": return Identity; case "DesktopEntry": return DesktopEntry; case "SupportedMimeTypes": return SupportedMimeTypes; case "SupportedUriSchemes": return SupportedUriSchemes; default: return null; } } else if (interface_name == player_interface_name) { switch (propname) { case "CanControl": return CanControl; case "CanGoNext": return CanGoNext; case "CanGoPrevious": return CanGoPrevious; case "CanPause": return CanPause; case "CanPlay": return CanPlay; case "CanSeek": return CanSeek; case "MinimumRate": return MinimumRate; case "MaximumRate": return MaximumRate; case "Rate": return Rate; case "Shuffle": return Shuffle; case "LoopStatus": return LoopStatus; case "PlaybackStatus": return PlaybackStatus; case "Position": return Position; case "Metadata": return Metadata; case "Volume": return Volume; default: return null; } } else { return null; } } public void Set (string interface_name, string propname, object value) { // All writable properties are on the Player interface if (interface_name != player_interface_name) { return; } switch (propname) { case "LoopStatus": string s = value as string; if (!String.IsNullOrEmpty (s)) { LoopStatus = s; } break; case "Shuffle": if (value is bool) { Shuffle = (bool)value; } break; case "Volume": if (value is double) { Volume = (double)value; } break; } } public IDictionary<string, object> GetAll (string interface_name) { var props = new Dictionary<string, object> (); if (interface_name == mediaplayer_interface_name) { foreach (string prop in mediaplayer_properties) { props.Add (prop, Get (interface_name, prop)); } } else if (interface_name == player_interface_name) { foreach (string prop in player_properties) { props.Add (prop, Get (interface_name, prop)); } } return props; } } #endregion // Those are all the properties that can trigger the PropertiesChanged signal // The names must match exactly the names of the properties public enum PlayerProperties { CanControl, CanGoNext, CanGoPrevious, CanPause, CanPlay, CanSeek, MinimumRate, MaximumRate, Rate, Shuffle, LoopStatus, PlaybackStatus, Metadata, Volume } }
using System; using System.Data; using Epi.Data.Services; namespace Epi.Fields { public delegate void FieldSaveCompleteHandler(Field field); /// <summary> /// Field /// </summary> public abstract class Field : IField { #region Constructors /// <summary> /// Private constructor - cannot be used /// </summary> private Field() { } /// <summary> /// Instantiates a field /// </summary> /// <param name="view">The view that contains this field</param> public Field(View view) { this.view = view; } #endregion Constructors #region Events public event FieldSaveCompleteHandler FieldInsertComplete; public event FieldSaveCompleteHandler FieldUpdateComplete; #endregion #region Fields private string name = string.Empty; private int id; private string sourceTable; private Guid uniqueId = Guid.NewGuid(); /// <summary> /// The parent view of the field. /// </summary> protected View view; public static int fieldsWaitingToUpdate; private bool isVisible = true; private bool isEnabled = true; private bool isHighlighted = false; private bool isRequired = false; #endregion Fields #region Public Properties /// <summary> /// Returns the type of the field. /// </summary> public abstract MetaFieldType FieldType { get; } /// <summary> /// Returns the parent View /// </summary> /// <returns></returns> public View GetView() { return view; } /// <summary> /// Returns the parent View /// </summary> /// <returns></returns> public View View { get { return view; } set { view = value; } } /// <summary> /// Gets/sets the fields's Id. /// </summary> public int Id { get { return id; } set { id = value; } } /// <summary> /// Gets/sets the field name /// </summary> public string Name { get { return name; } set { name = value; } } /// <summary> /// Gets/sets the source of the field /// </summary> public string SourceTable { get { return sourceTable; } set { sourceTable = value; } } /// <summary> /// Gets/sets the id used to diffentiate between fields in metadata /// </summary> public Guid UniqueId { get { return uniqueId; } set { uniqueId = value; } } /// <summary> /// attribute to control enable property /// </summary> public bool IsEnabled { get { return this.isEnabled; } set { this.isEnabled = value; } } /// <summary> /// attribute to control visibility /// </summary> public bool IsVisible { get { return this.isVisible; } set { this.isVisible = value; } } /// <summary> /// attribute to control Highlighting /// </summary> public bool IsHighlighted { get { return this.isHighlighted; } set { this.isHighlighted = value; } } /// <summary> /// attribute to control whether the field is required /// </summary> public bool IsRequired { get { return this.isRequired; } set { this.isRequired = value; } } #endregion Public Properties #region Public Methods /// <summary> /// Shortcut for getting project instance. /// </summary> /// <returns>Current Epi Project object.</returns> public Project GetProject() { return this.GetView().GetProject(); } /// <summary> /// Returns the metadata provider for the project /// </summary> /// <returns>Metadata Provider object.</returns> public IMetadataProvider GetMetadata() { return GetProject().Metadata; } /// <summary> /// Populates the field object from the database row /// </summary> /// <param name="row">A row of data in <see cref="System.Data.DataTable"/>.</param> public virtual void LoadFromRow(DataRow row) { this.Id = (int)row[ColumnNames.FIELD_ID]; this.Name = row[ColumnNames.NAME].ToString(); this.SourceTable = row[ColumnNames.SOURCE_TABLE_NAME].ToString(); if (row["UniqueId"] is Guid) { uniqueId = (Guid)row["UniqueId"]; } } public virtual void AssignMembers(Object field) { (field as Field).Id = this.Id; (field as Field).Name = this.Name; (field as Field).SourceTable = this.SourceTable; (field as Field).uniqueId = this.uniqueId; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public virtual void Dispose() { } /// <summary> /// Saves the field to the database /// </summary> public virtual void SaveToDb() { if (Id == 0) { InsertField(); } else { throw new System.ApplicationException("Can't update this field"); } } /// <summary> /// Deletes the field from the view /// </summary> public abstract void Delete(); #endregion Public Methods #region Protected Methods /// <summary> /// Executes when a field is inserted into the view. /// </summary> protected void OnFieldAdded() { view.MustRefreshFieldCollection = true; } /// <summary> /// Inserts the field to the database /// </summary> protected abstract void InsertField(); protected void OnFieldInserted(Field f) { if (FieldInsertComplete != null) { FieldInsertComplete(f); } } protected void OnFieldUpdated(Field f) { if (FieldUpdateComplete != null) { FieldUpdateComplete(f); } } #endregion Protected Methods } }
using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security.Cryptography; using ToolKit.Validation; namespace ToolKit.Cryptography { /// <summary> /// Symmetric-key algorithms are a class of algorithms for cryptography that use trivially /// related, often identical, cryptographic keys for both decryption and encryption. The /// encryption key is trivially related to the decryption key, in that they may be identical or /// there is a simple transformation to go between the two keys. The keys, in practice, /// represent a shared secret between two or more parties that can be used to maintain a private /// information link. /// </summary> [SuppressMessage( "StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Encryption tend to have names not in standard dictionaries...")] public class SymmetricEncryption : DisposableObject { private readonly int _bufferSize = 2048; private readonly SymmetricAlgorithm _crypto; private EncryptionData _initializationVector; private EncryptionData _key; /// <summary> /// Initializes a new instance of the <see cref="SymmetricEncryption" /> class using the /// specified provider. /// </summary> /// <param name="provider">The cryptographic provider.</param> [SuppressMessage( "Security", "CA5350:Do Not Use Weak Cryptographic Algorithms", Justification = "While I wouldn't use weak algorithms, I don't want to break backward-compatibility.")] public SymmetricEncryption(Provider provider) { switch (provider) { case Provider.Rijndael: _crypto = new RijndaelManaged(); break; case Provider.TripleDES: _crypto = new TripleDESCryptoServiceProvider(); break; default: throw new ArgumentException("Invalid Provider Provided!"); } // Ensure that any IV or key can be used regardless of length _crypto.Padding = PaddingMode.Zeros; // Make sure key and IV are always set, no matter what Key = RandomKey(); InitializationVector = RandomInitializationVector(); } /// <summary> /// Prevents a default instance of the <see cref="SymmetricEncryption" /> class from being created. /// </summary> [ExcludeFromCodeCoverage] private SymmetricEncryption() { } /// <summary> /// Types of available symmetric encryption algorithms. Some are considered insecure as of /// 2011 due the small key sizes.. /// </summary> public enum Provider { /// <summary> /// The Rijndael (also known as AES) provider supports keys of 128, 192, or 256 bits /// with a default of 256 bits /// </summary> // ReSharper disable once IdentifierTypo Rijndael, /// <summary> /// The TripleDES provider (also known as 3DES) supports keys of 128 or 192 bits with a /// default of 192 bits /// </summary> // ReSharper disable once InconsistentNaming TripleDES } /// <summary> /// Gets or sets the initialization vector. /// </summary> /// <value>The initialization vector.</value> /// <remark> /// Using the default Cipher Block Chaining (CBC) mode, all data blocks are processed using /// the value derived from the previous block; the first data block has no previous data /// block to use, so it needs an InitializationVector to feed the first block. /// </remark> public EncryptionData InitializationVector { get => _initializationVector; set { _initializationVector = value; _initializationVector.MaximumBytes = _crypto.BlockSize / 8; _initializationVector.MinimumBytes = _crypto.BlockSize / 8; } } /// <summary> /// Gets or sets the key used to encrypt/decrypt data. /// </summary> public EncryptionData Key { get => _key; set { _key = value; _key.MaximumBytes = _crypto.LegalKeySizes[0].MaxSize / 8; _key.MinimumBytes = _crypto.LegalKeySizes[0].MinSize / 8; } } /// <summary> /// Gets or sets the key size in bits. We use the default key size for any given provider; /// if you want to force a specific key size, set this property. /// </summary> public int KeySizeBits { get => _crypto.KeySize; set { _crypto.KeySize = value; _key.MaximumBits = value; } } /// <summary> /// Gets or sets the key size in bytes. We use the default key size for any given provider; /// if you want to force a specific key size, set this property. /// </summary> public int KeySizeBytes { get => _crypto.KeySize / 8; set { _crypto.KeySize = value * 8; _key.MaximumBytes = value; } } /// <summary> /// Decrypts the specified data using provided key and preset initialization vector. /// </summary> /// <param name="encryptedData">The encrypted data.</param> /// <param name="key">The encryption key used to preform the cryptographic function on.</param> /// <returns>the decrypted data.</returns> public EncryptionData Decrypt(EncryptionData encryptedData, EncryptionData key) { Key = key; return Decrypt(encryptedData); } /// <summary> /// Decrypts the specified data using provided key and preset initialization vector.. /// </summary> /// <param name="encryptedData">The encrypted data.</param> /// <param name="key">The encryption key used to preform the cryptographic function on.</param> /// <param name="iv">The initialization vector.</param> /// <returns>the decrypted data.</returns> public EncryptionData Decrypt(EncryptionData encryptedData, EncryptionData key, EncryptionData iv) { Key = key; InitializationVector = iv; return Decrypt(encryptedData); } /// <summary> /// Decrypts the specified data using preset key and preset initialization vector. /// </summary> /// <param name="encryptedData">The encrypted data.</param> /// <returns>the decrypted data.</returns> public EncryptionData Decrypt(EncryptionData encryptedData) { Check.NotNull(encryptedData, nameof(encryptedData)); _crypto.Key = _key.Bytes; _crypto.IV = _initializationVector.Bytes; using (var ms = new MemoryStream(encryptedData.Bytes, 0, encryptedData.Bytes.Length)) { var b = new byte[encryptedData.Bytes.Length]; var cs = new CryptoStream(ms, _crypto.CreateDecryptor(), CryptoStreamMode.Read); try { cs.Read(b, 0, encryptedData.Bytes.Length); } finally { cs.Close(); } return new EncryptionData(b); } } /// <summary> /// Decrypts the specified stream using provided key and preset initialization vector. /// </summary> /// <param name="encryptedStream">The encrypted stream.</param> /// <param name="key">The encryption key used to preform the cryptographic function on.</param> /// <param name="iv">The initialization vector.</param> /// <returns>the decrypted data.</returns> public EncryptionData Decrypt(Stream encryptedStream, EncryptionData key, EncryptionData iv) { Key = key; InitializationVector = iv; return Decrypt(encryptedStream); } /// <summary> /// Decrypts the specified stream using provided key and preset initialization vector. /// </summary> /// <param name="encryptedStream">The encrypted stream.</param> /// <param name="key">The encryption key used to preform the cryptographic function on.</param> /// <returns>the decrypted data.</returns> public EncryptionData Decrypt(Stream encryptedStream, EncryptionData key) { Key = key; return Decrypt(encryptedStream); } /// <summary> /// Decrypts the specified stream using preset key and preset initialization vector. /// </summary> /// <param name="encryptedStream">The encrypted stream.</param> /// <returns>the decrypted data.</returns> public EncryptionData Decrypt(Stream encryptedStream) { _crypto.Key = _key.Bytes; _crypto.IV = _initializationVector.Bytes; using (var ms = new MemoryStream()) { var b = new byte[_bufferSize + 1]; using (var cs = new CryptoStream( encryptedStream, _crypto.CreateDecryptor(), CryptoStreamMode.Read)) { var i = cs.Read(b, 0, _bufferSize); while (i > 0) { ms.Write(b, 0, i); i = cs.Read(b, 0, _bufferSize); } cs.Close(); } ms.Close(); return new EncryptionData(ms.ToArray()); } } /// <summary> /// Encrypts the specified Data using provided key. /// </summary> /// <param name="d">The data to encrypt.</param> /// <param name="key">The encryption key used to preform the cryptographic function on.</param> /// <returns>the encrypted data.</returns> public EncryptionData Encrypt(EncryptionData d, EncryptionData key) { Key = key; return Encrypt(d); } /// <summary> /// Encrypts the specified Data using preset key and preset initialization vector. /// </summary> /// <param name="d">The data to encrypt.</param> /// <returns>the encrypted data.</returns> public EncryptionData Encrypt(EncryptionData d) { Check.NotNull(d, nameof(d)); _crypto.Key = _key.Bytes; _crypto.IV = _initializationVector.Bytes; using (var ms = new MemoryStream()) { var cs = new CryptoStream(ms, _crypto.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(d.Bytes, 0, d.Bytes.Length); cs.Close(); ms.Close(); return new EncryptionData(ms.ToArray()); } } /// <summary> /// Encrypts the specified Data using provided key and provided initialization vector. /// </summary> /// <param name="d">The data to encrypt.</param> /// <param name="key">The encryption key used to preform the cryptographic function on.</param> /// <param name="iv">The initialization vector.</param> /// <returns>the encrypted data.</returns> public EncryptionData Encrypt(EncryptionData d, EncryptionData key, EncryptionData iv) { InitializationVector = iv; Key = key; return Encrypt(d); } /// <summary> /// Encrypts the stream to memory using provided key and provided initialization vector. /// </summary> /// <param name="s">The stream to preform the cryptographic function on.</param> /// <param name="key">The encryption key used to preform the cryptographic function on.</param> /// <param name="iv">The initialization vector .</param> /// <returns>the encrypted data.</returns> public EncryptionData Encrypt(Stream s, EncryptionData key, EncryptionData iv) { InitializationVector = iv; Key = key; return Encrypt(s); } /// <summary> /// Encrypts the stream to memory using specified key. /// </summary> /// <param name="s">The stream to preform the cryptographic function on.</param> /// <param name="key">The encryption key used to preform the cryptographic function on.</param> /// <returns>the encrypted data.</returns> public EncryptionData Encrypt(Stream s, EncryptionData key) { Key = key; return Encrypt(s); } /// <summary> /// Encrypts the specified stream to memory using preset key and preset initialization vector. /// </summary> /// <param name="s">The stream to preform the cryptographic function on.</param> /// <returns>the encrypted data.</returns> public EncryptionData Encrypt(Stream s) { Check.NotNull(s, nameof(s)); _crypto.Key = _key.Bytes; _crypto.IV = _initializationVector.Bytes; using (var ms = new MemoryStream()) { var b = new byte[_bufferSize + 1]; var cs = new CryptoStream(ms, _crypto.CreateEncryptor(), CryptoStreamMode.Write); var i = s.Read(b, 0, _bufferSize); while (i > 0) { cs.Write(b, 0, i); i = s.Read(b, 0, _bufferSize); } cs.Close(); ms.Close(); return new EncryptionData(ms.ToArray()); } } /// <summary> /// Disposes the resources used by the inherited class. /// </summary> /// <param name="disposing"> /// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release /// only unmanaged resources. /// </param> protected override void DisposeResources(bool disposing) { _crypto?.Dispose(); } private EncryptionData RandomInitializationVector() { _crypto.GenerateIV(); return new EncryptionData(_crypto.IV); } private EncryptionData RandomKey() { _crypto.GenerateKey(); return new EncryptionData(_crypto.Key); } } }
// Copyright (C) 2014 dot42 // // Original filename: Android.Graphics.Drawable.Shapes.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Android.Graphics.Drawable.Shapes { /// <summary> /// <para>Defines a generic graphical "shape." Any Shape can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass it to a android.graphics.drawable.ShapeDrawable. </para> /// </summary> /// <java-name> /// android/graphics/drawable/shapes/Shape /// </java-name> [Dot42.DexImport("android/graphics/drawable/shapes/Shape", AccessFlags = 1057)] public abstract partial class Shape : global::Java.Lang.ICloneable /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public Shape() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the width of the Shape. </para> /// </summary> /// <java-name> /// getWidth /// </java-name> [Dot42.DexImport("getWidth", "()F", AccessFlags = 17)] public float GetWidth() /* MethodBuilder.Create */ { return default(float); } /// <summary> /// <para>Returns the height of the Shape. </para> /// </summary> /// <java-name> /// getHeight /// </java-name> [Dot42.DexImport("getHeight", "()F", AccessFlags = 17)] public float GetHeight() /* MethodBuilder.Create */ { return default(float); } /// <summary> /// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para> /// </summary> /// <java-name> /// draw /// </java-name> [Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1025)] public abstract void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */ ; /// <summary> /// <para>Resizes the dimensions of this shape. Must be called before draw(Canvas,Paint).</para><para></para> /// </summary> /// <java-name> /// resize /// </java-name> [Dot42.DexImport("resize", "(FF)V", AccessFlags = 17)] public void Resize(float width, float height) /* MethodBuilder.Create */ { } /// <summary> /// <para>Checks whether the Shape is opaque. Default impl returns true. Override if your subclass can be opaque.</para><para></para> /// </summary> /// <returns> /// <para>true if any part of the drawable is <b>not</b> opaque. </para> /// </returns> /// <java-name> /// hasAlpha /// </java-name> [Dot42.DexImport("hasAlpha", "()Z", AccessFlags = 1)] public virtual bool HasAlpha() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Callback method called when resize(float,float) is executed.</para><para></para> /// </summary> /// <java-name> /// onResize /// </java-name> [Dot42.DexImport("onResize", "(FF)V", AccessFlags = 4)] protected internal virtual void OnResize(float width, float height) /* MethodBuilder.Create */ { } /// <java-name> /// clone /// </java-name> [Dot42.DexImport("clone", "()Landroid/graphics/drawable/shapes/Shape;", AccessFlags = 1)] public virtual global::Android.Graphics.Drawable.Shapes.Shape Clone() /* MethodBuilder.Create */ { return default(global::Android.Graphics.Drawable.Shapes.Shape); } /// <summary> /// <para>Returns the width of the Shape. </para> /// </summary> /// <java-name> /// getWidth /// </java-name> public float Width { [Dot42.DexImport("getWidth", "()F", AccessFlags = 17)] get{ return GetWidth(); } } /// <summary> /// <para>Returns the height of the Shape. </para> /// </summary> /// <java-name> /// getHeight /// </java-name> public float Height { [Dot42.DexImport("getHeight", "()F", AccessFlags = 17)] get{ return GetHeight(); } } } /// <summary> /// <para>Defines a rectangle shape. The rectangle can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass the RectShape to a android.graphics.drawable.ShapeDrawable. </para> /// </summary> /// <java-name> /// android/graphics/drawable/shapes/RectShape /// </java-name> [Dot42.DexImport("android/graphics/drawable/shapes/RectShape", AccessFlags = 33)] public partial class RectShape : global::Android.Graphics.Drawable.Shapes.Shape /* scope: __dot42__ */ { /// <summary> /// <para>RectShape constructor. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public RectShape() /* MethodBuilder.Create */ { } /// <summary> /// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para> /// </summary> /// <java-name> /// draw /// </java-name> [Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1)] public override void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */ { } /// <summary> /// <para>Callback method called when resize(float,float) is executed.</para><para></para> /// </summary> /// <java-name> /// onResize /// </java-name> [Dot42.DexImport("onResize", "(FF)V", AccessFlags = 4)] protected internal override void OnResize(float width, float height) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the RectF that defines this rectangle's bounds. </para> /// </summary> /// <java-name> /// rect /// </java-name> [Dot42.DexImport("rect", "()Landroid/graphics/RectF;", AccessFlags = 20)] protected internal global::Android.Graphics.RectF Rect() /* MethodBuilder.Create */ { return default(global::Android.Graphics.RectF); } /// <java-name> /// clone /// </java-name> [Dot42.DexImport("clone", "()Landroid/graphics/drawable/shapes/RectShape;", AccessFlags = 1)] public new virtual global::Android.Graphics.Drawable.Shapes.RectShape Clone() /* MethodBuilder.Create */ { return default(global::Android.Graphics.Drawable.Shapes.RectShape); } } /// <summary> /// <para>Creates a rounded-corner rectangle. Optionally, an inset (rounded) rectangle can be included (to make a sort of "O" shape). The rounded rectangle can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass the RoundRectShape to a android.graphics.drawable.ShapeDrawable. </para> /// </summary> /// <java-name> /// android/graphics/drawable/shapes/RoundRectShape /// </java-name> [Dot42.DexImport("android/graphics/drawable/shapes/RoundRectShape", AccessFlags = 33)] public partial class RoundRectShape : global::Android.Graphics.Drawable.Shapes.RectShape /* scope: __dot42__ */ { /// <summary> /// <para>RoundRectShape constructor. Specifies an outer (round)rect and an optional inner (round)rect.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "([FLandroid/graphics/RectF;[F)V", AccessFlags = 1)] public RoundRectShape(float[] outerRadii, global::Android.Graphics.RectF inset, float[] innerRadii) /* MethodBuilder.Create */ { } /// <summary> /// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para> /// </summary> /// <java-name> /// draw /// </java-name> [Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1)] public override void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */ { } /// <summary> /// <para>Callback method called when resize(float,float) is executed.</para><para></para> /// </summary> /// <java-name> /// onResize /// </java-name> [Dot42.DexImport("onResize", "(FF)V", AccessFlags = 4)] protected internal override void OnResize(float width, float height) /* MethodBuilder.Create */ { } /// <java-name> /// clone /// </java-name> [Dot42.DexImport("clone", "()Landroid/graphics/drawable/shapes/RoundRectShape;", AccessFlags = 1)] public new virtual global::Android.Graphics.Drawable.Shapes.RoundRectShape Clone() /* MethodBuilder.Create */ { return default(global::Android.Graphics.Drawable.Shapes.RoundRectShape); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal RoundRectShape() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>Creates geometric paths, utilizing the android.graphics.Path class. The path can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass the PathShape to a android.graphics.drawable.ShapeDrawable. </para> /// </summary> /// <java-name> /// android/graphics/drawable/shapes/PathShape /// </java-name> [Dot42.DexImport("android/graphics/drawable/shapes/PathShape", AccessFlags = 33)] public partial class PathShape : global::Android.Graphics.Drawable.Shapes.Shape /* scope: __dot42__ */ { /// <summary> /// <para>PathShape constructor.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Landroid/graphics/Path;FF)V", AccessFlags = 1)] public PathShape(global::Android.Graphics.Path path, float stdWidth, float stdHeight) /* MethodBuilder.Create */ { } /// <summary> /// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para> /// </summary> /// <java-name> /// draw /// </java-name> [Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1)] public override void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */ { } /// <summary> /// <para>Callback method called when resize(float,float) is executed.</para><para></para> /// </summary> /// <java-name> /// onResize /// </java-name> [Dot42.DexImport("onResize", "(FF)V", AccessFlags = 4)] protected internal override void OnResize(float width, float height) /* MethodBuilder.Create */ { } /// <java-name> /// clone /// </java-name> [Dot42.DexImport("clone", "()Landroid/graphics/drawable/shapes/PathShape;", AccessFlags = 1)] public new virtual global::Android.Graphics.Drawable.Shapes.PathShape Clone() /* MethodBuilder.Create */ { return default(global::Android.Graphics.Drawable.Shapes.PathShape); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal PathShape() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>Defines an oval shape. The oval can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass the OvalShape to a android.graphics.drawable.ShapeDrawable. </para> /// </summary> /// <java-name> /// android/graphics/drawable/shapes/OvalShape /// </java-name> [Dot42.DexImport("android/graphics/drawable/shapes/OvalShape", AccessFlags = 33)] public partial class OvalShape : global::Android.Graphics.Drawable.Shapes.RectShape /* scope: __dot42__ */ { /// <summary> /// <para>OvalShape constructor. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public OvalShape() /* MethodBuilder.Create */ { } /// <summary> /// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para> /// </summary> /// <java-name> /// draw /// </java-name> [Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1)] public override void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Creates an arc shape. The arc shape starts at a specified angle and sweeps clockwise, drawing slices of pie. The arc can be drawn to a Canvas with its own draw() method, but more graphical control is available if you instead pass the ArcShape to a android.graphics.drawable.ShapeDrawable. </para> /// </summary> /// <java-name> /// android/graphics/drawable/shapes/ArcShape /// </java-name> [Dot42.DexImport("android/graphics/drawable/shapes/ArcShape", AccessFlags = 33)] public partial class ArcShape : global::Android.Graphics.Drawable.Shapes.RectShape /* scope: __dot42__ */ { /// <summary> /// <para>ArcShape constructor.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(FF)V", AccessFlags = 1)] public ArcShape(float startAngle, float sweepAngle) /* MethodBuilder.Create */ { } /// <summary> /// <para>Draw this shape into the provided Canvas, with the provided Paint. Before calling this, you must call resize(float,float).</para><para></para> /// </summary> /// <java-name> /// draw /// </java-name> [Dot42.DexImport("draw", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V", AccessFlags = 1)] public override void Draw(global::Android.Graphics.Canvas canvas, global::Android.Graphics.Paint paint) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ArcShape() /* TypeBuilder.AddDefaultConstructor */ { } } }
/* ==================================================================== 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.SS.Util { using System; using NPOI.SS.UserModel; using System.Collections.Generic; using System.Globalization; /** * For POI internal use only * * @author Josh Micich */ public class SSCellRange<K> : ICellRange<K> where K:ICell { private int _height; private int _width; private K[] _flattenedArray; private int _firstRow; private int _firstColumn; private SSCellRange(int firstRow, int firstColumn, int height, int width, K[] flattenedArray) { _firstRow = firstRow; _firstColumn = firstColumn; _height = height; _width = width; _flattenedArray = (K[])flattenedArray.Clone(); } public static SSCellRange<K> Create(int firstRow, int firstColumn, int height, int width, List<K> flattenedList, Type cellClass) { int nItems = flattenedList.Count; if (height * width != nItems) { throw new ArgumentException("Array size mismatch."); } K[] flattenedArray = (K[])Array.CreateInstance(cellClass, nItems); flattenedArray=flattenedList.ToArray(); return new SSCellRange<K>(firstRow, firstColumn, height, width, flattenedArray); } public K GetCell(int relativeRowIndex, int relativeColumnIndex) { if (relativeRowIndex < 0 || relativeRowIndex >= _height) { throw new IndexOutOfRangeException("Specified row " + relativeRowIndex + " is outside the allowable range (0.." + (_height - 1) + ")."); } if (relativeColumnIndex < 0 || relativeColumnIndex >= _width) { throw new IndexOutOfRangeException("Specified colummn " + relativeColumnIndex + " is outside the allowable range (0.." + (_width - 1) + ")."); } int flatIndex = _width * relativeRowIndex + relativeColumnIndex; return _flattenedArray[flatIndex]; } internal class ArrayIterator<D> :IEnumerator<D> { private D[] _array; private int _index; public ArrayIterator(D[] array) { _array = (D[])array.Clone(); _index = 0; } #region IEnumerator<D> Members public bool MoveNext() { return _index < _array.Length; } public void Remove() { throw new NotSupportedException("Cannot remove cells from this CellRange."); } public void Reset() { } public D Current { get { if (_index >= _array.Length) { throw new ArgumentNullException(_index.ToString(CultureInfo.CurrentCulture)); } return _array[_index++]; } } #endregion #region IDisposable Members public void Dispose() { //do nothing? } #endregion #region IEnumerator Members object System.Collections.IEnumerator.Current { get { return this.Current; } } #endregion } #region CellRange<K> Members public K TopLeftCell { get { return _flattenedArray[0]; } } public K[] FlattenedCells { get { return (K[])_flattenedArray.Clone(); } } public K[][] Cells { get { Type itemCls = _flattenedArray.GetType(); K[][] result = (K[][])Array.CreateInstance(itemCls, _height); itemCls = itemCls.GetElementType(); for (int r = _height - 1; r >= 0; r--) { K[] row = (K[])Array.CreateInstance(itemCls, _width); int flatIndex = _width * r; Array.Copy(_flattenedArray, flatIndex, row, 0, _width); } return result; } } public int Height { get { return _height; } } public int Width { get { return _width; } } public int Size { get { return _height * _width; } } public String ReferenceText { get { CellRangeAddress cra = new CellRangeAddress(_firstRow, _firstRow + _height - 1, _firstColumn, _firstColumn + _width - 1); return cra.FormatAsString(); } } #endregion #region IEnumerable<K> Members public IEnumerator<K> GetEnumerator() { return new ArrayIterator<K>(_flattenedArray); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new NotImplementedException(); } #endregion } }
using NadekoBot.Extensions; using NadekoBot.Modules.Searches.Common; using Newtonsoft.Json; using NLog; using StackExchange.Redis; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; namespace NadekoBot.Core.Services.Impl { public class RedisCache : IDataCache { private readonly Logger _log; public ConnectionMultiplexer Redis { get; } public IImageCache LocalImages { get; } public ILocalDataCache LocalData { get; } private readonly string _redisKey; private readonly EndPoint _redisEndpoint; public RedisCache(IBotCredentials creds, int shardId) { _log = LogManager.GetCurrentClassLogger(); var conf = ConfigurationOptions.Parse(creds.RedisOptions); Redis = ConnectionMultiplexer.Connect(conf); _redisEndpoint = Redis.GetEndPoints().First(); Redis.PreserveAsyncOrder = false; LocalImages = new RedisImagesCache(Redis, creds); LocalData = new RedisLocalDataCache(Redis, creds, shardId); _redisKey = creds.RedisKey(); } // things here so far don't need the bot id // because it's a good thing if different bots // which are hosted on the same PC // can re-use the same image/anime data public async Task<(bool Success, byte[] Data)> TryGetImageDataAsync(Uri key) { var _db = Redis.GetDatabase(); byte[] x = await _db.StringGetAsync("image_" + key).ConfigureAwait(false); return (x != null, x); } public Task SetImageDataAsync(Uri key, byte[] data) { var _db = Redis.GetDatabase(); return _db.StringSetAsync("image_" + key, data); } public async Task<(bool Success, string Data)> TryGetAnimeDataAsync(string key) { var _db = Redis.GetDatabase(); string x = await _db.StringGetAsync("anime_" + key).ConfigureAwait(false); return (x != null, x); } public Task SetAnimeDataAsync(string key, string data) { var _db = Redis.GetDatabase(); return _db.StringSetAsync("anime_" + key, data, expiry: TimeSpan.FromHours(3)); } public async Task<(bool Success, string Data)> TryGetNovelDataAsync(string key) { var _db = Redis.GetDatabase(); string x = await _db.StringGetAsync("novel_" + key).ConfigureAwait(false); return (x != null, x); } public Task SetNovelDataAsync(string key, string data) { var _db = Redis.GetDatabase(); return _db.StringSetAsync("novel_" + key, data, expiry: TimeSpan.FromHours(3)); } private readonly object timelyLock = new object(); public TimeSpan? AddTimelyClaim(ulong id, int period) { if (period == 0) return null; lock (timelyLock) { var time = TimeSpan.FromHours(period); var _db = Redis.GetDatabase(); if ((bool?)_db.StringGet($"{_redisKey}_timelyclaim_{id}") == null) { _db.StringSet($"{_redisKey}_timelyclaim_{id}", true, time); return null; } return _db.KeyTimeToLive($"{_redisKey}_timelyclaim_{id}"); } } public void RemoveAllTimelyClaims() { var server = Redis.GetServer(_redisEndpoint); var _db = Redis.GetDatabase(); foreach (var k in server.Keys(pattern: $"{_redisKey}_timelyclaim_*")) { _db.KeyDelete(k, CommandFlags.FireAndForget); } } public bool TryAddAffinityCooldown(ulong userId, out TimeSpan? time) { var _db = Redis.GetDatabase(); time = _db.KeyTimeToLive($"{_redisKey}_affinity_{userId}"); if (time == null) { time = TimeSpan.FromMinutes(30); _db.StringSet($"{_redisKey}_affinity_{userId}", true, time); return true; } return false; } public bool TryAddDivorceCooldown(ulong userId, out TimeSpan? time) { var _db = Redis.GetDatabase(); time = _db.KeyTimeToLive($"{_redisKey}_divorce_{userId}"); if (time == null) { time = TimeSpan.FromHours(6); _db.StringSet($"{_redisKey}_divorce_{userId}", true, time); return true; } return false; } public Task SetStreamDataAsync(string url, string data) { var _db = Redis.GetDatabase(); return _db.StringSetAsync($"{_redisKey}_stream_{url}", data, expiry: TimeSpan.FromHours(6)); } public bool TryGetStreamData(string url, out string dataStr) { var _db = Redis.GetDatabase(); dataStr = _db.StringGet($"{_redisKey}_stream_{url}"); return !string.IsNullOrWhiteSpace(dataStr); } public void SubscribeToStreamUpdates(Func<StreamResponse[], Task> onStreamsUpdated) { var _sub = Redis.GetSubscriber(); _sub.Subscribe($"{_redisKey}_stream_updates", (ch, msg) => { onStreamsUpdated(JsonConvert.DeserializeObject<StreamResponse[]>(msg)); }); } public Task PublishStreamUpdates(List<StreamResponse> newStatuses) { var _sub = Redis.GetSubscriber(); return _sub.PublishAsync($"{_redisKey}_stream_updates", JsonConvert.SerializeObject(newStatuses)); } public async Task<StreamResponse[]> GetAllStreamDataAsync() { await Task.Yield(); var server = Redis.GetServer(_redisEndpoint); var _db = Redis.GetDatabase(); List<RedisValue> dataStrs = new List<RedisValue>(); foreach (var k in server.Keys(pattern: $"{_redisKey}_stream_*")) { dataStrs.Add(_db.StringGet(k)); } return dataStrs .Select(x => JsonConvert.DeserializeObject<StreamResponse>(x)) .Where(x => !string.IsNullOrWhiteSpace(x.ApiUrl)) .ToArray(); } public Task ClearAllStreamData() { var server = Redis.GetServer(_redisEndpoint); var _db = Redis.GetDatabase(); return Task.WhenAll(server.Keys(pattern: $"{_redisKey}_stream_*") .Select(x => _db.KeyDeleteAsync(x, CommandFlags.FireAndForget))); } public TimeSpan? TryAddRatelimit(ulong id, string name, int expireIn) { var _db = Redis.GetDatabase(); if (_db.StringSet($"{_redisKey}_ratelimit_{id}_{name}", 0, // i don't use the value TimeSpan.FromSeconds(expireIn), When.NotExists)) { return null; } return _db.KeyTimeToLive($"{_redisKey}_ratelimit_{id}_{name}"); } public bool TryGetEconomy(out string data) { var _db = Redis.GetDatabase(); if ((data = _db.StringGet($"{_redisKey}_economy")) != null) { return true; } return false; } public void SetEconomy(string data) { var _db = Redis.GetDatabase(); _db.StringSet($"{_redisKey}_economy", data, expiry: TimeSpan.FromMinutes(3)); } public async Task<TOut> GetOrAddCachedDataAsync<TParam, TOut>(string key, Func<TParam, Task<TOut>> factory, TParam param, TimeSpan expiry) where TOut : class { var _db = Redis.GetDatabase(); RedisValue data = await _db.StringGetAsync(key).ConfigureAwait(false); if (!data.HasValue) { var obj = await factory(param).ConfigureAwait(false); if (obj == null) return default(TOut); await _db.StringSetAsync(key, JsonConvert.SerializeObject(obj), expiry: expiry).ConfigureAwait(false); return obj; } return (TOut)JsonConvert.DeserializeObject(data, typeof(TOut)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Concurrent; using System.Collections.Generic; using Xunit; namespace System.Linq.Parallel.Tests { public static class SelectSelectManyTests { [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Select_Unordered(int count) { IntegerRangeSet seen = new IntegerRangeSet(0, count); foreach (var p in UnorderedSources.Default(count).Select(x => KeyValuePair.Create(x, x * x))) { seen.Add(p.Key); Assert.Equal(p.Key * p.Key, p.Value); } seen.AssertComplete(); } [Fact] [OuterLoop] public static void Select_Unordered_Longrunning() { Select_Unordered(Sources.OuterLoopCount / 64); } [Theory] [MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))] public static void Select(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int seen = 0; foreach (var p in query.Select(x => KeyValuePair.Create(x, x * x))) { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key * p.Key, p.Value); } Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), new[] { 1024 * 4 }, MemberType = typeof(Sources))] public static void Select_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Select(labeled, count); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Select_Unordered_NotPipelined(int count) { IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.All(UnorderedSources.Default(count).Select(x => KeyValuePair.Create(x, x * x)).ToList(), p => { seen.Add(p.Key); Assert.Equal(p.Key * p.Key, p.Value); }); seen.AssertComplete(); } [Fact] [OuterLoop] public static void Select_Unordered_NotPipelined_Longrunning() { Select_Unordered_NotPipelined(Sources.OuterLoopCount / 64); } [Theory] [MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))] public static void Select_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int seen = 0; Assert.All(query.Select(x => KeyValuePair.Create(x, x * x)).ToList(), p => { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key * p.Key, p.Value); }); Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), new[] { 1024 * 4 }, MemberType = typeof(Sources))] public static void Select_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Select_NotPipelined(labeled, count); } // Uses an element's index to calculate an output value. If order preservation isn't // working, this would PROBABLY fail. Unfortunately, this isn't deterministic. But choosing // larger input sizes increases the probability that it will. [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Select_Indexed_Unordered(int count) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(0, count); foreach (var p in UnorderedSources.Default(count).Select((x, index) => KeyValuePair.Create(x, index))) { seen.Add(p.Key); Assert.Equal(p.Key, p.Value); } seen.AssertComplete(); } [Fact] [OuterLoop] public static void Select_Indexed_Unordered_Longrunning() { Select_Indexed_Unordered(Sources.OuterLoopCount / 64); } [Theory] [MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))] public static void Select_Indexed(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int seen = 0; foreach (var p in query.Select((x, index) => KeyValuePair.Create(x, index))) { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key, p.Value); } Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), new[] { 1024 * 4 }, MemberType = typeof(Sources))] public static void Select_Indexed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Select_Indexed(labeled, count); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Select_Indexed_Unordered_NotPipelined(int count) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.All(UnorderedSources.Default(count).Select((x, index) => KeyValuePair.Create(x, index)).ToList(), p => { seen.Add(p.Key); Assert.Equal(p.Key, p.Value); }); seen.AssertComplete(); } [Fact] [OuterLoop] public static void Select_Indexed_Unordered_NotPipelined_Longrunning() { Select_Indexed_Unordered_NotPipelined(Sources.OuterLoopCount / 64); } [Theory] [MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))] public static void Select_Indexed_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int seen = 0; Assert.All(query.Select((x, index) => KeyValuePair.Create(x, index)).ToList(), p => { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key, p.Value); }); Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), new[] { 1024 * 4 }, MemberType = typeof(Sources))] public static void Select_Indexed_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Select_Indexed_NotPipelined(labeled, count); } [Fact] public static void Select_ArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).Select(x => x)); AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).Select((x, index) => x)); AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Empty<bool>().Select((Func<bool, bool>)null)); AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Empty<bool>().Select((Func<bool, int, bool>)null)); } [Theory] [InlineData(true, true)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(false, false)] public static void Select_OrderablePartitionerWithOutOfOrderInputs_AsOrdered_CorrectOrder(bool keysOrderedInEachPartition, bool keysNormalized) { var range = new RangeOrderablePartitioner(0, 1024, keysOrderedInEachPartition, keysNormalized); int next = 0; foreach (int i in range.AsParallel().AsOrdered().Select(i => i)) { Assert.Equal(next++, i); } } // // SelectMany // // [Regression Test] // An issue occurred because the QuerySettings structure was not being deep-cloned during // query-opening. As a result, the concurrent inner-enumerators (for the RHS operators) // that occur in SelectMany were sharing CancellationState that they should not have. // The result was that enumerators could falsely believe they had been canceled when // another inner-enumerator was disposed. // // Note: the failure was intermittent. this test would fail about 1 in 2 times on mikelid1 (4-core). public static IEnumerable<object[]> SelectManyUnorderedData(int[] counts) { foreach (int count in counts.DefaultIfEmpty(Sources.OuterLoopCount / 64)) { foreach (Labeled<Func<int, int, IEnumerable<int>>> expander in Expanders()) { foreach (int expandCount in new[] { 0, 1, 2, 8 }) { yield return new object[] { count, expander, expandCount }; } } } } public static IEnumerable<object[]> SelectManyData(int[] counts) { foreach (object[] results in Sources.Ranges(counts.DefaultIfEmpty(Sources.OuterLoopCount / 64))) { foreach (Labeled<Func<int, int, IEnumerable<int>>> expander in Expanders()) { foreach (int count in new[] { 0, 1, 2, 8 }) { yield return new object[] { results[0], results[1], expander, count }; } } } } private static IEnumerable<Labeled<Func<int, int, IEnumerable<int>>>> Expanders() { yield return Labeled.Label("Array", (Func<int, int, IEnumerable<int>>)((start, count) => Enumerable.Range(start * count, count).ToArray())); yield return Labeled.Label("Enumerable.Range", (Func<int, int, IEnumerable<int>>)((start, count) => Enumerable.Range(start * count, count))); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Unordered(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); foreach (int i in UnorderedSources.Default(count).SelectMany(x => expand(x, expansion))) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Unordered_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Unordered(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; foreach (int i in query.SelectMany(x => expand(x, expansion))) { Assert.Equal(seen++, i); } Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Unordered_NotPipelined(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); Assert.All(UnorderedSources.Default(count).SelectMany(x => expand(x, expansion)).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Unordered_NotPipelined_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Unordered_NotPipelined(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; Assert.All(query.SelectMany(x => expand(x, expansion)).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_NotPipelined(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Unordered_ResultSelector(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); foreach (var p in UnorderedSources.Default(count).SelectMany(x => expand(x, expansion), (original, expanded) => KeyValuePair.Create(original, expanded))) { seen.Add(p.Value); Assert.Equal(p.Key, p.Value / expansion); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Unordered_ResultSelector_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Unordered_ResultSelector(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Unordered_ResultSelector_NotPipelined(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); Assert.All(UnorderedSources.Default(count).SelectMany(x => expand(x, expansion), (original, expanded) => KeyValuePair.Create(original, expanded)).ToList(), p => { seen.Add(p.Value); Assert.Equal(p.Key, p.Value / expansion); }); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Unordered_ResultSelector_NotPipelined_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Unordered_ResultSelector_NotPipelined(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_ResultSelector(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; foreach (var p in query.SelectMany(x => expand(x, expansion), (original, expanded) => KeyValuePair.Create(original, expanded))) { Assert.Equal(seen++, p.Value); Assert.Equal(p.Key, p.Value / expansion); } Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_ResultSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_ResultSelector(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_ResultSelector_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; Assert.All(query.SelectMany(x => expand(x, expansion), (original, expanded) => KeyValuePair.Create(original, expanded)).ToList(), p => { Assert.Equal(seen++, p.Value); Assert.Equal(p.Key, p.Value / expansion); }); Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_ResultSelector_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_ResultSelector_NotPipelined(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_Unordered(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); foreach (var pIndex in UnorderedSources.Default(count).SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)))) { seen.Add(pIndex.Value); Assert.Equal(pIndex.Key, pIndex.Value / expansion); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_Unordered_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_Unordered(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_Unordered_NotPipelined(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); Assert.All(UnorderedSources.Default(count).SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y))).ToList(), pIndex => { seen.Add(pIndex.Value); Assert.Equal(pIndex.Key, pIndex.Value / expansion); }); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_Unordered_NotPipelined_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_Unordered_NotPipelined(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; foreach (var pIndex in query.SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)))) { Assert.Equal(seen++, pIndex.Value); Assert.Equal(pIndex.Key, pIndex.Value / expansion); } Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; Assert.All(query.SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y))).ToList(), pIndex => { Assert.Equal(seen++, pIndex.Value); Assert.Equal(pIndex.Key, pIndex.Value / expansion); }); Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_NotPipelined(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_Unordered_ResultSelector(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); foreach (var pOuter in UnorderedSources.Default(count).SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)), (original, expanded) => KeyValuePair.Create(original, expanded))) { var pInner = pOuter.Value; Assert.Equal(pOuter.Key, pInner.Key); seen.Add(pInner.Value); Assert.Equal(pOuter.Key, pInner.Value / expansion); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_Unordered_ResultSelector_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_Unordered_ResultSelector(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_Unordered_ResultSelector_NotPipelined(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); Assert.All(UnorderedSources.Default(count).SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)), (original, expanded) => KeyValuePair.Create(original, expanded)).ToList(), pOuter => { var pInner = pOuter.Value; Assert.Equal(pOuter.Key, pInner.Key); seen.Add(pInner.Value); Assert.Equal(pOuter.Key, pInner.Value / expansion); }); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_Unordered_ResultSelector_NotPipelined_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_Unordered_ResultSelector_NotPipelined(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_ResultSelector(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; foreach (var pOuter in query.SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)), (original, expanded) => KeyValuePair.Create(original, expanded))) { var pInner = pOuter.Value; Assert.Equal(pOuter.Key, pInner.Key); Assert.Equal(seen++, pInner.Value); Assert.Equal(pOuter.Key, pInner.Value / expansion); } Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_ResultSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_ResultSelector(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_ResultSelector_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; Assert.All(query.SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)), (original, expanded) => KeyValuePair.Create(original, expanded)).ToList(), pOuter => { var pInner = pOuter.Value; Assert.Equal(pOuter.Key, pInner.Key); Assert.Equal(seen++, pInner.Value); Assert.Equal(pOuter.Key, pInner.Value / expansion); }); Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_ResultSelector_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_ResultSelector_NotPipelined(labeled, count, expander, expansion); } [Fact] public static void SelectMany_ArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).SelectMany(x => new[] { x })); AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).SelectMany((x, index) => new[] { x })); AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Empty<bool>().SelectMany((Func<bool, IEnumerable<bool>>)null)); AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Empty<bool>().SelectMany((Func<bool, int, IEnumerable<bool>>)null)); AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).SelectMany(x => new[] { x }, (x, y) => x)); AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).SelectMany((x, index) => new[] { x }, (x, y) => x)); AssertExtensions.Throws<ArgumentNullException>("collectionSelector", () => ParallelEnumerable.Empty<bool>().SelectMany((Func<bool, IEnumerable<bool>>)null, (x, y) => x)); AssertExtensions.Throws<ArgumentNullException>("collectionSelector", () => ParallelEnumerable.Empty<bool>().SelectMany((Func<bool, int, IEnumerable<bool>>)null, (x, y) => x)); AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => ParallelEnumerable.Empty<bool>().SelectMany(x => new[] { x }, (Func<bool, bool, bool>)null)); AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => ParallelEnumerable.Empty<bool>().SelectMany((x, index) => new[] { x }, (Func<bool, bool, bool>)null)); } } }
using System; using System.Linq; using NetGore.Extensions; using NUnit.Framework; using SFML.Graphics; namespace NetGore.Tests.NetGore { [TestFixture] public class Vector3Tests { #region Unit tests [Test] public void AbsTest() { for (var x = -10; x < 10; x++) { for (var y = -10; y < 10; y++) { for (var z = -10; z < 10; z++) { var v = new Vector3(x, y, z); v = v.Abs(); Assert.LessOrEqual(0, v.X); Assert.LessOrEqual(0, v.Y); Assert.LessOrEqual(0, v.Z); } } } } [Test] public void CeilingTest() { const int max = 1000; var r = new Random(987); for (var i = 0; i < 30; i++) { var v = new Vector3(r.NextFloat() * max, r.NextFloat() * max, r.NextFloat() * max); var c = v.Ceiling(); Assert.AreEqual(Math.Ceiling(v.X), c.X); Assert.AreEqual(Math.Ceiling(v.Y), c.Y); Assert.AreEqual(Math.Ceiling(v.Z), c.Z); } } [Test] public void FloorTest() { const int max = 1000; var r = new Random(102); for (var i = 0; i < 30; i++) { var v = new Vector3(r.NextFloat() * max, r.NextFloat() * max, r.NextFloat() * max); var c = v.Floor(); Assert.AreEqual(Math.Floor(v.X), c.X); Assert.AreEqual(Math.Floor(v.Y), c.Y); Assert.AreEqual(Math.Floor(v.Z), c.Z); } } [Test] public void IsGreaterOrEqualTest() { for (var x1 = -2; x1 < 2; x1++) { for (var y1 = -2; y1 < 2; y1++) { for (var z1 = -5; z1 < 5; z1++) { for (var x2 = -2; x2 < 2; x2++) { for (var y2 = -2; y2 < 2; y2++) { for (var z2 = -5; z2 < 5; z2++) { var v1 = new Vector3(x1, y1, z1); var v2 = new Vector3(x2, y2, z2); var b1 = (v1.X >= v2.X && v1.Y >= v2.Y && v1.Z >= v2.Z); Assert.AreEqual(b1, v1.IsGreaterOrEqual(v2)); var b2 = (v2.X >= v1.X && v2.Y >= v1.Y && v2.Z >= v1.Z); Assert.AreEqual(b2, v2.IsGreaterOrEqual(v1)); } } } } } } } [Test] public void IsGreaterThanTest() { for (var x1 = -2; x1 < 2; x1++) { for (var y1 = -2; y1 < 2; y1++) { for (var z1 = -5; z1 < 5; z1++) { for (var x2 = -2; x2 < 2; x2++) { for (var y2 = -2; y2 < 2; y2++) { for (var z2 = -5; z2 < 5; z2++) { var v1 = new Vector3(x1, y1, z1); var v2 = new Vector3(x2, y2, z2); var b1 = (v1.X > v2.X && v1.Y > v2.Y && v1.Z > v2.Z); Assert.AreEqual(b1, v1.IsGreaterThan(v2)); var b2 = (v2.X > v1.X && v2.Y > v1.Y && v2.Z > v1.Z); Assert.AreEqual(b2, v2.IsGreaterThan(v1)); } } } } } } } [Test] public void IsLessOrEqualTest() { for (var x1 = -2; x1 < 2; x1++) { for (var y1 = -2; y1 < 2; y1++) { for (var z1 = -5; z1 < 5; z1++) { for (var x2 = -2; x2 < 2; x2++) { for (var y2 = -2; y2 < 2; y2++) { for (var z2 = -5; z2 < 5; z2++) { var v1 = new Vector3(x1, y1, z1); var v2 = new Vector3(x2, y2, z2); var b1 = (v1.X <= v2.X && v1.Y <= v2.Y && v1.Z <= v2.Z); Assert.AreEqual(b1, v1.IsLessOrEqual(v2)); var b2 = (v2.X <= v1.X && v2.Y <= v1.Y && v2.Z <= v1.Z); Assert.AreEqual(b2, v2.IsLessOrEqual(v1)); } } } } } } } [Test] public void IsLessThanTest() { for (var x1 = -2; x1 < 2; x1++) { for (var y1 = -2; y1 < 2; y1++) { for (var z1 = -5; z1 < 5; z1++) { for (var x2 = -2; x2 < 2; x2++) { for (var y2 = -2; y2 < 2; y2++) { for (var z2 = -5; z2 < 5; z2++) { var v1 = new Vector3(x1, y1, z1); var v2 = new Vector3(x2, y2, z2); var b1 = (v1.X < v2.X && v1.Y < v2.Y && v1.Z < v2.Z); Assert.AreEqual(b1, v1.IsLessThan(v2)); var b2 = (v2.X < v1.X && v2.Y < v1.Y && v2.Z < v1.Z); Assert.AreEqual(b2, v2.IsLessThan(v1)); } } } } } } } [Test] public void RoundTest() { const int max = 1000; var r = new Random(578); for (var i = 0; i < 30; i++) { var v = new Vector3(r.NextFloat() * max, r.NextFloat() * max, r.NextFloat() * max); var c = v.Round(); Assert.AreEqual(Math.Round(v.X), c.X); Assert.AreEqual(Math.Round(v.Y), c.Y); Assert.AreEqual(Math.Round(v.Z), c.Z); } } [Test] public void SumTest() { for (var x = -10; x < 10; x++) { for (var y = -10; y < 10; y++) { for (var z = -10; z < 10; z++) { var v = new Vector3(x, y, z); Assert.AreEqual(x + y + z, v.Sum()); } } } } #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. namespace System.Security.Cryptography { using Microsoft.Win32; using System.IO; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if FEATURE_MACL using System.Security.AccessControl; #endif // FEATURE_MACL using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; #if FEATURE_IMPERSONATION using System.Security.Principal; #endif // FEATURE_IMPERSONATION using System.Text; using System.Threading; using System.Diagnostics.Contracts; using System.Runtime.Versioning; [Serializable] internal enum CspAlgorithmType { Rsa = 0, Dss = 1 } internal static class Constants { #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO internal const int S_OK = 0; internal const int NTE_FILENOTFOUND = unchecked((int) 0x80070002); // The system cannot find the file specified. internal const int NTE_NO_KEY = unchecked((int) 0x8009000D); // Key does not exist. internal const int NTE_BAD_KEYSET = unchecked((int) 0x80090016); // Keyset does not exist. internal const int NTE_KEYSET_NOT_DEF = unchecked((int) 0x80090019); // The keyset is not defined. internal const int KP_IV = 1; internal const int KP_MODE = 4; internal const int KP_MODE_BITS = 5; internal const int KP_EFFECTIVE_KEYLEN = 19; internal const int ALG_CLASS_SIGNATURE = (1 << 13); internal const int ALG_CLASS_DATA_ENCRYPT = (3 << 13); internal const int ALG_CLASS_HASH = (4 << 13); internal const int ALG_CLASS_KEY_EXCHANGE = (5 << 13); internal const int ALG_TYPE_DSS = (1 << 9); internal const int ALG_TYPE_RSA = (2 << 9); internal const int ALG_TYPE_BLOCK = (3 << 9); internal const int ALG_TYPE_STREAM = (4 << 9); internal const int ALG_TYPE_ANY = (0); internal const int CALG_MD5 = (ALG_CLASS_HASH | ALG_TYPE_ANY | 3); internal const int CALG_SHA1 = (ALG_CLASS_HASH | ALG_TYPE_ANY | 4); internal const int CALG_SHA_256 = (ALG_CLASS_HASH | ALG_TYPE_ANY | 12); internal const int CALG_SHA_384 = (ALG_CLASS_HASH | ALG_TYPE_ANY | 13); internal const int CALG_SHA_512 = (ALG_CLASS_HASH | ALG_TYPE_ANY | 14); internal const int CALG_RSA_KEYX = (ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_RSA | 0); internal const int CALG_RSA_SIGN = (ALG_CLASS_SIGNATURE | ALG_TYPE_RSA | 0); internal const int CALG_DSS_SIGN = (ALG_CLASS_SIGNATURE | ALG_TYPE_DSS | 0); internal const int CALG_DES = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 1); internal const int CALG_RC2 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 2); internal const int CALG_3DES = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 3); internal const int CALG_3DES_112 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 9); internal const int CALG_AES_128 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 14); internal const int CALG_AES_192 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 15); internal const int CALG_AES_256 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 16); internal const int CALG_RC4 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_STREAM | 1); #endif // FEATURE_CRYPTO internal const int PROV_RSA_FULL = 1; internal const int PROV_DSS_DH = 13; internal const int PROV_RSA_AES = 24; #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO internal const int AT_KEYEXCHANGE = 1; #endif // FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO internal const int AT_SIGNATURE = 2; #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO internal const int PUBLICKEYBLOB = 0x6; internal const int PRIVATEKEYBLOB = 0x7; internal const int CRYPT_OAEP = 0x40; internal const uint CRYPT_VERIFYCONTEXT = 0xF0000000; internal const uint CRYPT_NEWKEYSET = 0x00000008; internal const uint CRYPT_DELETEKEYSET = 0x00000010; internal const uint CRYPT_MACHINE_KEYSET = 0x00000020; internal const uint CRYPT_SILENT = 0x00000040; internal const uint CRYPT_EXPORTABLE = 0x00000001; internal const uint CLR_KEYLEN = 1; internal const uint CLR_PUBLICKEYONLY = 2; internal const uint CLR_EXPORTABLE = 3; internal const uint CLR_REMOVABLE = 4; internal const uint CLR_HARDWARE = 5; internal const uint CLR_ACCESSIBLE = 6; internal const uint CLR_PROTECTED = 7; internal const uint CLR_UNIQUE_CONTAINER = 8; internal const uint CLR_ALGID = 9; internal const uint CLR_PP_CLIENT_HWND = 10; internal const uint CLR_PP_PIN = 11; internal const string OID_RSA_SMIMEalgCMS3DESwrap = "1.2.840.113549.1.9.16.3.6"; internal const string OID_RSA_MD5 = "1.2.840.113549.2.5"; internal const string OID_RSA_RC2CBC = "1.2.840.113549.3.2"; internal const string OID_RSA_DES_EDE3_CBC = "1.2.840.113549.3.7"; internal const string OID_OIWSEC_desCBC = "1.3.14.3.2.7"; internal const string OID_OIWSEC_SHA1 = "1.3.14.3.2.26"; internal const string OID_OIWSEC_SHA256 = "2.16.840.1.101.3.4.2.1"; internal const string OID_OIWSEC_SHA384 = "2.16.840.1.101.3.4.2.2"; internal const string OID_OIWSEC_SHA512 = "2.16.840.1.101.3.4.2.3"; internal const string OID_OIWSEC_RIPEMD160 = "1.3.36.3.2.1"; #endif // FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO } internal static class Utils { #if FEATURE_CRYPTO [SecuritySafeCritical] #endif static Utils() { } // Provider type to use by default for RSA operations. We want to use RSA-AES CSP // since it enables access to SHA-2 operations. All currently supported OSes support RSA-AES. internal const int DefaultRsaProviderType = Constants.PROV_RSA_AES; #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject = new Object(); private static Object InternalSyncObject { get { return s_InternalSyncObject; } } [System.Security.SecurityCritical] // auto-generated private static volatile SafeProvHandle _safeProvHandle; internal static SafeProvHandle StaticProvHandle { [System.Security.SecurityCritical] // auto-generated get { if (_safeProvHandle == null) { lock (InternalSyncObject) { if (_safeProvHandle == null) { _safeProvHandle = AcquireProvHandle(new CspParameters(DefaultRsaProviderType)); } } } return _safeProvHandle; } } [System.Security.SecurityCritical] // auto-generated private static volatile SafeProvHandle _safeDssProvHandle; internal static SafeProvHandle StaticDssProvHandle { [System.Security.SecurityCritical] // auto-generated get { if (_safeDssProvHandle == null) { lock (InternalSyncObject) { if (_safeDssProvHandle == null) { _safeDssProvHandle = CreateProvHandle(new CspParameters(Constants.PROV_DSS_DH), true); } } } return _safeDssProvHandle; } } [System.Security.SecurityCritical] // auto-generated internal static SafeProvHandle AcquireProvHandle (CspParameters parameters) { if (parameters == null) parameters = new CspParameters(DefaultRsaProviderType); SafeProvHandle safeProvHandle = SafeProvHandle.InvalidHandle; Utils._AcquireCSP(parameters, ref safeProvHandle); return safeProvHandle; } [System.Security.SecurityCritical] // auto-generated internal static SafeProvHandle CreateProvHandle (CspParameters parameters, bool randomKeyContainer) { SafeProvHandle safeProvHandle = SafeProvHandle.InvalidHandle; int hr = Utils._OpenCSP(parameters, 0, ref safeProvHandle); KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); if (hr != Constants.S_OK) { // If UseExistingKey flag is used and the key container does not exist // throw an exception without attempting to create the container. if ((parameters.Flags & CspProviderFlags.UseExistingKey) != 0 || (hr != Constants.NTE_KEYSET_NOT_DEF && hr != Constants.NTE_BAD_KEYSET && hr != Constants.NTE_FILENOTFOUND)) throw new CryptographicException(hr); if (!randomKeyContainer) { if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Create); kp.AccessEntries.Add(entry); kp.Demand(); } } Utils._CreateCSP(parameters, randomKeyContainer, ref safeProvHandle); } else { if (!randomKeyContainer) { if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open); kp.AccessEntries.Add(entry); kp.Demand(); } } } return safeProvHandle; } #if FEATURE_MACL [System.Security.SecurityCritical] // auto-generated internal static CryptoKeySecurity GetKeySetSecurityInfo (SafeProvHandle hProv, AccessControlSections accessControlSections) { SecurityInfos securityInfo = 0; Privilege privilege = null; if ((accessControlSections & AccessControlSections.Owner) != 0) securityInfo |= SecurityInfos.Owner; if ((accessControlSections & AccessControlSections.Group) != 0) securityInfo |= SecurityInfos.Group; if ((accessControlSections & AccessControlSections.Access) != 0) securityInfo |= SecurityInfos.DiscretionaryAcl; byte[] rawSecurityDescriptor = null; int error; RuntimeHelpers.PrepareConstrainedRegions(); try { if ((accessControlSections & AccessControlSections.Audit) != 0) { securityInfo |= SecurityInfos.SystemAcl; privilege = new Privilege("SeSecurityPrivilege"); privilege.Enable(); } rawSecurityDescriptor = _GetKeySetSecurityInfo(hProv, securityInfo, out error); } finally { if (privilege != null) privilege.Revert(); } // This means that the object doesn't have a security descriptor. And thus we throw // a specific exception for the caller to catch and handle properly. if (error == Win32Native.ERROR_SUCCESS && (rawSecurityDescriptor == null || rawSecurityDescriptor.Length == 0)) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoSecurityDescriptor")); if (error == Win32Native.ERROR_NOT_ENOUGH_MEMORY) throw new OutOfMemoryException(); if (error == Win32Native.ERROR_ACCESS_DENIED) throw new UnauthorizedAccessException(); if (error == Win32Native.ERROR_PRIVILEGE_NOT_HELD) throw new PrivilegeNotHeldException( "SeSecurityPrivilege" ); if (error != Win32Native.ERROR_SUCCESS) throw new CryptographicException(error); CommonSecurityDescriptor sd = new CommonSecurityDescriptor(false /* isContainer */, false /* isDS */, new RawSecurityDescriptor(rawSecurityDescriptor, 0), true); return new CryptoKeySecurity(sd); } [System.Security.SecurityCritical] // auto-generated internal static void SetKeySetSecurityInfo (SafeProvHandle hProv, CryptoKeySecurity cryptoKeySecurity, AccessControlSections accessControlSections) { SecurityInfos securityInfo = 0; Privilege privilege = null; if ((accessControlSections & AccessControlSections.Owner) != 0 && cryptoKeySecurity._securityDescriptor.Owner != null) securityInfo |= SecurityInfos.Owner; if ((accessControlSections & AccessControlSections.Group) != 0 && cryptoKeySecurity._securityDescriptor.Group != null) securityInfo |= SecurityInfos.Group; if ((accessControlSections & AccessControlSections.Audit) != 0) securityInfo |= SecurityInfos.SystemAcl; if ((accessControlSections & AccessControlSections.Access) != 0 && cryptoKeySecurity._securityDescriptor.IsDiscretionaryAclPresent) securityInfo |= SecurityInfos.DiscretionaryAcl; if (securityInfo == 0) { // Nothing to persist return; } int error = 0; RuntimeHelpers.PrepareConstrainedRegions(); try { if ((securityInfo & SecurityInfos.SystemAcl) != 0) { privilege = new Privilege("SeSecurityPrivilege"); privilege.Enable(); } byte[] sd = cryptoKeySecurity.GetSecurityDescriptorBinaryForm(); if (sd != null && sd.Length > 0) error = SetKeySetSecurityInfo (hProv, securityInfo, sd); } finally { if (privilege != null) privilege.Revert(); } if (error == Win32Native.ERROR_ACCESS_DENIED || error == Win32Native.ERROR_INVALID_OWNER || error == Win32Native.ERROR_INVALID_PRIMARY_GROUP) throw new UnauthorizedAccessException(); else if (error == Win32Native.ERROR_PRIVILEGE_NOT_HELD) throw new PrivilegeNotHeldException("SeSecurityPrivilege"); else if (error == Win32Native.ERROR_INVALID_HANDLE) throw new NotSupportedException(Environment.GetResourceString("AccessControl_InvalidHandle")); else if (error != Win32Native.ERROR_SUCCESS) throw new CryptographicException(error); } #endif //FEATURE_MACL [System.Security.SecurityCritical] // auto-generated internal static byte[] ExportCspBlobHelper (bool includePrivateParameters, CspParameters parameters, SafeKeyHandle safeKeyHandle) { if (includePrivateParameters) { if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Export); kp.AccessEntries.Add(entry); kp.Demand(); } } byte[] blob = null; Utils.ExportCspBlob(safeKeyHandle, includePrivateParameters ? Constants.PRIVATEKEYBLOB : Constants.PUBLICKEYBLOB, JitHelpers.GetObjectHandleOnStack(ref blob)); return blob; } [System.Security.SecuritySafeCritical] // auto-generated internal static void GetKeyPairHelper (CspAlgorithmType keyType, CspParameters parameters, bool randomKeyContainer, int dwKeySize, ref SafeProvHandle safeProvHandle, ref SafeKeyHandle safeKeyHandle) { SafeProvHandle TempFetchedProvHandle = Utils.CreateProvHandle(parameters, randomKeyContainer); #if FEATURE_MACL // If the user wanted to set the security descriptor on the provider context, apply it now. if (parameters.CryptoKeySecurity != null) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.ChangeAcl); kp.AccessEntries.Add(entry); kp.Demand(); SetKeySetSecurityInfo(TempFetchedProvHandle, parameters.CryptoKeySecurity, parameters.CryptoKeySecurity.ChangedAccessControlSections); } #endif //FEATURE_MACL #if FEATURE_X509_SECURESTRINGS // If the user wanted to specify a PIN or HWND for a smart card CSP, apply those settings now. if (parameters.ParentWindowHandle != IntPtr.Zero) SetProviderParameter(TempFetchedProvHandle, parameters.KeyNumber, Constants.CLR_PP_CLIENT_HWND, parameters.ParentWindowHandle); else if (parameters.KeyPassword != null) { IntPtr szPassword = Marshal.SecureStringToCoTaskMemAnsi(parameters.KeyPassword); try { SetProviderParameter(TempFetchedProvHandle, parameters.KeyNumber, Constants.CLR_PP_PIN, szPassword); } finally { if (szPassword != IntPtr.Zero) Marshal.ZeroFreeCoTaskMemAnsi(szPassword); } } #endif //FEATURE_X509_SECURESTRINGS safeProvHandle = TempFetchedProvHandle; // If the key already exists, use it, else generate a new one SafeKeyHandle TempFetchedKeyHandle = SafeKeyHandle.InvalidHandle; int hr = Utils._GetUserKey(safeProvHandle, parameters.KeyNumber, ref TempFetchedKeyHandle); if (hr != Constants.S_OK) { if ((parameters.Flags & CspProviderFlags.UseExistingKey) != 0 || hr != Constants.NTE_NO_KEY) throw new CryptographicException(hr); // _GenerateKey will check for failures and throw an exception Utils._GenerateKey(safeProvHandle, parameters.KeyNumber, parameters.Flags, dwKeySize, ref TempFetchedKeyHandle); } // check that this is indeed an RSA/DSS key. byte[] algid = (byte[]) Utils._GetKeyParameter(TempFetchedKeyHandle, Constants.CLR_ALGID); int dwAlgId = (algid[0] | (algid[1] << 8) | (algid[2] << 16) | (algid[3] << 24)); if ((keyType == CspAlgorithmType.Rsa && dwAlgId != Constants.CALG_RSA_KEYX && dwAlgId != Constants.CALG_RSA_SIGN) || (keyType == CspAlgorithmType.Dss && dwAlgId != Constants.CALG_DSS_SIGN)) { TempFetchedKeyHandle.Dispose(); throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_WrongKeySpec")); } safeKeyHandle = TempFetchedKeyHandle; } [System.Security.SecurityCritical] // auto-generated internal static void ImportCspBlobHelper (CspAlgorithmType keyType, byte[] keyBlob, bool publicOnly, ref CspParameters parameters, bool randomKeyContainer, ref SafeProvHandle safeProvHandle, ref SafeKeyHandle safeKeyHandle) { // Free the current key handle if (safeKeyHandle != null && !safeKeyHandle.IsClosed) safeKeyHandle.Dispose(); safeKeyHandle = SafeKeyHandle.InvalidHandle; if (publicOnly) { parameters.KeyNumber = Utils._ImportCspBlob(keyBlob, keyType == CspAlgorithmType.Dss ? Utils.StaticDssProvHandle : Utils.StaticProvHandle, (CspProviderFlags) 0, ref safeKeyHandle); } else { if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Import); kp.AccessEntries.Add(entry); kp.Demand(); } if (safeProvHandle == null) safeProvHandle = Utils.CreateProvHandle(parameters, randomKeyContainer); parameters.KeyNumber = Utils._ImportCspBlob(keyBlob, safeProvHandle, parameters.Flags, ref safeKeyHandle); } } #endif // FEATURE_CRYPTO #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO [System.Security.SecurityCritical] // auto-generated internal static CspParameters SaveCspParameters (CspAlgorithmType keyType, CspParameters userParameters, CspProviderFlags defaultFlags, ref bool randomKeyContainer) { CspParameters parameters; if (userParameters == null) { parameters = new CspParameters(keyType == CspAlgorithmType.Dss ? Constants.PROV_DSS_DH : DefaultRsaProviderType, null, null, defaultFlags); } else { ValidateCspFlags(userParameters.Flags); parameters = new CspParameters(userParameters); } if (parameters.KeyNumber == -1) parameters.KeyNumber = keyType == CspAlgorithmType.Dss ? Constants.AT_SIGNATURE : Constants.AT_KEYEXCHANGE; else if (parameters.KeyNumber == Constants.CALG_DSS_SIGN || parameters.KeyNumber == Constants.CALG_RSA_SIGN) parameters.KeyNumber = Constants.AT_SIGNATURE; else if (parameters.KeyNumber == Constants.CALG_RSA_KEYX) parameters.KeyNumber = Constants.AT_KEYEXCHANGE; // If no key container was specified and UseDefaultKeyContainer is not used, then use CRYPT_VERIFYCONTEXT // to generate an ephemeral key randomKeyContainer = (parameters.Flags & CspProviderFlags.CreateEphemeralKey) == CspProviderFlags.CreateEphemeralKey; if (parameters.KeyContainerName == null && (parameters.Flags & CspProviderFlags.UseDefaultKeyContainer) == 0) { parameters.Flags |= CspProviderFlags.CreateEphemeralKey; randomKeyContainer = true; } return parameters; } [System.Security.SecurityCritical] // auto-generated private static void ValidateCspFlags (CspProviderFlags flags) { // check that the flags are consistent. if ((flags & CspProviderFlags.UseExistingKey) != 0) { CspProviderFlags keyFlags = (CspProviderFlags.UseNonExportableKey | CspProviderFlags.UseArchivableKey | CspProviderFlags.UseUserProtectedKey); if ((flags & keyFlags) != CspProviderFlags.NoFlags) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag")); } // make sure we are allowed to display the key protection UI if a user protected key is requested. if ((flags & CspProviderFlags.UseUserProtectedKey) != 0) { // UI only allowed in interactive session. if (!System.Environment.UserInteractive) throw new InvalidOperationException(Environment.GetResourceString("Cryptography_NotInteractive")); // we need to demand UI permission here. UIPermission uiPermission = new UIPermission(UIPermissionWindow.SafeTopLevelWindows); uiPermission.Demand(); } } #endif // FEATURE_CRYPTO private static volatile RNGCryptoServiceProvider _rng; internal static RNGCryptoServiceProvider StaticRandomNumberGenerator { get { if (_rng == null) _rng = new RNGCryptoServiceProvider(); return _rng; } } // // internal static methods // internal static byte[] GenerateRandom (int keySize) { byte[] key = new byte[keySize]; StaticRandomNumberGenerator.GetBytes(key); return key; } #if FEATURE_CRYPTO /// <summary> /// Read the FIPS policy from the pre-Vista registry key /// </summary> /// <returns> /// True if the FIPS policy is enabled, false otherwise. An error reading the policy key is /// interpreted as if the policy is enabled, and a missing key is interpreted as the policy being /// disabled. /// </returns> [System.Security.SecurityCritical] // auto-generated #pragma warning disable 618 [RegistryPermissionAttribute(SecurityAction.Assert, Read="HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Lsa")] #pragma warning restore 618 internal static bool ReadLegacyFipsPolicy() { Contract.Assert(Environment.OSVersion.Version.Major < 6, "CryptGetFIPSAlgorithmMode should be used on Vista+"); try { using (RegistryKey fipsAlgorithmPolicyKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Lsa", false)) { if (fipsAlgorithmPolicyKey == null) return false; object data = fipsAlgorithmPolicyKey.GetValue("FIPSAlgorithmPolicy"); if (data == null) { return false; } else if (fipsAlgorithmPolicyKey.GetValueKind("FIPSAlgorithmPolicy") != RegistryValueKind.DWord) { return true; } else { return ((int)data != 0); } } } catch (SecurityException) { // If we could not open the registry key, we'll assume the setting is to enforce FIPS policy. return true; } } #endif //FEATURE_CRYPTO #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO // dwKeySize = 0 means the default key size [System.Security.SecurityCritical] // auto-generated internal static bool HasAlgorithm (int dwCalg, int dwKeySize) { bool r = false; // We need to take a lock here since we are querying the provider handle in a loop. // If multiple threads are racing in this code, not all algorithms/key sizes combinations // will be examined; which may lead to a situation where false is wrongfully returned. lock (InternalSyncObject) { r = SearchForAlgorithm(StaticProvHandle, dwCalg, dwKeySize); } return r; } internal static int ObjToAlgId(object hashAlg, OidGroup group) { if (hashAlg == null) throw new ArgumentNullException("hashAlg"); Contract.EndContractBlock(); string oidValue = null; string hashAlgString = hashAlg as string; if (hashAlgString != null) { oidValue = CryptoConfig.MapNameToOID(hashAlgString, group); if (oidValue == null) oidValue = hashAlgString; // maybe we were passed the OID value } else if (hashAlg is HashAlgorithm) { oidValue = CryptoConfig.MapNameToOID(hashAlg.GetType().ToString(), group); } else if (hashAlg is Type) { oidValue = CryptoConfig.MapNameToOID(hashAlg.ToString(), group); } if (oidValue == null) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue")); return X509Utils.GetAlgIdFromOid(oidValue, group); } internal static HashAlgorithm ObjToHashAlgorithm (Object hashAlg) { if (hashAlg == null) throw new ArgumentNullException("hashAlg"); Contract.EndContractBlock(); HashAlgorithm hash = null; if (hashAlg is String) { hash = (HashAlgorithm) CryptoConfig.CreateFromName((string) hashAlg); if (hash == null) { string oidFriendlyName = X509Utils.GetFriendlyNameFromOid((string) hashAlg, OidGroup.HashAlgorithm); if (oidFriendlyName != null) hash = (HashAlgorithm) CryptoConfig.CreateFromName(oidFriendlyName); } } else if (hashAlg is HashAlgorithm) { hash = (HashAlgorithm) hashAlg; } else if (hashAlg is Type) { hash = (HashAlgorithm) CryptoConfig.CreateFromName(hashAlg.ToString()); } if (hash == null) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue")); return hash; } internal static String DiscardWhiteSpaces (string inputBuffer) { return DiscardWhiteSpaces(inputBuffer, 0, inputBuffer.Length); } internal static String DiscardWhiteSpaces (string inputBuffer, int inputOffset, int inputCount) { int i, iCount = 0; for (i=0; i<inputCount; i++) if (Char.IsWhiteSpace(inputBuffer[inputOffset + i])) iCount++; char[] output = new char[inputCount - iCount]; iCount = 0; for (i=0; i<inputCount; i++) { if (!Char.IsWhiteSpace(inputBuffer[inputOffset + i])) output[iCount++] = inputBuffer[inputOffset + i]; } return new String(output); } internal static int ConvertByteArrayToInt (byte[] input) { // Input to this routine is always big endian int dwOutput = 0; for (int i = 0; i < input.Length; i++) { dwOutput *= 256; dwOutput += input[i]; } return(dwOutput); } // output of this routine is always big endian internal static byte[] ConvertIntToByteArray (int dwInput) { byte[] temp = new byte[8]; // int can never be greater than Int64 int t1; // t1 is remaining value to account for int t2; // t2 is t1 % 256 int i = 0; if (dwInput == 0) return new byte[1]; t1 = dwInput; while (t1 > 0) { Contract.Assert(i < 8, "Got too big an int here!"); t2 = t1 % 256; temp[i] = (byte) t2; t1 = (t1 - t2)/256; i++; } // Now, copy only the non-zero part of temp and reverse byte[] output = new byte[i]; // copy and reverse in one pass for (int j = 0; j < i; j++) { output[j] = temp[i-j-1]; } return output; } // output is little endian internal static void ConvertIntToByteArray (uint dwInput, ref byte[] counter) { uint t1 = dwInput; // t1 is remaining value to account for uint t2; // t2 is t1 % 256 int i = 0; // clear the array first Array.Clear(counter, 0, counter.Length); if (dwInput == 0) return; while (t1 > 0) { Contract.Assert(i < 4, "Got too big an int here!"); t2 = t1 % 256; counter[3 - i] = (byte) t2; t1 = (t1 - t2)/256; i++; } } internal static byte[] FixupKeyParity (byte[] key) { byte[] oddParityKey = new byte[key.Length]; for (int index=0; index < key.Length; index++) { // Get the bits we are interested in oddParityKey[index] = (byte) (key[index] & 0xfe); // Get the parity of the sum of the previous bits byte tmp1 = (byte)((oddParityKey[index] & 0xF) ^ (oddParityKey[index] >> 4)); byte tmp2 = (byte)((tmp1 & 0x3) ^ (tmp1 >> 2)); byte sumBitsMod2 = (byte)((tmp2 & 0x1) ^ (tmp2 >> 1)); // We need to set the last bit in oddParityKey[index] to the negation // of the last bit in sumBitsMod2 if (sumBitsMod2 == 0) oddParityKey[index] |= 1; } return oddParityKey; } // digits == number of DWORDs [System.Security.SecurityCritical] // auto-generated internal unsafe static void DWORDFromLittleEndian (uint* x, int digits, byte* block) { int i; int j; for (i = 0, j = 0; i < digits; i++, j += 4) x[i] = (uint) (block[j] | (block[j+1] << 8) | (block[j+2] << 16) | (block[j+3] << 24)); } // encodes x (DWORD) into block (unsigned char), least significant byte first. // digits == number of DWORDs internal static void DWORDToLittleEndian (byte[] block, uint[] x, int digits) { int i; int j; for (i = 0, j = 0; i < digits; i++, j += 4) { block[j] = (byte)(x[i] & 0xff); block[j+1] = (byte)((x[i] >> 8) & 0xff); block[j+2] = (byte)((x[i] >> 16) & 0xff); block[j+3] = (byte)((x[i] >> 24) & 0xff); } } #endif // FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO // digits == number of DWORDs [System.Security.SecurityCritical] // auto-generated internal unsafe static void DWORDFromBigEndian (uint* x, int digits, byte* block) { int i; int j; for (i = 0, j = 0; i < digits; i++, j += 4) x[i] = (uint)((block[j] << 24) | (block[j + 1] << 16) | (block[j + 2] << 8) | block[j + 3]); } // encodes x (DWORD) into block (unsigned char), most significant byte first. // digits == number of DWORDs internal static void DWORDToBigEndian (byte[] block, uint[] x, int digits) { int i; int j; for (i = 0, j = 0; i < digits; i++, j += 4) { block[j] = (byte)((x[i] >> 24) & 0xff); block[j+1] = (byte)((x[i] >> 16) & 0xff); block[j+2] = (byte)((x[i] >> 8) & 0xff); block[j+3] = (byte)(x[i] & 0xff); } } #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO // digits == number of QWORDs [System.Security.SecurityCritical] // auto-generated internal unsafe static void QuadWordFromBigEndian (UInt64* x, int digits, byte* block) { int i; int j; for (i = 0, j = 0; i < digits; i++, j += 8) x[i] = ( (((UInt64)block[j]) << 56) | (((UInt64)block[j+1]) << 48) | (((UInt64)block[j+2]) << 40) | (((UInt64)block[j+3]) << 32) | (((UInt64)block[j+4]) << 24) | (((UInt64)block[j+5]) << 16) | (((UInt64)block[j+6]) << 8) | ((UInt64)block[j+7]) ); } // encodes x (DWORD) into block (unsigned char), most significant byte first. // digits = number of QWORDS internal static void QuadWordToBigEndian (byte[] block, UInt64[] x, int digits) { int i; int j; for (i = 0, j = 0; i < digits; i++, j += 8) { block[j] = (byte)((x[i] >> 56) & 0xff); block[j+1] = (byte)((x[i] >> 48) & 0xff); block[j+2] = (byte)((x[i] >> 40) & 0xff); block[j+3] = (byte)((x[i] >> 32) & 0xff); block[j+4] = (byte)((x[i] >> 24) & 0xff); block[j+5] = (byte)((x[i] >> 16) & 0xff); block[j+6] = (byte)((x[i] >> 8) & 0xff); block[j+7] = (byte)(x[i] & 0xff); } } #endif // FEATURE_CRYPTO // encodes the integer i into a 4-byte array, in big endian. internal static byte[] Int(uint i) { return unchecked(new byte[] { (byte)(i >> 24), (byte)(i >> 16), (byte)(i >> 8), (byte)i }); } #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO [System.Security.SecurityCritical] // auto-generated internal static byte[] RsaOaepEncrypt (RSA rsa, HashAlgorithm hash, PKCS1MaskGenerationMethod mgf, RandomNumberGenerator rng, byte[] data) { int cb = rsa.KeySize / 8; // 1. Hash the parameters to get PHash int cbHash = hash.HashSize / 8; if ((data.Length + 2 + 2*cbHash) > cb) throw new CryptographicException(String.Format(null, Environment.GetResourceString("Cryptography_Padding_EncDataTooBig"), cb-2-2*cbHash)); hash.ComputeHash(EmptyArray<Byte>.Value); // Use an empty octet string // 2. Create DB object byte[] DB = new byte[cb - cbHash]; // Structure is as follows: // pHash || PS || 01 || M // PS consists of all zeros Buffer.InternalBlockCopy(hash.Hash, 0, DB, 0, cbHash); DB[DB.Length - data.Length - 1] = 1; Buffer.InternalBlockCopy(data, 0, DB, DB.Length-data.Length, data.Length); // 3. Create a random value of size hLen byte[] seed = new byte[cbHash]; rng.GetBytes(seed); // 4. Compute the mask value byte[] mask = mgf.GenerateMask(seed, DB.Length); // 5. Xor maskDB into DB for (int i=0; i < DB.Length; i++) { DB[i] = (byte) (DB[i] ^ mask[i]); } // 6. Compute seed mask value mask = mgf.GenerateMask(DB, cbHash); // 7. Xor mask into seed for (int i=0; i < seed.Length; i++) { seed[i] ^= mask[i]; } // 8. Concatenate seed and DB to form value to encrypt byte[] pad = new byte[cb]; Buffer.InternalBlockCopy(seed, 0, pad, 0, seed.Length); Buffer.InternalBlockCopy(DB, 0, pad, seed.Length, DB.Length); return rsa.EncryptValue(pad); } [System.Security.SecurityCritical] // auto-generated internal static byte[] RsaOaepDecrypt (RSA rsa, HashAlgorithm hash, PKCS1MaskGenerationMethod mgf, byte[] encryptedData) { int cb = rsa.KeySize / 8; // 1. Decode the input data // It is important that the Integer to Octet String conversion errors be indistinguishable from the other decoding // errors to protect against chosen cipher text attacks // A lecture given by James Manger during Crypto 2001 explains the issue in details byte[] data = null; try { data = rsa.DecryptValue(encryptedData); } catch (CryptographicException) { throw new CryptographicException(Environment.GetResourceString("Cryptography_OAEPDecoding")); } // 2. Create the hash object so we can get its size info. int cbHash = hash.HashSize / 8; // 3. Let maskedSeed be the first hLen octects and maskedDB // be the remaining bytes. int zeros = cb - data.Length; if (zeros < 0 || zeros >= cbHash) throw new CryptographicException(Environment.GetResourceString("Cryptography_OAEPDecoding")); byte[] seed = new byte[cbHash]; Buffer.InternalBlockCopy(data, 0, seed, zeros, seed.Length - zeros); byte[] DB = new byte[data.Length - seed.Length + zeros]; Buffer.InternalBlockCopy(data, seed.Length - zeros, DB, 0, DB.Length); // 4. seedMask = MGF(maskedDB, hLen); byte[] mask = mgf.GenerateMask(DB, seed.Length); // 5. seed = seedMask XOR maskedSeed int i = 0; for (i=0; i < seed.Length; i++) { seed[i] ^= mask[i]; } // 6. dbMask = MGF(seed, |EM| - hLen); mask = mgf.GenerateMask(seed, DB.Length); // 7. DB = maskedDB xor dbMask for (i=0; i < DB.Length; i++) { DB[i] = (byte) (DB[i] ^ mask[i]); } // 8. pHash = HASH(P) hash.ComputeHash(EmptyArray<Byte>.Value); // 9. DB = pHash' || PS || 01 || M // 10. Check that pHash = pHash' byte[] hashValue = hash.Hash; for (i=0; i < cbHash; i++) { if (DB[i] != hashValue[i]) throw new CryptographicException(Environment.GetResourceString("Cryptography_OAEPDecoding")); } // Check that PS is all zeros for (; i<DB.Length; i++) { if (DB[i] == 1) break; else if (DB[i] != 0) throw new CryptographicException(Environment.GetResourceString("Cryptography_OAEPDecoding")); } if (i == DB.Length) throw new CryptographicException(Environment.GetResourceString("Cryptography_OAEPDecoding")); i++; // skip over the one // 11. Output M. byte[] output = new byte[DB.Length - i]; Buffer.InternalBlockCopy(DB, i, output, 0, output.Length); return output; } [System.Security.SecurityCritical] // auto-generated internal static byte[] RsaPkcs1Padding (RSA rsa, byte[] oid, byte[] hash) { int cb = rsa.KeySize/8; byte[] pad = new byte[cb]; // // We want to pad this to the following format: // // 00 || 01 || FF ... FF || 00 || prefix || Data // // We want basically to ASN 1 encode the OID + hash: // STRUCTURE { // STRUCTURE { // OID <hash algorithm OID> // NULL (0x05 0x00) // this is actually an ANY and contains the parameters of the algorithm specified by the OID, I think // } // OCTET STRING <hashvalue> // } // // Get the correct prefix byte[] data = new byte[oid.Length + 8 + hash.Length]; data[0] = 0x30; // a structure follows int tmp = data.Length - 2; data[1] = (byte) tmp; data[2] = 0x30; tmp = oid.Length + 2; data[3] = (byte) tmp; Buffer.InternalBlockCopy(oid, 0, data, 4, oid.Length); data[4 + oid.Length] = 0x05; data[4 + oid.Length + 1] = 0x00; data[4 + oid.Length + 2] = 0x04; // an octet string follows data[4 + oid.Length + 3] = (byte) hash.Length; Buffer.InternalBlockCopy(hash, 0, data, oid.Length + 8, hash.Length); // Construct the whole array int cb1 = cb - data.Length; if (cb1 <= 2) throw new CryptographicUnexpectedOperationException(Environment.GetResourceString("Cryptography_InvalidOID")); pad[0] = 0; pad[1] = 1; for (int i=2; i<cb1-1; i++) { pad[i] = 0xff; } pad[cb1-1] = 0; Buffer.InternalBlockCopy(data, 0, pad, cb1, data.Length); return pad; } // This routine compares 2 big ints; ignoring any leading zeros internal static bool CompareBigIntArrays (byte[] lhs, byte[] rhs) { if (lhs == null) return (rhs == null); int i = 0, j = 0; while (i < lhs.Length && lhs[i] == 0) i++; while (j < rhs.Length && rhs[j] == 0) j++; int count = (lhs.Length - i); if ((rhs.Length - j) != count) return false; for (int k = 0; k < count; k++) { if (lhs[i + k] != rhs[j + k]) return false; } return true; } #if !FEATURE_CORECLR internal static HashAlgorithmName OidToHashAlgorithmName(string oid) { switch (oid) { case Constants.OID_OIWSEC_SHA1: return HashAlgorithmName.SHA1; case Constants.OID_OIWSEC_SHA256: return HashAlgorithmName.SHA256; case Constants.OID_OIWSEC_SHA384: return HashAlgorithmName.SHA384; case Constants.OID_OIWSEC_SHA512: return HashAlgorithmName.SHA512; default: throw new NotSupportedException(); } } #endif // FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern SafeHashHandle CreateHash(SafeProvHandle hProv, int algid); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private static extern void EndHash(SafeHashHandle hHash, ObjectHandleOnStack retHash); [System.Security.SecurityCritical] // auto-generated internal static byte[] EndHash(SafeHashHandle hHash) { byte[] hash = null; EndHash(hHash, JitHelpers.GetObjectHandleOnStack(ref hash)); return hash; } [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private static extern void ExportCspBlob(SafeKeyHandle hKey, int blobType, ObjectHandleOnStack retBlob); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern bool GetPersistKeyInCsp(SafeProvHandle hProv); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private static extern void HashData(SafeHashHandle hHash, byte[] data, int cbData, int ibStart, int cbSize); [System.Security.SecurityCritical] // auto-generated internal static void HashData(SafeHashHandle hHash, byte[] data, int ibStart, int cbSize) { HashData(hHash, data, data.Length, ibStart, cbSize); } [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private static extern bool SearchForAlgorithm(SafeProvHandle hProv, int algID, int keyLength); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern void SetKeyParamDw(SafeKeyHandle hKey, int param, int dwValue); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern void SetKeyParamRgb(SafeKeyHandle hKey, int param, byte[] value, int cbValue); #if FEATURE_MACL [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private static extern int SetKeySetSecurityInfo(SafeProvHandle hProv, SecurityInfos securityInfo, byte[] sd); #endif //FEATURE_MACL [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern void SetPersistKeyInCsp(SafeProvHandle hProv, bool fPersistKeyInCsp); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern void SetProviderParameter(SafeProvHandle hProv, int keyNumber, uint paramID, IntPtr pbData); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private static extern void SignValue(SafeKeyHandle hKey, int keyNumber, int calgKey, int calgHash, byte[] hash, int cbHash, ObjectHandleOnStack retSignature); [System.Security.SecurityCritical] // auto-generated internal static byte[] SignValue(SafeKeyHandle hKey, int keyNumber, int calgKey, int calgHash, byte[] hash) { byte[] signature = null; SignValue(hKey, keyNumber, calgKey, calgHash, hash, hash.Length, JitHelpers.GetObjectHandleOnStack(ref signature)); return signature; } [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private static extern bool VerifySign(SafeKeyHandle hKey, int calgKey, int calgHash, byte[] hash, int cbHash, byte[] signature, int cbSignature); [System.Security.SecurityCritical] // auto-generated internal static bool VerifySign(SafeKeyHandle hKey, int calgKey, int calgHash, byte[] hash, byte[] signature) { return VerifySign(hKey, calgKey, calgHash, hash, hash.Length, signature, signature.Length); } [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void _CreateCSP(CspParameters param, bool randomKeyContainer, ref SafeProvHandle hProv); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int _DecryptData(SafeKeyHandle hKey, byte[] data, int ib, int cb, ref byte[] outputBuffer, int outputOffset, PaddingMode PaddingMode, bool fDone); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int _EncryptData(SafeKeyHandle hKey, byte[] data, int ib, int cb, ref byte[] outputBuffer, int outputOffset, PaddingMode PaddingMode, bool fDone); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void _ExportKey(SafeKeyHandle hKey, int blobType, object cspObject); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void _GenerateKey(SafeProvHandle hProv, int algid, CspProviderFlags flags, int keySize, ref SafeKeyHandle hKey); #endif // FEATURE_CRYPTO [System.Security.SecurityCritical] // auto-generated [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool _GetEnforceFipsPolicySetting(); #if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern byte[] _GetKeyParameter(SafeKeyHandle hKey, uint paramID); #if FEATURE_MACL [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern byte[] _GetKeySetSecurityInfo(SafeProvHandle hProv, SecurityInfos securityInfo, out int error); #endif //FEATURE_MACL [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern object _GetProviderParameter(SafeProvHandle hProv, int keyNumber, uint paramID); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int _GetUserKey(SafeProvHandle hProv, int keyNumber, ref SafeKeyHandle hKey); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void _ImportBulkKey(SafeProvHandle hProv, int algid, bool useSalt, byte[] key, ref SafeKeyHandle hKey); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int _ImportCspBlob(byte[] keyBlob, SafeProvHandle hProv, CspProviderFlags flags, ref SafeKeyHandle hKey); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void _ImportKey(SafeProvHandle hCSP, int keyNumber, CspProviderFlags flags, object cspObject, ref SafeKeyHandle hKey); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern bool _ProduceLegacyHmacValues(); #endif // FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int _OpenCSP(CspParameters param, uint flags, ref SafeProvHandle hProv); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void _AcquireCSP(CspParameters param, ref SafeProvHandle hProv); } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using OTFontFileVal; namespace FontVal { /// <summary> /// Summary description for FormTransform. /// </summary> public class FormTransform : System.Windows.Forms.Form { private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox textBoxR1C1; private System.Windows.Forms.TextBox textBoxR1C2; private System.Windows.Forms.TextBox textBoxR1C3; private System.Windows.Forms.TextBox textBoxR2C1; private System.Windows.Forms.TextBox textBoxR2C2; private System.Windows.Forms.TextBox textBoxR2C3; private System.Windows.Forms.TextBox textBoxR3C1; private System.Windows.Forms.TextBox textBoxR3C2; private System.Windows.Forms.TextBox textBoxR3C3; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.TextBox textBoxStretchX; private System.Windows.Forms.TextBox textBoxStretchY; private System.Windows.Forms.TextBox textBoxRotation; private System.Windows.Forms.TextBox textBoxSkew; private System.Windows.Forms.ErrorProvider errorProvider1; private RastTestTransform m_RastTestTransform; public FormTransform(RastTestTransform rtt) { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // m_RastTestTransform = rtt; textBoxStretchX.Text = rtt.stretchX.ToString("0.000"); textBoxStretchY.Text = rtt.stretchY.ToString("0.000"); textBoxRotation.Text = rtt.rotation.ToString("0.000"); textBoxSkew.Text = rtt.skew.ToString("0.000"); textBoxR1C1.Text = rtt.matrix[0,0].ToString("0.000"); textBoxR1C2.Text = rtt.matrix[0,1].ToString("0.000"); textBoxR1C3.Text = rtt.matrix[0,2].ToString("0.000"); textBoxR2C1.Text = rtt.matrix[1,0].ToString("0.000"); textBoxR2C2.Text = rtt.matrix[1,1].ToString("0.000"); textBoxR2C3.Text = rtt.matrix[1,2].ToString("0.000"); textBoxR3C1.Text = rtt.matrix[2,0].ToString("0.000"); textBoxR3C2.Text = rtt.matrix[2,1].ToString("0.000"); textBoxR3C3.Text = rtt.matrix[2,2].ToString("0.000"); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(FormTransform)); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.btnOK = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.textBoxStretchX = new System.Windows.Forms.TextBox(); this.textBoxStretchY = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.textBoxRotation = new System.Windows.Forms.TextBox(); this.textBoxSkew = new System.Windows.Forms.TextBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.textBoxR1C1 = new System.Windows.Forms.TextBox(); this.textBoxR1C2 = new System.Windows.Forms.TextBox(); this.textBoxR1C3 = new System.Windows.Forms.TextBox(); this.textBoxR2C1 = new System.Windows.Forms.TextBox(); this.textBoxR2C2 = new System.Windows.Forms.TextBox(); this.textBoxR2C3 = new System.Windows.Forms.TextBox(); this.textBoxR3C1 = new System.Windows.Forms.TextBox(); this.textBoxR3C2 = new System.Windows.Forms.TextBox(); this.textBoxR3C3 = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.errorProvider1 = new System.Windows.Forms.ErrorProvider(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); this.tabPage2.SuspendLayout(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // tabControl1 // this.tabControl1.Controls.AddRange(new System.Windows.Forms.Control[] { this.tabPage1, this.tabPage2}); this.tabControl1.Location = new System.Drawing.Point(8, 8); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(328, 224); this.tabControl1.TabIndex = 0; // // tabPage1 // this.tabPage1.Controls.AddRange(new System.Windows.Forms.Control[] { this.textBoxSkew, this.textBoxRotation, this.label4, this.label3, this.groupBox1}); this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Size = new System.Drawing.Size(320, 198); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Settings"; // // tabPage2 // this.tabPage2.Controls.AddRange(new System.Windows.Forms.Control[] { this.groupBox2}); this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Size = new System.Drawing.Size(320, 198); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Matrix"; // // btnOK // this.btnOK.Location = new System.Drawing.Point(64, 248); this.btnOK.Name = "btnOK"; this.btnOK.TabIndex = 1; this.btnOK.Text = "OK"; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Location = new System.Drawing.Point(200, 248); this.btnCancel.Name = "btnCancel"; this.btnCancel.TabIndex = 2; this.btnCancel.Text = "Cancel"; // // groupBox1 // this.groupBox1.Controls.AddRange(new System.Windows.Forms.Control[] { this.textBoxStretchY, this.textBoxStretchX, this.label2, this.label1}); this.groupBox1.Location = new System.Drawing.Point(16, 16); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(288, 72); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; this.groupBox1.Text = "Stretch Factor"; // // label1 // this.label1.Location = new System.Drawing.Point(24, 32); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(16, 23); this.label1.TabIndex = 0; this.label1.Text = "X:"; // // label2 // this.label2.Location = new System.Drawing.Point(136, 32); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(24, 23); this.label2.TabIndex = 1; this.label2.Text = "Y:"; // // textBoxStretchX // this.textBoxStretchX.Location = new System.Drawing.Point(48, 32); this.textBoxStretchX.Name = "textBoxStretchX"; this.textBoxStretchX.Size = new System.Drawing.Size(64, 20); this.textBoxStretchX.TabIndex = 2; this.textBoxStretchX.Text = ""; this.textBoxStretchX.Validating += new System.ComponentModel.CancelEventHandler(this.textBoxStretchX_Validating); this.textBoxStretchX.Validated += new System.EventHandler(this.textBoxStretchX_Validated); // // textBoxStretchY // this.textBoxStretchY.Location = new System.Drawing.Point(168, 32); this.textBoxStretchY.Name = "textBoxStretchY"; this.textBoxStretchY.Size = new System.Drawing.Size(64, 20); this.textBoxStretchY.TabIndex = 3; this.textBoxStretchY.Text = ""; this.textBoxStretchY.Validating += new System.ComponentModel.CancelEventHandler(this.textBoxStretchY_Validating); this.textBoxStretchY.Validated += new System.EventHandler(this.textBoxStretchY_Validated); // // label3 // this.label3.Location = new System.Drawing.Point(16, 104); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(224, 23); this.label3.TabIndex = 1; this.label3.Text = "Rotation in degrees (+ Counter Clockwise)"; // // label4 // this.label4.Location = new System.Drawing.Point(16, 144); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(168, 23); this.label4.TabIndex = 2; this.label4.Text = "Skew in degrees (+ Clockwise)"; // // textBoxRotation // this.textBoxRotation.Location = new System.Drawing.Point(248, 104); this.textBoxRotation.Name = "textBoxRotation"; this.textBoxRotation.Size = new System.Drawing.Size(56, 20); this.textBoxRotation.TabIndex = 3; this.textBoxRotation.Text = ""; this.textBoxRotation.Validating += new System.ComponentModel.CancelEventHandler(this.textBoxRotation_Validating); this.textBoxRotation.Validated += new System.EventHandler(this.textBoxRotation_Validated); // // textBoxSkew // this.textBoxSkew.Location = new System.Drawing.Point(248, 144); this.textBoxSkew.Name = "textBoxSkew"; this.textBoxSkew.Size = new System.Drawing.Size(56, 20); this.textBoxSkew.TabIndex = 4; this.textBoxSkew.Text = ""; this.textBoxSkew.Validating += new System.ComponentModel.CancelEventHandler(this.textBoxSkew_Validating); this.textBoxSkew.Validated += new System.EventHandler(this.textBoxSkew_Validated); // // groupBox2 // this.groupBox2.Controls.AddRange(new System.Windows.Forms.Control[] { this.label5, this.textBoxR3C3, this.textBoxR3C2, this.textBoxR3C1, this.textBoxR2C3, this.textBoxR2C2, this.textBoxR2C1, this.textBoxR1C3, this.textBoxR1C2, this.textBoxR1C1}); this.groupBox2.Location = new System.Drawing.Point(32, 16); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(256, 160); this.groupBox2.TabIndex = 0; this.groupBox2.TabStop = false; this.groupBox2.Text = "Transform Matrix"; // // textBoxR1C1 // this.textBoxR1C1.Location = new System.Drawing.Point(16, 56); this.textBoxR1C1.Name = "textBoxR1C1"; this.textBoxR1C1.Size = new System.Drawing.Size(64, 20); this.textBoxR1C1.TabIndex = 0; this.textBoxR1C1.Text = ""; this.textBoxR1C1.Validating += new System.ComponentModel.CancelEventHandler(this.textBoxR1C1_Validating); this.textBoxR1C1.Validated += new System.EventHandler(this.textBoxR1C1_Validated); // // textBoxR1C2 // this.textBoxR1C2.Location = new System.Drawing.Point(96, 56); this.textBoxR1C2.Name = "textBoxR1C2"; this.textBoxR1C2.Size = new System.Drawing.Size(64, 20); this.textBoxR1C2.TabIndex = 1; this.textBoxR1C2.Text = ""; this.textBoxR1C2.Validating += new System.ComponentModel.CancelEventHandler(this.textBoxR1C2_Validating); this.textBoxR1C2.Validated += new System.EventHandler(this.textBoxR1C2_Validated); // // textBoxR1C3 // this.textBoxR1C3.Location = new System.Drawing.Point(176, 56); this.textBoxR1C3.Name = "textBoxR1C3"; this.textBoxR1C3.Size = new System.Drawing.Size(64, 20); this.textBoxR1C3.TabIndex = 2; this.textBoxR1C3.Text = ""; this.textBoxR1C3.Validating += new System.ComponentModel.CancelEventHandler(this.textBoxR1C3_Validating); this.textBoxR1C3.Validated += new System.EventHandler(this.textBoxR1C3_Validated); // // textBoxR2C1 // this.textBoxR2C1.Location = new System.Drawing.Point(16, 88); this.textBoxR2C1.Name = "textBoxR2C1"; this.textBoxR2C1.Size = new System.Drawing.Size(64, 20); this.textBoxR2C1.TabIndex = 3; this.textBoxR2C1.Text = ""; this.textBoxR2C1.Validating += new System.ComponentModel.CancelEventHandler(this.textBoxR2C1_Validating); this.textBoxR2C1.Validated += new System.EventHandler(this.textBoxR2C1_Validated); // // textBoxR2C2 // this.textBoxR2C2.Location = new System.Drawing.Point(96, 88); this.textBoxR2C2.Name = "textBoxR2C2"; this.textBoxR2C2.Size = new System.Drawing.Size(64, 20); this.textBoxR2C2.TabIndex = 4; this.textBoxR2C2.Text = ""; this.textBoxR2C2.Validating += new System.ComponentModel.CancelEventHandler(this.textBoxR2C2_Validating); this.textBoxR2C2.Validated += new System.EventHandler(this.textBoxR2C2_Validated); // // textBoxR2C3 // this.textBoxR2C3.Location = new System.Drawing.Point(176, 88); this.textBoxR2C3.Name = "textBoxR2C3"; this.textBoxR2C3.Size = new System.Drawing.Size(64, 20); this.textBoxR2C3.TabIndex = 5; this.textBoxR2C3.Text = ""; this.textBoxR2C3.Validating += new System.ComponentModel.CancelEventHandler(this.textBoxR2C3_Validating); this.textBoxR2C3.Validated += new System.EventHandler(this.textBoxR2C3_Validated); // // textBoxR3C1 // this.textBoxR3C1.Location = new System.Drawing.Point(16, 120); this.textBoxR3C1.Name = "textBoxR3C1"; this.textBoxR3C1.Size = new System.Drawing.Size(64, 20); this.textBoxR3C1.TabIndex = 6; this.textBoxR3C1.Text = ""; this.textBoxR3C1.Validating += new System.ComponentModel.CancelEventHandler(this.textBoxR3C1_Validating); this.textBoxR3C1.Validated += new System.EventHandler(this.textBoxR3C1_Validated); // // textBoxR3C2 // this.textBoxR3C2.Location = new System.Drawing.Point(96, 120); this.textBoxR3C2.Name = "textBoxR3C2"; this.textBoxR3C2.Size = new System.Drawing.Size(64, 20); this.textBoxR3C2.TabIndex = 7; this.textBoxR3C2.Text = ""; this.textBoxR3C2.Validating += new System.ComponentModel.CancelEventHandler(this.textBoxR3C2_Validating); this.textBoxR3C2.Validated += new System.EventHandler(this.textBoxR3C2_Validated); // // textBoxR3C3 // this.textBoxR3C3.Location = new System.Drawing.Point(176, 120); this.textBoxR3C3.Name = "textBoxR3C3"; this.textBoxR3C3.Size = new System.Drawing.Size(64, 20); this.textBoxR3C3.TabIndex = 8; this.textBoxR3C3.Text = ""; this.textBoxR3C3.Validating += new System.ComponentModel.CancelEventHandler(this.textBoxR3C3_Validating); this.textBoxR3C3.Validated += new System.EventHandler(this.textBoxR3C3_Validated); // // label5 // this.label5.Location = new System.Drawing.Point(16, 24); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(224, 23); this.label5.TabIndex = 9; this.label5.Text = "Combined with values in the Settings tab."; // // errorProvider1 // this.errorProvider1.DataMember = null; // // FormTransform // this.AcceptButton = this.btnOK; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.btnCancel; this.ClientSize = new System.Drawing.Size(344, 286); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.btnCancel, this.btnOK, this.tabControl1}); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "FormTransform"; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Transform Properties"; this.tabControl1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.tabPage2.ResumeLayout(false); this.groupBox1.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void btnOK_Click(object sender, System.EventArgs e) { m_RastTestTransform.stretchX = (float)Double.Parse(textBoxStretchX.Text); m_RastTestTransform.stretchY = (float)Double.Parse(textBoxStretchY.Text); m_RastTestTransform.rotation = (float)Double.Parse(textBoxRotation.Text); m_RastTestTransform.skew = (float)Double.Parse(textBoxSkew.Text); m_RastTestTransform.matrix[0,0] = (float)Double.Parse(textBoxR1C1.Text); m_RastTestTransform.matrix[0,1] = (float)Double.Parse(textBoxR1C2.Text); m_RastTestTransform.matrix[0,2] = (float)Double.Parse(textBoxR1C3.Text); m_RastTestTransform.matrix[1,0] = (float)Double.Parse(textBoxR2C1.Text); m_RastTestTransform.matrix[1,1] = (float)Double.Parse(textBoxR2C2.Text); m_RastTestTransform.matrix[1,2] = (float)Double.Parse(textBoxR2C3.Text); m_RastTestTransform.matrix[2,0] = (float)Double.Parse(textBoxR3C1.Text); m_RastTestTransform.matrix[2,1] = (float)Double.Parse(textBoxR3C2.Text); m_RastTestTransform.matrix[2,2] = (float)Double.Parse(textBoxR3C3.Text); this.DialogResult = DialogResult.OK; } /********************************************************************************** * * Validation for text boxes containing a float * */ private void ValidateFloat(TextBox tb, object sender, System.ComponentModel.CancelEventArgs e) { if (tb.Text.Length == 0) { e.Cancel = true; this.errorProvider1.SetError(tb, "this value is required"); } else { // make sure there is one or more digits in the string, no more than one decimal point, and no other characters int nDigits = 0; int nDecPts = 0; int nOthers = 0; for (int i=0; i<tb.Text.Length; i++) { char c = tb.Text[i]; if (c>='0' && c<='9') nDigits++; else if (c=='.') nDecPts++; else nOthers++; } if (nDigits<1 || nDecPts>1 || nOthers!=0) { e.Cancel = true; errorProvider1.SetError(tb, "illegal data, enter a floating point number"); } } } private void textBoxStretchX_Validating(object sender, System.ComponentModel.CancelEventArgs e) { ValidateFloat(textBoxStretchX, sender, e); } private void textBoxStretchX_Validated(object sender, System.EventArgs e) { errorProvider1.SetError(textBoxStretchX, ""); } private void textBoxStretchY_Validating(object sender, System.ComponentModel.CancelEventArgs e) { ValidateFloat(textBoxStretchY, sender, e); } private void textBoxStretchY_Validated(object sender, System.EventArgs e) { errorProvider1.SetError(textBoxStretchY, ""); } private void textBoxRotation_Validating(object sender, System.ComponentModel.CancelEventArgs e) { ValidateFloat(textBoxRotation, sender, e); } private void textBoxRotation_Validated(object sender, System.EventArgs e) { errorProvider1.SetError(textBoxRotation, ""); } private void textBoxSkew_Validating(object sender, System.ComponentModel.CancelEventArgs e) { ValidateFloat(textBoxSkew, sender, e); } private void textBoxSkew_Validated(object sender, System.EventArgs e) { errorProvider1.SetError(textBoxSkew, ""); } private void textBoxR1C1_Validating(object sender, System.ComponentModel.CancelEventArgs e) { ValidateFloat(textBoxR1C1, sender, e); } private void textBoxR1C1_Validated(object sender, System.EventArgs e) { errorProvider1.SetError(textBoxR1C1, ""); } private void textBoxR1C2_Validating(object sender, System.ComponentModel.CancelEventArgs e) { ValidateFloat(textBoxR1C2, sender, e); } private void textBoxR1C2_Validated(object sender, System.EventArgs e) { errorProvider1.SetError(textBoxR1C2, ""); } private void textBoxR1C3_Validating(object sender, System.ComponentModel.CancelEventArgs e) { ValidateFloat(textBoxR1C3, sender, e); } private void textBoxR1C3_Validated(object sender, System.EventArgs e) { errorProvider1.SetError(textBoxR1C3, ""); } private void textBoxR2C1_Validating(object sender, System.ComponentModel.CancelEventArgs e) { ValidateFloat(textBoxR2C1, sender, e); } private void textBoxR2C1_Validated(object sender, System.EventArgs e) { errorProvider1.SetError(textBoxR2C1, ""); } private void textBoxR2C2_Validating(object sender, System.ComponentModel.CancelEventArgs e) { ValidateFloat(textBoxR2C2, sender, e); } private void textBoxR2C2_Validated(object sender, System.EventArgs e) { errorProvider1.SetError(textBoxR2C2, ""); } private void textBoxR2C3_Validating(object sender, System.ComponentModel.CancelEventArgs e) { ValidateFloat(textBoxR2C3, sender, e); } private void textBoxR2C3_Validated(object sender, System.EventArgs e) { errorProvider1.SetError(textBoxR2C3, ""); } private void textBoxR3C1_Validating(object sender, System.ComponentModel.CancelEventArgs e) { ValidateFloat(textBoxR3C1, sender, e); } private void textBoxR3C1_Validated(object sender, System.EventArgs e) { errorProvider1.SetError(textBoxR3C1, ""); } private void textBoxR3C2_Validating(object sender, System.ComponentModel.CancelEventArgs e) { ValidateFloat(textBoxR3C2, sender, e); } private void textBoxR3C2_Validated(object sender, System.EventArgs e) { errorProvider1.SetError(textBoxR3C2, ""); } private void textBoxR3C3_Validating(object sender, System.ComponentModel.CancelEventArgs e) { ValidateFloat(textBoxR3C3, sender, e); } private void textBoxR3C3_Validated(object sender, System.EventArgs e) { errorProvider1.SetError(textBoxR3C3, ""); } } }
#if !(UNITY_4_3 || UNITY_4_5) using UnityEngine; using UnityEngine.Events; using System; using System.Collections; using System.Collections.Generic; namespace PixelCrushers.DialogueSystem { /// <summary> /// Response menu controls for UnityUIDialogueUI. /// </summary> [System.Serializable] public class UnityUIResponseMenuControls : AbstractUIResponseMenuControls { /// <summary> /// The panel containing the response menu controls. A panel is optional, but you may want one /// so you can include a background image, panel-wide effects, etc. /// </summary> [Tooltip("The panel containing the response menu controls. A panel is optional, but you may want one so you can include a background image, panel-wide effects, etc.")] public UnityEngine.UI.Graphic panel; /// <summary> /// The PC portrait image to show during the response menu. /// </summary> [Tooltip("The PC portrait image to show during the response menu.")] public UnityEngine.UI.Image pcImage; /// <summary> /// The label that will show the PC name. /// </summary> [Tooltip("The label that will show the PC name.")] public UnityEngine.UI.Text pcName; /// <summary> /// The reminder of the last subtitle. /// </summary> [Tooltip("The reminder of the last subtitle.")] public UnityUISubtitleControls subtitleReminder; /// <summary> /// The (optional) timer. /// </summary> [Tooltip("The (optional) timer.")] public UnityEngine.UI.Slider timer; /// <summary> /// If ticked, then select the currently-focused response on timeout. /// </summary> [Tooltip("Select the currently-focused response on timeout.")] public bool selectCurrentOnTimeout = false; /// <summary> /// The response buttons, if you want to specify buttons at design time. /// </summary> [Tooltip("Design-time positioned response buttons")] public UnityUIResponseButton[] buttons; [Tooltip("Template from which to instantiate response buttons; optional to use instead of positioned buttons above")] public UnityUIResponseButton buttonTemplate; [Tooltip("If using Button Template, instantiated buttons are parented under this GameObject")] public UnityEngine.UI.Graphic buttonTemplateHolder; [Tooltip("Optional scrollbar if the instantiated button holder is in a scroll rect")] public UnityEngine.UI.Scrollbar buttonTemplateScrollbar; [Tooltip("Reset the scroll bar to this value when preparing the response menu")] public float buttonTemplateScrollbarResetValue = 1; [Tooltip("Automatically set up explicit navigation for instantiated template buttons instead of using Automatic navigation")] public bool explicitNavigationForTemplateButtons = true; [Serializable] public class AnimationTransitions { [Tooltip("Trigger to set when showing the response menu panel.")] public string showTrigger = string.Empty; [Tooltip("Trigger to set when hiding the response menu panel.")] public string hideTrigger = string.Empty; } [Serializable] public class AutonumberSettings { [Tooltip("Enable autonumbering of responses.")] public bool enabled = false; [Tooltip("Format for response button text, where {0} is the number and {1} is the menu text.")] public string format = "{0}. {1}"; } public AutonumberSettings autonumber = new AutonumberSettings(); public AnimationTransitions animationTransitions = new AnimationTransitions(); public UnityEvent onContentChanged = new UnityEvent(); /// <summary> /// The instantiated buttons. These are only valid during a specific response menu, /// and only if you're using templates. Each showing of the response menu clears /// this list and re-populates it with new buttons. /// </summary> [HideInInspector] public List<GameObject> instantiatedButtons = new List<GameObject>(); /// <summary> /// Assign this delegate if you want it to replace the default timeout handler. /// </summary> public System.Action TimeoutHandler = null; private UnityUITimer unityUITimer = null; private Texture2D pcPortraitTexture = null; private string pcPortraitName = null; private Animator animator = null; private bool lookedForAnimator = false; private bool isVisible = false; private bool isHiding = false; /// <summary> /// Sets the PC portrait name and texture to use in the response menu. /// </summary> /// <param name="portraitTexture">Portrait texture.</param> /// <param name="portraitName">Portrait name.</param> public override void SetPCPortrait(Texture2D portraitTexture, string portraitName) { pcPortraitTexture = portraitTexture; pcPortraitName = portraitName; } /// <summary> /// Sets the portrait texture to use in the response menu if the named actor is the player. /// This is used to immediately update the GUI control if the SetPortrait() sequencer /// command changes the portrait texture. /// </summary> /// <param name="actorName">Actor name in database.</param> /// <param name="portraitTexture">Portrait texture.</param> public override void SetActorPortraitTexture(string actorName, Texture2D portraitTexture) { if (string.Equals(actorName, pcPortraitName)) { Texture2D actorPortraitTexture = AbstractDialogueUI.GetValidPortraitTexture(actorName, portraitTexture); pcPortraitTexture = actorPortraitTexture; if ((pcImage != null) && (DialogueManager.MasterDatabase.IsPlayer(actorName))) { pcImage.sprite = UITools.CreateSprite(actorPortraitTexture); } } } public override AbstractUISubtitleControls SubtitleReminder { get { return subtitleReminder; } } /// <summary> /// Sets the controls active/inactive, except this method never activates the timer. If the /// UI's display settings specify a timeout, then the UI will call StartTimer() to manually /// activate the timer. /// </summary> /// <param name='value'> /// Value (<c>true</c> for active; otherwise inactive). /// </param> public override void SetActive(bool value) { try { SubtitleReminder.SetActive(value && SubtitleReminder.HasText); Tools.SetGameObjectActive(buttonTemplate, false); foreach (var button in buttons) { if (button != null) { Tools.SetGameObjectActive(button, value && button.visible); } } Tools.SetGameObjectActive(timer, false); Tools.SetGameObjectActive(pcName, value); Tools.SetGameObjectActive(pcImage, value); if (value == true) { if ((pcImage != null) && (pcPortraitTexture != null)) pcImage.sprite = UITools.CreateSprite(pcPortraitTexture); if ((pcName != null) && (pcPortraitName != null)) pcName.text = pcPortraitName; Tools.SetGameObjectActive(panel, true); if (!isVisible && CanTriggerAnimation(animationTransitions.showTrigger)) { animator.SetTrigger(animationTransitions.showTrigger); } if (explicitNavigationForTemplateButtons) SetupTemplateButtonNavigation(); } else { if (isVisible && CanTriggerAnimation(animationTransitions.hideTrigger)) { animator.SetTrigger(animationTransitions.hideTrigger); DialogueManager.Instance.StartCoroutine(DisableAfterAnimation(panel)); } else if (!isHiding) { if (panel != null) Tools.SetGameObjectActive(panel, false); } } } finally { isVisible = value; } } /// <summary> /// Clears the response buttons. /// </summary> protected override void ClearResponseButtons() { DestroyInstantiatedButtons(); if (buttons != null) { for (int i = 0; i < buttons.Length; i++) { if (buttons[i] == null) continue; buttons[i].Reset(); buttons[i].visible = showUnusedButtons; } } } /// <summary> /// Sets the response buttons. /// </summary> /// <param name='responses'> /// Responses. /// </param> /// <param name='target'> /// Target that will receive OnClick events from the buttons. /// </param> protected override void SetResponseButtons(Response[] responses, Transform target) { DestroyInstantiatedButtons(); if ((buttons != null) && (responses != null)) { int buttonNumber = 0; // Add explicitly-positioned buttons: for (int i = 0; i < responses.Length; i++) { if (responses[i].formattedText.position != FormattedText.NoAssignedPosition) { int position = responses[i].formattedText.position; if (0 <= position && position < buttons.Length && buttons[position] != null) { SetResponseButton(buttons[position], responses[i], target, buttonNumber++); } else { Debug.LogWarning(DialogueDebug.Prefix + ": Buttons list doesn't contain a button for position " + position); } } } if ((buttonTemplate != null) && (buttonTemplateHolder != null)) { // Reset scrollbar to top: if (buttonTemplateScrollbar != null) { buttonTemplateScrollbar.value = buttonTemplateScrollbarResetValue; } // Instantiate buttons from template: for (int i = 0; i < responses.Length; i++) { if (responses[i].formattedText.position != FormattedText.NoAssignedPosition) continue; GameObject buttonGameObject = GameObject.Instantiate(buttonTemplate.gameObject) as GameObject; if (buttonGameObject == null) { Debug.LogError(string.Format("{0}: Couldn't instantiate response button template", DialogueDebug.Prefix)); } else { instantiatedButtons.Add(buttonGameObject); buttonGameObject.transform.SetParent(buttonTemplateHolder.transform, false); buttonGameObject.SetActive(true); UnityUIResponseButton responseButton = buttonGameObject.GetComponent<UnityUIResponseButton>(); SetResponseButton(responseButton, responses[i], target, buttonNumber++); if (responseButton != null) buttonGameObject.name = "Response: " + responseButton.Text; } } } else { // Auto-position remaining buttons: if (buttonAlignment == ResponseButtonAlignment.ToFirst) { // Align to first, so add in order to front: for (int i = 0; i < Mathf.Min(buttons.Length, responses.Length); i++) { if (responses[i].formattedText.position == FormattedText.NoAssignedPosition) { int position = Mathf.Clamp(GetNextAvailableResponseButtonPosition(0, 1), 0, buttons.Length - 1); SetResponseButton(buttons[position], responses[i], target, buttonNumber++); } } } else { // Align to last, so add in reverse order to back: for (int i = Mathf.Min(buttons.Length, responses.Length) - 1; i >= 0; i--) { if (responses[i].formattedText.position == FormattedText.NoAssignedPosition) { int position = Mathf.Clamp(GetNextAvailableResponseButtonPosition(buttons.Length - 1, -1), 0, buttons.Length - 1); SetResponseButton(buttons[position], responses[i], target, buttonNumber++); } } } } } NotifyContentChanged(); } private void SetResponseButton(UnityUIResponseButton button, Response response, Transform target, int buttonNumber) { if (button != null) { button.visible = true; button.clickable = response.enabled; button.target = target; if (response != null) button.SetFormattedText(response.formattedText); button.response = response; // Auto-number: if (autonumber.enabled) { button.Text = string.Format(autonumber.format, buttonNumber + 1, button.Text); var keyTrigger = button.GetComponent<UIButtonKeyTrigger>(); if (keyTrigger == null) keyTrigger = button.gameObject.AddComponent<UIButtonKeyTrigger>(); keyTrigger.key = (KeyCode)((int)KeyCode.Alpha1 + buttonNumber); } } } private int GetNextAvailableResponseButtonPosition(int start, int direction) { if (buttons != null) { int position = start; while ((0 <= position) && (position < buttons.Length)) { if (buttons[position].visible && buttons[position].response != null) { position += direction; } else { return position; } } } return 5; } private void SetupTemplateButtonNavigation() { // Assumes buttons are active (since uses GetComponent), so call after activating panel. for (int i = 0; i < instantiatedButtons.Count; i++) { var button = instantiatedButtons[i].GetComponent<UnityUIResponseButton>().button; var above = (i == 0) ? null : instantiatedButtons[i - 1].GetComponent<UnityUIResponseButton>().button; var below = (i == instantiatedButtons.Count - 1) ? null : instantiatedButtons[i + 1].GetComponent<UnityUIResponseButton>().button; var navigation = new UnityEngine.UI.Navigation(); navigation.mode = UnityEngine.UI.Navigation.Mode.Explicit; navigation.selectOnUp = above; navigation.selectOnLeft = above; navigation.selectOnDown = below; navigation.selectOnRight = below; button.navigation = navigation; } } public void DestroyInstantiatedButtons() { foreach (var instantiatedButton in instantiatedButtons) { GameObject.Destroy(instantiatedButton); } instantiatedButtons.Clear(); NotifyContentChanged(); } public void NotifyContentChanged() { onContentChanged.Invoke(); } /// <summary> /// Starts the timer. /// </summary> /// <param name='timeout'> /// Timeout duration in seconds. /// </param> public override void StartTimer(float timeout) { if (timer != null) { if (unityUITimer == null) { Tools.SetGameObjectActive(timer, true); unityUITimer = timer.GetComponent<UnityUITimer>(); if (unityUITimer == null) unityUITimer = timer.gameObject.AddComponent<UnityUITimer>(); Tools.SetGameObjectActive(timer, false); } if (unityUITimer != null) { Tools.SetGameObjectActive(timer, true); unityUITimer.StartCountdown(timeout, OnTimeout); } else { if (DialogueDebug.LogWarnings) Debug.LogWarning(string.Format("{0}: No UnityUITimer component found on timer", DialogueDebug.Prefix)); } } } /// <summary> /// This method is called if the timer runs out. It selects the first response. /// </summary> public virtual void OnTimeout() { if (TimeoutHandler != null) { TimeoutHandler.Invoke(); } else { DefaultTimeoutHandler(); } } public void DefaultTimeoutHandler() { if (selectCurrentOnTimeout) { var currentButton = UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject.GetComponent<UnityUIResponseButton>(); if (currentButton != null) { currentButton.OnClick(); return; } } DialogueManager.Instance.SendMessage("OnConversationTimeout"); } /// <summary> /// Auto-focuses the first response. Useful for gamepads. /// </summary> public void AutoFocus() { if (UnityEngine.EventSystems.EventSystem.current == null) return; if (instantiatedButtons.Count > 0) { UnityEngine.EventSystems.EventSystem.current.SetSelectedGameObject(instantiatedButtons[0].gameObject, null); } else { for (int i = 0; i < buttons.Length; i++) { if (buttons[i].clickable) { UnityEngine.EventSystems.EventSystem.current.SetSelectedGameObject(buttons[i].gameObject, null); return; } } } } private bool CanTriggerAnimation(string triggerName) { return CanTriggerAnimations() && !string.IsNullOrEmpty(triggerName); } private bool CanTriggerAnimations() { if ((animator == null) && !lookedForAnimator) { lookedForAnimator = true; if (panel != null) animator = panel.GetComponentInParent<Animator>(); } return (animator != null) && (animationTransitions != null); } private IEnumerator DisableAfterAnimation(UnityEngine.UI.Graphic panel) { isHiding = true; if (animator != null) { const float maxWaitDuration = 10; float timeout = Time.realtimeSinceStartup + maxWaitDuration; var oldHashId = UITools.GetAnimatorNameHash(animator.GetCurrentAnimatorStateInfo(0)); while ((UITools.GetAnimatorNameHash(animator.GetCurrentAnimatorStateInfo(0)) == oldHashId) && (Time.realtimeSinceStartup < timeout)) { yield return null; } yield return DialogueManager.Instance.StartCoroutine(DialogueTime.WaitForSeconds(animator.GetCurrentAnimatorStateInfo(0).length)); } isHiding = false; if (panel != null) Tools.SetGameObjectActive(panel, false); } } } #endif
using System; using System.Web; using System.Web.Security; using System.Web.UI; using Vevo.Domain; using Vevo.Domain.Marketing; using Vevo.Domain.Users; using Vevo.Shared.Utilities; using Vevo.Shared.WebUI; using Vevo.WebAppLib; using Vevo.WebUI; using Vevo.Base.Domain; using Vevo.Deluxe.Domain; using Vevo.Deluxe.Domain.Marketing; public partial class Components_AffiliateDetails : Vevo.WebUI.International.BaseLanguageUserControl { private enum Mode { Add, Edit }; private Mode _mode = Mode.Add; private string AffiliateCode { get { return DataAccessContextDeluxe.AffiliateRepository.GetCodeFromUserName( HttpContext.Current.User.Identity.Name ); } } private string EditMode { get { if (!String.IsNullOrEmpty( Request.QueryString["EditMode"] )) return Request.QueryString["EditMode"]; else return ""; } } private bool IsEnabled { get { if (ViewState["CurrentIsEnabled"] == null) return true; else return (bool) ViewState["CurrentIsEnabled"]; } set { ViewState["CurrentIsEnabled"] = value; } } private string ErrorMessage { get { if (ViewState["ErrorMessage"] == null) return String.Empty; return ViewState["ErrorMessage"].ToString(); } set { ViewState["ErrorMessage"] = value; } } private void PopulateBlockAccept() { string bodyText = String.Empty; EmailTemplateTextVariable.ReplaceAffiliateAgreementText( out bodyText ); uxAgreementDIV.InnerHtml = bodyText; } private void PopulateControls() { if (!string.IsNullOrEmpty( AffiliateCode )) { Affiliate affiliate = DataAccessContextDeluxe.AffiliateRepository.GetOne( AffiliateCode ); uxFirstName.Text = affiliate.ContactAddress.FirstName; uxLastName.Text = affiliate.ContactAddress.LastName; uxUserName.Text = affiliate.UserName; uxCompany.Text = affiliate.ContactAddress.Company; uxAddress1.Text = affiliate.ContactAddress.Address1; uxAddress2.Text = affiliate.ContactAddress.Address2; uxCity.Text = affiliate.ContactAddress.City; uxCountryAndState.CurrentCountry = affiliate.ContactAddress.Country; uxCountryAndState.CurrentState = affiliate.ContactAddress.State; uxZip.Text = affiliate.ContactAddress.Zip; uxPhone.Text = affiliate.ContactAddress.Phone; uxFax.Text = affiliate.ContactAddress.Fax; uxEmail.Text = affiliate.Email; uxWebSite.Text = affiliate.Website; uxCommissionRateLabel.Text = affiliate.CommissionRate.ToString(); IsEnabled = affiliate.IsEnabled; } } private void SendMailToAffiliate( string affiliateEmail, string userName ) { string body, subjectMail; if (DataAccessContext.Configurations.GetBoolValue( "AffiliateAutoApprove" )) { EmailTemplateTextVariable.ReplaceAffiliateApproveText( userName, affiliateEmail, out subjectMail, out body ); } else { EmailTemplateTextVariable.ReplaceNewAffiliateRegistrationText( userName, affiliateEmail, out subjectMail, out body ); } WebUtilities.SendHtmlMail( NamedConfig.CompanyEmail, affiliateEmail, subjectMail, body ); } private void SendMailToMerchant( string affiliateCode ) { string subjectMail; string body; string affiliateViewUrl = UrlPath.StorefrontUrl + DataAccessContext.Configurations.GetValue( "AdminAdvancedFolder" ) + "/Default.aspx#AffiliateEdit,AffiliateCode=" + affiliateCode; EmailTemplateTextVariable.ReplaceAffiliateSubscribeText( affiliateViewUrl, uxUserName.Text.Trim(), uxEmail.Text.Trim(), out subjectMail, out body ); WebUtilities.SendHtmlMail( NamedConfig.CompanyEmail, NamedConfig.CompanyEmail, subjectMail, body ); } private Affiliate SetUpAffiliate( Affiliate affiliate ) { affiliate.UserName = uxUserName.Text.Trim(); affiliate.ContactAddress = new Address( uxFirstName.Text, uxLastName.Text, uxCompany.Text, uxAddress1.Text, uxAddress2.Text, uxCity.Text, uxCountryAndState.CurrentState, uxZip.Text, uxCountryAndState.CurrentCountry, uxPhone.Text, uxFax.Text ); affiliate.Email = uxEmail.Text.Trim(); affiliate.Website = uxWebSite.Text.Trim(); if (!DataAccessContext.Configurations.GetBoolValue( "AffiliateAutoApprove" )) affiliate.IsEnabled = false; else affiliate.IsEnabled = true; return affiliate; } private void AddAffiliate() { if (Page.IsValid) { if (uxCountryAndState.IsRequiredCountry && !uxCountryAndState.VerifyCountryIsValid) { uxCountryStateDiv.Visible = true; uxCountryStateMessage.Text = "Required Country."; return; } if (uxCountryAndState.IsRequiredState && !uxCountryAndState.VerifyStateIsValid) { uxCountryStateDiv.Visible = true; uxCountryStateMessage.Text = "Required State."; return; } MembershipUser user = Membership.GetUser( uxUserName.Text.Trim() ); if (user == null) { Affiliate affiliate = new Affiliate(); affiliate = SetUpAffiliate( affiliate ); affiliate.RegisterDate = DateTime.Today; affiliate.CommissionRate = DataAccessContext.Configurations.GetDecimalValue( "AffiliateCommissionRate" ); affiliate = DataAccessContextDeluxe.AffiliateRepository.Save( affiliate ); Membership.CreateUser( uxUserName.Text.Trim(), uxPassword.Text, uxEmail.Text.Trim() ); Roles.AddUserToRole( uxUserName.Text, "Affiliates" ); if (DataAccessContext.Configurations.GetBoolValue( "AffiliateAutoApprove" )) FormsAuthentication.SetAuthCookie( uxUserName.Text, false ); try { SendMailToAffiliate( uxEmail.Text, uxUserName.Text ); SendMailToMerchant( affiliate.AffiliateCode ); Response.Redirect( "AffiliateRegisterFinish.aspx" ); } catch (Exception) { uxUsernameValidDIV.Attributes.Add( "display", "none" ); ErrorMessage = "[$SentErrorMessage]"; ClearData(); } } else { ErrorMessage = "[$User Existed]"; } } } private void Update() { Affiliate affiliate = DataAccessContextDeluxe.AffiliateRepository.GetOne( AffiliateCode ); affiliate = SetUpAffiliate( affiliate ); affiliate.CommissionRate = ConvertUtilities.ToDecimal( uxCommissionRateLabel.Text ); DataAccessContextDeluxe.AffiliateRepository.Save( affiliate ); ErrorMessage = "[$UpdateComplete]"; } private void ClearData() { uxUserName.Text = String.Empty; uxEmail.Text = String.Empty; uxPassword.Text = String.Empty; uxTextBoxConfrim.Text = String.Empty; uxFirstName.Text = String.Empty; uxLastName.Text = String.Empty; uxWebSite.Text = String.Empty; uxCompany.Text = String.Empty; uxAddress1.Text = String.Empty; uxAddress2.Text = String.Empty; uxCity.Text = String.Empty; uxZip.Text = String.Empty; uxPhone.Text = String.Empty; uxFax.Text = String.Empty; uxAcceptCheck.Checked = false; uxCountryAndState.CurrentState = ""; Country country = DataAccessContext.CountryRepository.GetOne( DataAccessContext.Configurations.GetValue( "StoreDefaultCountry", StoreContext.CurrentStore ).ToString() ); uxCountryAndState.SetCountryByName( country.CommonName ); } protected void Page_Load( object sender, EventArgs e ) { uxCountryStateDiv.Visible = false; if (!IsEditMode()) { if (IsPostBack) { uxUsernameValidDIV.Attributes.Add( "display", "" ); uxUserName.Attributes.Add( "onchange", "var uxMessage = document.getElementById('" + uxUsernameValidDIV.ClientID + "');uxMessage.innerHTML = '';" ); } else { uxUsernameValidDIV.Attributes.Add( "display", "none" ); } } if (!IsPostBack) { if (IsEditMode()) { PopulateControls(); uxPasswordTR.Visible = false; uxConfirmPasswordTR.Visible = false; uxAddButton.Visible = false; uxAgreementPanel.Visible = false; uxUserName.Enabled = false; if (EditMode == "account") uxRegisAddressPanel.Style["display"] = "none"; else if (EditMode == "address") uxRegisterPanel.Style["display"] = "none"; } else { PopulateBlockAccept(); uxCommissionRateTR.Visible = false; uxUpdateButton.Visible = false; uxAgreementPanel.Visible = true; uxUserName.Enabled = true; } } } protected void Page_PreRender( object sender, EventArgs e ) { } protected void uxAddButton_Click( object sender, EventArgs e ) { if (!uxAcceptCheck.Checked) { uxPolicyAgreementMessage.Text = "[$ErrorPolicyCheck]"; uxPolicyAgreementValidatorDiv.Visible = true; } else { uxPolicyAgreementValidatorDiv.Visible = false; AddAffiliate(); } } protected void uxUpdateButton_Click( object sender, EventArgs e ) { if (uxCountryAndState.IsRequiredCountry && !uxCountryAndState.VerifyCountryIsValid) { uxCountryStateDiv.Visible = true; uxCountryStateMessage.Text = "Required Country."; return; } if (uxCountryAndState.IsRequiredState && !uxCountryAndState.VerifyStateIsValid) { uxCountryStateDiv.Visible = true; uxCountryStateMessage.Text = "Required State."; return; } Update(); } public bool IsEditMode() { return (_mode == Mode.Edit); } public void SetEditMode() { _mode = Mode.Edit; } public string GetMessage() { return ErrorMessage; } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Layouts { using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Text; using NLog.Common; using NLog.Conditions; using NLog.Config; using NLog.Internal; using NLog.LayoutRenderers; using NLog.LayoutRenderers.Wrappers; /// <summary> /// Parses layout strings. /// </summary> internal static class LayoutParser { internal static LayoutRenderer[] CompileLayout(ConfigurationItemFactory configurationItemFactory, SimpleStringReader sr, bool isNested, out string text) { var result = new List<LayoutRenderer>(); var literalBuf = new StringBuilder(); int ch; int p0 = sr.Position; while ((ch = sr.Peek()) != -1) { if (isNested) { //possible escape char `\` if (ch == '\\') { sr.Read(); var nextChar = sr.Peek(); //escape chars if (EndOfLayout(nextChar)) { //read next char and append sr.Read(); literalBuf.Append((char)nextChar); } else { //dont treat \ as escape char and just read it literalBuf.Append('\\'); } continue; } if (EndOfLayout(ch)) { //end of innerlayout. // `}` is when double nested inner layout. // `:` when single nested layout break; } } sr.Read(); //detect `${` (new layout-renderer) if (ch == '$' && sr.Peek() == '{') { //stach already found layout-renderer. AddLiteral(literalBuf, result); LayoutRenderer newLayoutRenderer = ParseLayoutRenderer(configurationItemFactory, sr); if (CanBeConvertedToLiteral(newLayoutRenderer)) { newLayoutRenderer = ConvertToLiteral(newLayoutRenderer); } // layout renderer result.Add(newLayoutRenderer); } else { literalBuf.Append((char)ch); } } AddLiteral(literalBuf, result); int p1 = sr.Position; MergeLiterals(result); text = sr.Substring(p0, p1); return result.ToArray(); } /// <summary> /// Add <see cref="LiteralLayoutRenderer"/> to <paramref name="result"/> /// </summary> /// <param name="literalBuf"></param> /// <param name="result"></param> private static void AddLiteral(StringBuilder literalBuf, List<LayoutRenderer> result) { if (literalBuf.Length > 0) { result.Add(new LiteralLayoutRenderer(literalBuf.ToString())); literalBuf.Length = 0; } } private static bool EndOfLayout(int ch) { return ch == '}' || ch == ':'; } private static string ParseLayoutRendererName(SimpleStringReader sr) { int ch; var nameBuf = new StringBuilder(); while ((ch = sr.Peek()) != -1) { if (ch == ':' || ch == '}') { break; } nameBuf.Append((char)ch); sr.Read(); } return nameBuf.ToString(); } private static string ParseParameterName(SimpleStringReader sr) { int ch; int nestLevel = 0; var nameBuf = new StringBuilder(); while ((ch = sr.Peek()) != -1) { if ((ch == '=' || ch == '}' || ch == ':') && nestLevel == 0) { break; } if (ch == '$') { sr.Read(); nameBuf.Append('$'); if (sr.Peek() == '{') { nameBuf.Append('{'); nestLevel++; sr.Read(); } continue; } if (ch == '}') { nestLevel--; } if (ch == '\\') { // skip the backslash sr.Read(); // append next character nameBuf.Append((char)sr.Read()); continue; } nameBuf.Append((char)ch); sr.Read(); } return nameBuf.ToString(); } private static string ParseParameterValue(SimpleStringReader sr) { int ch; var nameBuf = new StringBuilder(); while ((ch = sr.Peek()) != -1) { if (ch == ':' || ch == '}') { break; } // Code in this condition was replaced // to support escape codes e.g. '\r' '\n' '\u003a', // which can not be used directly as they are used as tokens by the parser // All escape codes listed in the following link were included // in addition to "\{", "\}", "\:" which are NLog specific: // http://blogs.msdn.com/b/csharpfaq/archive/2004/03/12/what-character-escape-sequences-are-available.aspx if (ch == '\\') { // skip the backslash sr.Read(); var nextChar = (char)sr.Peek(); switch (nextChar) { case ':': case '{': case '}': case '\'': case '"': case '\\': sr.Read(); nameBuf.Append(nextChar); break; case '0': sr.Read(); nameBuf.Append('\0'); break; case 'a': sr.Read(); nameBuf.Append('\a'); break; case 'b': sr.Read(); nameBuf.Append('\b'); break; case 'f': sr.Read(); nameBuf.Append('\f'); break; case 'n': sr.Read(); nameBuf.Append('\n'); break; case 'r': sr.Read(); nameBuf.Append('\r'); break; case 't': sr.Read(); nameBuf.Append('\t'); break; case 'u': sr.Read(); var uChar = GetUnicode(sr, 4); // 4 digits nameBuf.Append(uChar); break; case 'U': sr.Read(); var UChar = GetUnicode(sr, 8); // 8 digits nameBuf.Append(UChar); break; case 'x': sr.Read(); var xChar = GetUnicode(sr, 4); // 1-4 digits nameBuf.Append(xChar); break; case 'v': sr.Read(); nameBuf.Append('\v'); break; } continue; } nameBuf.Append((char)ch); sr.Read(); } return nameBuf.ToString(); } private static char GetUnicode(SimpleStringReader sr, int maxDigits) { int code = 0; for (int cnt = 0; cnt < maxDigits; cnt++) { var digitCode = sr.Peek(); if (digitCode >= (int)'0' && digitCode <= (int)'9') digitCode = digitCode - (int)'0'; else if (digitCode >= (int)'a' && digitCode <= (int)'f') digitCode = digitCode - (int)'a' + 10; else if (digitCode >= (int)'A' && digitCode <= (int)'F') digitCode = digitCode - (int)'A' + 10; else break; sr.Read(); code = code * 16 + digitCode; } return (char)code; } private static LayoutRenderer ParseLayoutRenderer(ConfigurationItemFactory configurationItemFactory, SimpleStringReader stringReader) { int ch = stringReader.Read(); Debug.Assert(ch == '{', "'{' expected in layout specification"); string name = ParseLayoutRendererName(stringReader); var layoutRenderer = GetLayoutRenderer(configurationItemFactory, name); var wrappers = new Dictionary<Type, LayoutRenderer>(); var orderedWrappers = new List<LayoutRenderer>(); ch = stringReader.Read(); while (ch != -1 && ch != '}') { string parameterName = ParseParameterName(stringReader).Trim(); if (stringReader.Peek() == '=') { stringReader.Read(); // skip the '=' PropertyInfo propertyInfo; LayoutRenderer parameterTarget = layoutRenderer; if (!PropertyHelper.TryGetPropertyInfo(layoutRenderer, parameterName, out propertyInfo)) { Type wrapperType; if (configurationItemFactory.AmbientProperties.TryGetDefinition(parameterName, out wrapperType)) { LayoutRenderer wrapperRenderer; if (!wrappers.TryGetValue(wrapperType, out wrapperRenderer)) { wrapperRenderer = configurationItemFactory.AmbientProperties.CreateInstance(parameterName); wrappers[wrapperType] = wrapperRenderer; orderedWrappers.Add(wrapperRenderer); } if (!PropertyHelper.TryGetPropertyInfo(wrapperRenderer, parameterName, out propertyInfo)) { propertyInfo = null; } else { parameterTarget = wrapperRenderer; } } } if (propertyInfo == null) { ParseParameterValue(stringReader); } else { if (typeof(Layout).IsAssignableFrom(propertyInfo.PropertyType)) { var nestedLayout = new SimpleLayout(); string txt; LayoutRenderer[] renderers = CompileLayout(configurationItemFactory, stringReader, true, out txt); nestedLayout.SetRenderers(renderers, txt); propertyInfo.SetValue(parameterTarget, nestedLayout, null); } else if (typeof(ConditionExpression).IsAssignableFrom(propertyInfo.PropertyType)) { var conditionExpression = ConditionParser.ParseExpression(stringReader, configurationItemFactory); propertyInfo.SetValue(parameterTarget, conditionExpression, null); } else { string value = ParseParameterValue(stringReader); PropertyHelper.SetPropertyFromString(parameterTarget, parameterName, value, configurationItemFactory); } } } else { SetDefaultPropertyValue(configurationItemFactory, layoutRenderer, parameterName); } ch = stringReader.Read(); } layoutRenderer = ApplyWrappers(configurationItemFactory, layoutRenderer, orderedWrappers); return layoutRenderer; } private static LayoutRenderer GetLayoutRenderer(ConfigurationItemFactory configurationItemFactory, string name) { LayoutRenderer layoutRenderer; try { layoutRenderer = configurationItemFactory.LayoutRenderers.CreateInstance(name); } catch (Exception ex) { if (LogManager.ThrowConfigExceptions ?? LogManager.ThrowExceptions) { throw; } InternalLogger.Error(ex, "Error parsing layout {0} will be ignored.", name); //replace with emptys layoutRenderer = new LiteralLayoutRenderer(string.Empty); } return layoutRenderer; } private static void SetDefaultPropertyValue(ConfigurationItemFactory configurationItemFactory, LayoutRenderer layoutRenderer, string parameterName) { // what we've just read is not a parameterName, but a value // assign it to a default property (denoted by empty string) PropertyInfo propertyInfo; if (PropertyHelper.TryGetPropertyInfo(layoutRenderer, string.Empty, out propertyInfo)) { if (typeof(SimpleLayout) == propertyInfo.PropertyType) { propertyInfo.SetValue(layoutRenderer, new SimpleLayout(parameterName), null); } else { string value = parameterName; PropertyHelper.SetPropertyFromString(layoutRenderer, propertyInfo.Name, value, configurationItemFactory); } } else { InternalLogger.Warn("{0} has no default property", layoutRenderer.GetType().FullName); } } private static LayoutRenderer ApplyWrappers(ConfigurationItemFactory configurationItemFactory, LayoutRenderer lr, List<LayoutRenderer> orderedWrappers) { for (int i = orderedWrappers.Count - 1; i >= 0; --i) { var newRenderer = (WrapperLayoutRendererBase)orderedWrappers[i]; InternalLogger.Trace("Wrapping {0} with {1}", lr.GetType().Name, newRenderer.GetType().Name); if (CanBeConvertedToLiteral(lr)) { lr = ConvertToLiteral(lr); } newRenderer.Inner = new SimpleLayout(new[] { lr }, string.Empty, configurationItemFactory); lr = newRenderer; } return lr; } private static bool CanBeConvertedToLiteral(LayoutRenderer lr) { foreach (IRenderable renderable in ObjectGraphScanner.FindReachableObjects<IRenderable>(true, lr)) { if (renderable.GetType() == typeof(SimpleLayout)) { continue; } if (!renderable.GetType().IsDefined(typeof(AppDomainFixedOutputAttribute), false)) { return false; } } return true; } private static void MergeLiterals(List<LayoutRenderer> list) { for (int i = 0; i + 1 < list.Count;) { var lr1 = list[i] as LiteralLayoutRenderer; var lr2 = list[i + 1] as LiteralLayoutRenderer; if (lr1 != null && lr2 != null) { lr1.Text += lr2.Text; list.RemoveAt(i + 1); } else { i++; } } } private static LayoutRenderer ConvertToLiteral(LayoutRenderer renderer) { return new LiteralLayoutRenderer(renderer.Render(LogEventInfo.CreateNullEvent())); } } }
namespace Blueprint41.Modeller { partial class HtmlEditor { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel(); this.fontSizeComboBox = new System.Windows.Forms.ToolStripComboBox(); this.toolStripLabel2 = new System.Windows.Forms.ToolStripLabel(); this.fontColorComboBox = new System.Windows.Forms.ToolStripComboBox(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.boldButton = new System.Windows.Forms.ToolStripButton(); this.italicButton = new System.Windows.Forms.ToolStripButton(); this.underlineButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.justifyLeftButton = new System.Windows.Forms.ToolStripButton(); this.justifyCenterButton = new System.Windows.Forms.ToolStripButton(); this.justifyRightButton = new System.Windows.Forms.ToolStripButton(); this.justifyFullButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); this.orderedListButton = new System.Windows.Forms.ToolStripButton(); this.unorderedListButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.webBrowser1 = new System.Windows.Forms.WebBrowser(); this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.copyToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.pasteToolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem(); this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.pasteToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.cutToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.copyToolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem(); this.pasteToolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem(); this.deleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.backgroundColorToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.cSSToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.timer = new System.Windows.Forms.Timer(this.components); this.toolStrip1.SuspendLayout(); this.contextMenuStrip1.SuspendLayout(); this.SuspendLayout(); // // toolStrip1 // this.toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripLabel1, this.fontSizeComboBox, this.toolStripLabel2, this.fontColorComboBox, this.toolStripSeparator1, this.boldButton, this.italicButton, this.underlineButton, this.toolStripSeparator4, this.justifyLeftButton, this.justifyCenterButton, this.justifyRightButton, this.justifyFullButton, this.toolStripSeparator5, this.orderedListButton, this.unorderedListButton, this.toolStripSeparator2}); this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(627, 25); this.toolStrip1.TabIndex = 1; this.toolStrip1.Text = "toolStrip1"; // // toolStripLabel1 // this.toolStripLabel1.Name = "toolStripLabel1"; this.toolStripLabel1.Size = new System.Drawing.Size(30, 22); this.toolStripLabel1.Text = "Size:"; // // fontSizeComboBox // this.fontSizeComboBox.DropDownWidth = 75; this.fontSizeComboBox.Name = "fontSizeComboBox"; this.fontSizeComboBox.Size = new System.Drawing.Size(75, 25); this.fontSizeComboBox.ToolTipText = "Font Size"; // // toolStripLabel2 // this.toolStripLabel2.Name = "toolStripLabel2"; this.toolStripLabel2.Size = new System.Drawing.Size(39, 22); this.toolStripLabel2.Text = "Color:"; // // fontColorComboBox // this.fontColorComboBox.DropDownWidth = 75; this.fontColorComboBox.Name = "fontColorComboBox"; this.fontColorComboBox.Size = new System.Drawing.Size(75, 25); this.fontColorComboBox.ToolTipText = "Font Color"; // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25); // // boldButton // this.boldButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.boldButton.Image = global::Blueprint41.Modeller.Properties.Resources.bold; this.boldButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.boldButton.Name = "boldButton"; this.boldButton.Size = new System.Drawing.Size(23, 22); this.boldButton.Text = "toolStripButton1"; this.boldButton.ToolTipText = "Bold"; this.boldButton.Click += new System.EventHandler(this.boldButton_Click); // // italicButton // this.italicButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.italicButton.Image = global::Blueprint41.Modeller.Properties.Resources.italic; this.italicButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.italicButton.Name = "italicButton"; this.italicButton.Size = new System.Drawing.Size(23, 22); this.italicButton.Text = "toolStripButton2"; this.italicButton.ToolTipText = "Italic"; this.italicButton.Click += new System.EventHandler(this.italicButton_Click); // // underlineButton // this.underlineButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.underlineButton.Image = global::Blueprint41.Modeller.Properties.Resources.underscore; this.underlineButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.underlineButton.Name = "underlineButton"; this.underlineButton.Size = new System.Drawing.Size(23, 22); this.underlineButton.Text = "toolStripButton3"; this.underlineButton.ToolTipText = "Underline"; this.underlineButton.Click += new System.EventHandler(this.underlineButton_Click); // // toolStripSeparator4 // this.toolStripSeparator4.Name = "toolStripSeparator4"; this.toolStripSeparator4.Size = new System.Drawing.Size(6, 25); // // justifyLeftButton // this.justifyLeftButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.justifyLeftButton.Image = global::Blueprint41.Modeller.Properties.Resources.lj; this.justifyLeftButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.justifyLeftButton.Name = "justifyLeftButton"; this.justifyLeftButton.Size = new System.Drawing.Size(23, 22); this.justifyLeftButton.Text = "toolStripButton3"; this.justifyLeftButton.ToolTipText = "Justify Left"; this.justifyLeftButton.Click += new System.EventHandler(this.justifyLeftButton_Click); // // justifyCenterButton // this.justifyCenterButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.justifyCenterButton.Image = global::Blueprint41.Modeller.Properties.Resources.cj; this.justifyCenterButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.justifyCenterButton.Name = "justifyCenterButton"; this.justifyCenterButton.Size = new System.Drawing.Size(23, 22); this.justifyCenterButton.Text = "toolStripButton4"; this.justifyCenterButton.ToolTipText = "Justify Center"; this.justifyCenterButton.Click += new System.EventHandler(this.justifyCenterButton_Click); // // justifyRightButton // this.justifyRightButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.justifyRightButton.Image = global::Blueprint41.Modeller.Properties.Resources.rj; this.justifyRightButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.justifyRightButton.Name = "justifyRightButton"; this.justifyRightButton.Size = new System.Drawing.Size(23, 22); this.justifyRightButton.Text = "toolStripButton5"; this.justifyRightButton.ToolTipText = "Justify Right"; this.justifyRightButton.Click += new System.EventHandler(this.justifyRightButton_Click); // // justifyFullButton // this.justifyFullButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.justifyFullButton.Image = global::Blueprint41.Modeller.Properties.Resources.fj; this.justifyFullButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.justifyFullButton.Name = "justifyFullButton"; this.justifyFullButton.Size = new System.Drawing.Size(23, 22); this.justifyFullButton.Text = "toolStripButton6"; this.justifyFullButton.ToolTipText = "Justify Full"; this.justifyFullButton.Click += new System.EventHandler(this.justifyFullButton_Click); // // toolStripSeparator5 // this.toolStripSeparator5.Name = "toolStripSeparator5"; this.toolStripSeparator5.Size = new System.Drawing.Size(6, 25); // // orderedListButton // this.orderedListButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.orderedListButton.Image = global::Blueprint41.Modeller.Properties.Resources.ol; this.orderedListButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.orderedListButton.Name = "orderedListButton"; this.orderedListButton.Size = new System.Drawing.Size(23, 22); this.orderedListButton.Text = "toolStripButton3"; this.orderedListButton.Click += new System.EventHandler(this.orderedListButton_Click); // // unorderedListButton // this.unorderedListButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.unorderedListButton.Image = global::Blueprint41.Modeller.Properties.Resources.uol; this.unorderedListButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.unorderedListButton.Name = "unorderedListButton"; this.unorderedListButton.Size = new System.Drawing.Size(23, 22); this.unorderedListButton.Text = "toolStripButton4"; this.unorderedListButton.Click += new System.EventHandler(this.unorderedListButton_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25); // // toolStripButton2 // this.toolStripButton2.Name = "toolStripButton2"; this.toolStripButton2.Size = new System.Drawing.Size(23, 23); // // toolStripButton1 // this.toolStripButton1.Name = "toolStripButton1"; this.toolStripButton1.Size = new System.Drawing.Size(23, 23); // // webBrowser1 // this.webBrowser1.Dock = System.Windows.Forms.DockStyle.Fill; this.webBrowser1.Location = new System.Drawing.Point(0, 25); this.webBrowser1.MinimumSize = new System.Drawing.Size(20, 20); this.webBrowser1.Name = "webBrowser1"; this.webBrowser1.Size = new System.Drawing.Size(627, 125); this.webBrowser1.TabIndex = 2; // // cutToolStripMenuItem // this.cutToolStripMenuItem.Name = "cutToolStripMenuItem"; this.cutToolStripMenuItem.Size = new System.Drawing.Size(32, 19); // // copyToolStripMenuItem1 // this.copyToolStripMenuItem1.Name = "copyToolStripMenuItem1"; this.copyToolStripMenuItem1.Size = new System.Drawing.Size(32, 19); // // pasteToolStripMenuItem2 // this.pasteToolStripMenuItem2.Name = "pasteToolStripMenuItem2"; this.pasteToolStripMenuItem2.Size = new System.Drawing.Size(32, 19); // // copyToolStripMenuItem // this.copyToolStripMenuItem.Name = "copyToolStripMenuItem"; this.copyToolStripMenuItem.Size = new System.Drawing.Size(32, 19); // // pasteToolStripMenuItem // this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem"; this.pasteToolStripMenuItem.Size = new System.Drawing.Size(32, 19); // // pasteToolStripMenuItem1 // this.pasteToolStripMenuItem1.Name = "pasteToolStripMenuItem1"; this.pasteToolStripMenuItem1.Size = new System.Drawing.Size(32, 19); this.pasteToolStripMenuItem1.Text = "Paste"; // // contextMenuStrip1 // this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.cutToolStripMenuItem1, this.copyToolStripMenuItem2, this.pasteToolStripMenuItem3, this.deleteToolStripMenuItem, this.backgroundColorToolStripMenuItem, this.cSSToolStripMenuItem}); this.contextMenuStrip1.Name = "contextMenuStrip1"; this.contextMenuStrip1.Size = new System.Drawing.Size(171, 136); // // cutToolStripMenuItem1 // this.cutToolStripMenuItem1.Name = "cutToolStripMenuItem1"; this.cutToolStripMenuItem1.Size = new System.Drawing.Size(170, 22); this.cutToolStripMenuItem1.Text = "Cut"; this.cutToolStripMenuItem1.Click += new System.EventHandler(this.cutToolStripMenuItem1_Click); // // copyToolStripMenuItem2 // this.copyToolStripMenuItem2.Name = "copyToolStripMenuItem2"; this.copyToolStripMenuItem2.Size = new System.Drawing.Size(170, 22); this.copyToolStripMenuItem2.Text = "Copy"; this.copyToolStripMenuItem2.Click += new System.EventHandler(this.copyToolStripMenuItem2_Click); // // pasteToolStripMenuItem3 // this.pasteToolStripMenuItem3.Name = "pasteToolStripMenuItem3"; this.pasteToolStripMenuItem3.Size = new System.Drawing.Size(170, 22); this.pasteToolStripMenuItem3.Text = "Paste"; this.pasteToolStripMenuItem3.Click += new System.EventHandler(this.pasteToolStripMenuItem3_Click); // // deleteToolStripMenuItem // this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem"; this.deleteToolStripMenuItem.Size = new System.Drawing.Size(170, 22); this.deleteToolStripMenuItem.Text = "Delete"; this.deleteToolStripMenuItem.Click += new System.EventHandler(this.deleteToolStripMenuItem_Click); // // backgroundColorToolStripMenuItem // this.backgroundColorToolStripMenuItem.Name = "backgroundColorToolStripMenuItem"; this.backgroundColorToolStripMenuItem.Size = new System.Drawing.Size(170, 22); this.backgroundColorToolStripMenuItem.Text = "Background Color"; this.backgroundColorToolStripMenuItem.Click += new System.EventHandler(this.backgroundColorToolStripMenuItem_Click); // // cSSToolStripMenuItem // this.cSSToolStripMenuItem.Name = "cSSToolStripMenuItem"; this.cSSToolStripMenuItem.Size = new System.Drawing.Size(170, 22); // // HtmlEditor // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.webBrowser1); this.Controls.Add(this.toolStrip1); this.Name = "HtmlEditor"; this.Size = new System.Drawing.Size(627, 150); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.contextMenuStrip1.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.WebBrowser webBrowser1; private System.Windows.Forms.ToolStripButton boldButton; private System.Windows.Forms.ToolStripButton italicButton; private System.Windows.Forms.ToolStripButton toolStripButton1; private System.Windows.Forms.ToolStripButton toolStripButton2; private System.Windows.Forms.ToolStripComboBox fontSizeComboBox; private System.Windows.Forms.ToolStripButton underlineButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem2; private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem2; private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem deleteToolStripMenuItem; private System.Windows.Forms.Timer timer; private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; private System.Windows.Forms.ToolStripButton justifyLeftButton; private System.Windows.Forms.ToolStripButton justifyCenterButton; private System.Windows.Forms.ToolStripButton justifyRightButton; private System.Windows.Forms.ToolStripButton justifyFullButton; private System.Windows.Forms.ToolStripMenuItem backgroundColorToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem cSSToolStripMenuItem; private System.Windows.Forms.ToolStripComboBox fontColorComboBox; private System.Windows.Forms.ToolStripLabel toolStripLabel1; private System.Windows.Forms.ToolStripLabel toolStripLabel2; private System.Windows.Forms.ToolStripButton orderedListButton; private System.Windows.Forms.ToolStripButton unorderedListButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; } }
static class Parser { public static object Parse(Workbook workbook) { var results = new Dictionary<object, object>(); var sheet = (Worksheet)workbook.Worksheets[1]; var cell = sheet.Range["A1"]; results[cell.Value2] = cell.Font.Bold; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.Font.Italic; cell = cell.Offset[1, 0]; results[cell.Value2] = (XlUnderlineStyle)cell.Font.Underline; cell = cell.Offset[1, 0]; results[cell.Value2] = (XlUnderlineStyle)cell.Font.Underline; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.Font.Strikethrough; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.Font.Superscript; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.Font.Subscript; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.Font.Size; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.Font.Size; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.Font.Name; cell = cell.Offset[1, 0]; results[cell.Value2] = OleToHex(cell.Font.Color); cell = cell.Offset[1, 0]; results[cell.Value2] = cell.Font.ThemeColor; cell = cell.Offset[1, 0]; results[cell.Value2] = new { theme = cell.Font.ThemeColor, tint = Math.Round((double)cell.Font.TintAndShade, 4), // Round to avoid floating point comparison issues. }; cell = cell.Offset[1, 0]; results[cell.Value2] = (XlHAlign)cell.HorizontalAlignment; // Justify Last Line / Justify Distributed doesn't seem accessible in the Interop API... cell = cell.Offset[1, 0]; results[cell.Value2] = (XlHAlign)cell.HorizontalAlignment; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.IndentLevel; cell = cell.Offset[1, 0]; results[cell.Value2] = (XlVAlign)cell.VerticalAlignment; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.WrapText; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.ShrinkToFit; cell = cell.Offset[1, 0]; results[cell.Value2] = (Constants)cell.ReadingOrder; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.Orientation; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.Orientation; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.Orientation; cell = cell.Offset[1, 0]; results[cell.Value2] = (XlOrientation)cell.Orientation; cell = cell.Offset[1, 0]; results[cell.Value2] = (XlOrientation)cell.Orientation; cell = cell.Offset[1, 0]; results[cell.Value2] = (XlOrientation)cell.Orientation; cell = cell.Offset[1, 0]; results[cell.Value2] = new { pattern = (XlPattern)cell.Interior.Pattern, rgb = OleToHex(cell.Interior.Color), }; cell = cell.Offset[1, 0]; results[cell.Value2] = new { pattern = (XlPattern)cell.Interior.Pattern, theme = cell.Interior.ThemeColor, }; cell = cell.Offset[1, 0]; results[cell.Value2] = new { pattern = (XlPattern)cell.Interior.Pattern, theme = cell.Interior.ThemeColor, tint = Math.Round((double)cell.Interior.TintAndShade, 4), }; cell = cell.Offset[1, 0]; results[cell.Value2] = new { pattern = (XlPattern)cell.Interior.Pattern, fgRgb = OleToHex(cell.Interior.PatternColor), bgTheme = cell.Interior.ThemeColor, bgTint = Math.Round((double)cell.Interior.TintAndShade, 4), }; cell = cell.Offset[1, 0]; var linearGradient = (LinearGradient)cell.Interior.Gradient; results[cell.Value2] = new { pattern = (XlPattern)cell.Interior.Pattern, degree = linearGradient.Degree, stops = new object[] { new { position = linearGradient.ColorStops[1].Position, rgb = OleToHex(linearGradient.ColorStops[1].Color), }, new { position = linearGradient.ColorStops[2].Position, rgb = OleToHex(linearGradient.ColorStops[2].Color), }, new { position = linearGradient.ColorStops[3].Position, rgb = OleToHex(linearGradient.ColorStops[3].Color), }, } }; cell = cell.Offset[1, 0]; var rectangularGradient = (RectangularGradient)cell.Interior.Gradient; results[cell.Value2] = new { pattern = (XlPattern)cell.Interior.Pattern, left = rectangularGradient.RectangleLeft, right = rectangularGradient.RectangleRight, top = rectangularGradient.RectangleTop, bottom = rectangularGradient.RectangleBottom, stops = new object[] { new { position = rectangularGradient.ColorStops[1].Position, rgb = OleToHex(rectangularGradient.ColorStops[1].Color), }, new { position = rectangularGradient.ColorStops[2].Position, rgb = OleToHex(rectangularGradient.ColorStops[2].Color), }, } }; cell = cell.Offset[2, 0]; results[cell.Value2] = GetBorders(cell); cell = cell.Offset[2, 0]; results[cell.Value2] = GetBorders(cell); cell = cell.Offset[2, 0]; results[cell.Value2] = GetBorders(cell); cell = cell.Offset[2, 0]; results[cell.Value2] = GetBorders(cell); cell = cell.Offset[2, 0]; results[cell.Value2] = GetBorders(cell); cell = cell.Offset[2, 0]; results[cell.Value2] = GetBorders(cell); cell = cell.Offset[2, 0]; results[cell.Value2] = GetBorders(cell); cell = cell.Offset[2, 0]; results[cell.Value2] = GetBorders(cell); cell = cell.Offset[1, 0]; results[cell.Value2] = cell.Offset[0, 1].NumberFormat; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.Offset[0, 1].NumberFormat; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.Offset[0, 1].NumberFormat; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.Offset[0, 1].NumberFormat; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.Offset[0, 1].NumberFormat; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.Offset[0, 1].NumberFormat; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.Offset[0, 1].NumberFormat; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.Offset[0, 1].NumberFormat; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.Offset[0, 1].NumberFormat; cell = cell.Offset[1, 0]; results[cell.Value2] = cell.Offset[0, 1].NumberFormat; results["column-row"] = GetRowColumnStyleData(workbook, 2); results["row-column-value"] = GetRowColumnStyleData(workbook, 3); results["value-column-row"] = GetRowColumnStyleData(workbook, 4); return results; } private static object GetRowColumnStyleData(Workbook workbook, int sheetIndex) { var sheet = (Worksheet)workbook.Worksheets[sheetIndex]; var column = (Range)sheet.Columns[1]; var row = (Range)sheet.Rows[1]; return new { column = new { bold = column.Font.Bold, italic = column.Font.Italic, }, row = new { bold = row.Font.Bold, italic = row.Font.Italic, }, A1 = GetCellStyleData(sheet, "A1"), B1 = GetCellStyleData(sheet, "B1"), A2 = GetCellStyleData(sheet, "A2"), B2 = GetCellStyleData(sheet, "B2"), }; } private static object GetCellStyleData(Worksheet sheet, string address) { var cell = (Range)sheet.Range[address]; return new { bold = cell.Font.Bold, italic = cell.Font.Italic, value = cell.Value2, }; } private static string OleToHex(object ole) { var c = ColorTranslator.FromOle(Convert.ToInt32(ole)); return c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2"); } private static object GetBorders(Range cell) { return new { left = GetBorder(cell, XlBordersIndex.xlEdgeLeft), right = GetBorder(cell, XlBordersIndex.xlEdgeRight), top = GetBorder(cell, XlBordersIndex.xlEdgeTop), bottom = GetBorder(cell, XlBordersIndex.xlEdgeBottom), diagonalUp = GetBorder(cell, XlBordersIndex.xlDiagonalUp), diagonalDown = GetBorder(cell, XlBordersIndex.xlDiagonalDown), }; } private static object GetBorder(Range cell, XlBordersIndex index) { var border = cell.Borders[index]; var result = new Dictionary<string, object>(); var style = (XlLineStyle)border.LineStyle; result["style"] = style; if (style == XlLineStyle.xlLineStyleNone) return result; result["tint"] = Math.Round((double)border.TintAndShade, 4); result["weight"] = (XlBorderWeight)border.Weight; try { result["theme"] = border.ThemeColor; } catch { result["rgb"] = OleToHex(border.Color); } return result; } }
using System.Drawing; using System.Runtime.InteropServices; namespace Vanara.PInvoke { public static partial class User32 { /// <summary>The <c>CopyRect</c> function copies the coordinates of one rectangle to another.</summary> /// <param name="lprcDst">Pointer to the RECT structure that receives the logical coordinates of the source rectangle.</param> /// <param name="lprcSrc">Pointer to the RECT structure whose coordinates are to be copied in logical units.</param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero.</para> /// </returns> /// <remarks> /// <para> /// Because applications can use rectangles for different purposes, the rectangle functions do not use an explicit unit of measure. /// Instead, all rectangle coordinates and dimensions are given in signed, logical values. The mapping mode and the function in which /// the rectangle is used determine the units of measure. /// </para> /// <para>Examples</para> /// <para>For an example, see Using Rectangles.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-copyrect BOOL CopyRect( LPRECT lprcDst, const RECT // *lprcSrc ); [DllImport(Lib.User32, SetLastError = false, ExactSpelling = true)] [PInvokeData("winuser.h", MSDNShortId = "9349ba83-59d6-49d0-ac9d-a4d9589748dd")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CopyRect(out RECT lprcDst, in RECT lprcSrc); /// <summary> /// The <c>EqualRect</c> function determines whether the two specified rectangles are equal by comparing the coordinates of their /// upper-left and lower-right corners. /// </summary> /// <param name="lprc1">Pointer to a RECT structure that contains the logical coordinates of the first rectangle.</param> /// <param name="lprc2">Pointer to a RECT structure that contains the logical coordinates of the second rectangle.</param> /// <returns> /// <para>If the two rectangles are identical, the return value is nonzero.</para> /// <para>If the two rectangles are not identical, the return value is zero.</para> /// </returns> /// <remarks> /// <para>The <c>EqualRect</c> function does not treat empty rectangles as equal if their coordinates are different.</para> /// <para> /// Because applications can use rectangles for different purposes, the rectangle functions do not use an explicit unit of measure. /// Instead, all rectangle coordinates and dimensions are given in signed, logical values. The mapping mode and the function in which /// the rectangle is used determine the units of measure. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-equalrect BOOL EqualRect( const RECT *lprc1, const RECT // *lprc2 ); [DllImport(Lib.User32, SetLastError = false, ExactSpelling = true)] [PInvokeData("winuser.h", MSDNShortId = "00763184-6b60-4095-b71e-5a851c2643aa")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool EqualRect(in RECT lprc1, in RECT lprc2); /// <summary> /// The <c>InflateRect</c> function increases or decreases the width and height of the specified rectangle. The <c>InflateRect</c> /// function adds dx units to the left and right ends of the rectangle and dy units to the top and bottom. The dx and dy parameters /// are signed values; positive values increase the width and height, and negative values decrease them. /// </summary> /// <param name="lprc">A pointer to the RECT structure that increases or decreases in size.</param> /// <param name="dx">The amount to increase or decrease the rectangle width. This parameter must be negative to decrease the width.</param> /// <param name="dy">The amount to increase or decrease the rectangle height. This parameter must be negative to decrease the height.</param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero.</para> /// </returns> /// <remarks> /// Because applications can use rectangles for different purposes, the rectangle functions do not use an explicit unit of measure. /// Instead, all rectangle coordinates and dimensions are given in signed, logical values. The mapping mode and the function in which /// the rectangle is used determine the units of measure. /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-inflaterect BOOL InflateRect( LPRECT lprc, int dx, int dy ); [DllImport(Lib.User32, SetLastError = false, ExactSpelling = true)] [PInvokeData("winuser.h", MSDNShortId = "9a52fb7f-cd35-4426-8753-c26cebef30d5")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool InflateRect(ref RECT lprc, int dx, int dy); /// <summary> /// The <c>IntersectRect</c> function calculates the intersection of two source rectangles and places the coordinates of the /// intersection rectangle into the destination rectangle. If the source rectangles do not intersect, an empty rectangle (in which /// all coordinates are set to zero) is placed into the destination rectangle. /// </summary> /// <param name="lprcDst"> /// A pointer to the RECT structure that is to receive the intersection of the rectangles pointed to by the lprcSrc1 and lprcSrc2 /// parameters. This parameter cannot be <c>NULL</c>. /// </param> /// <param name="lprcSrc1">A pointer to the RECT structure that contains the first source rectangle.</param> /// <param name="lprcSrc2">A pointer to the RECT structure that contains the second source rectangle.</param> /// <returns> /// <para>If the rectangles intersect, the return value is nonzero.</para> /// <para>If the rectangles do not intersect, the return value is zero.</para> /// </returns> /// <remarks> /// <para> /// Because applications can use rectangles for different purposes, the rectangle functions do not use an explicit unit of measure. /// Instead, all rectangle coordinates and dimensions are given in signed, logical values. The mapping mode and the function in which /// the rectangle is used determine the units of measure. /// </para> /// <para>Examples</para> /// <para>For an example, see Using Rectangles.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-intersectrect BOOL IntersectRect( LPRECT lprcDst, const // RECT *lprcSrc1, const RECT *lprcSrc2 ); [DllImport(Lib.User32, SetLastError = false, ExactSpelling = true)] [PInvokeData("winuser.h", MSDNShortId = "da686f78-e557-4ff2-9f24-b229f0c01563")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IntersectRect(out RECT lprcDst, in RECT lprcSrc1, in RECT lprcSrc2); /// <summary> /// The <c>InvertRect</c> function inverts a rectangle in a window by performing a logical NOT operation on the color values for each /// pixel in the rectangle's interior. /// </summary> /// <param name="hDC">A handle to the device context.</param> /// <param name="lprc">A pointer to a RECT structure that contains the logical coordinates of the rectangle to be inverted.</param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero.</para> /// </returns> /// <remarks> /// On monochrome screens, <c>InvertRect</c> makes white pixels black and black pixels white. On color screens, the inversion depends /// on how colors are generated for the screen. Calling <c>InvertRect</c> twice for the same rectangle restores the display to its /// previous colors. /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-invertrect BOOL InvertRect( HDC hDC, const RECT *lprc ); [DllImport(Lib.User32, SetLastError = false, ExactSpelling = true)] [PInvokeData("winuser.h", MSDNShortId = "a8c4dbf1-94ec-46e9-b365-7dfc89e4f176")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool InvertRect(HDC hDC, ref RECT lprc); /// <summary> /// The <c>IsRectEmpty</c> function determines whether the specified rectangle is empty. An empty rectangle is one that has no area; /// that is, the coordinate of the right side is less than or equal to the coordinate of the left side, or the coordinate of the /// bottom side is less than or equal to the coordinate of the top side. /// </summary> /// <param name="lprc">Pointer to a RECT structure that contains the logical coordinates of the rectangle.</param> /// <returns> /// <para>If the rectangle is empty, the return value is nonzero.</para> /// <para>If the rectangle is not empty, the return value is zero.</para> /// </returns> /// <remarks> /// <para> /// Because applications can use rectangles for different purposes, the rectangle functions do not use an explicit unit of measure. /// Instead, all rectangle coordinates and dimensions are given in signed, logical values. The mapping mode and the function in which /// the rectangle is used determine the units of measure. /// </para> /// <para>Examples</para> /// <para>For an example, see Using Rectangles.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-isrectempty BOOL IsRectEmpty( const RECT *lprc ); [DllImport(Lib.User32, SetLastError = false, ExactSpelling = true)] [PInvokeData("winuser.h", MSDNShortId = "9deeed4f-304e-47a3-8259-ed7bc3815fd7")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsRectEmpty(in RECT lprc); /// <summary>The <c>OffsetRect</c> function moves the specified rectangle by the specified offsets.</summary> /// <param name="lprc">Pointer to a RECT structure that contains the logical coordinates of the rectangle to be moved.</param> /// <param name="dx"> /// Specifies the amount to move the rectangle left or right. This parameter must be a negative value to move the rectangle to the left. /// </param> /// <param name="dy"> /// Specifies the amount to move the rectangle up or down. This parameter must be a negative value to move the rectangle up. /// </param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero.</para> /// </returns> /// <remarks> /// <para> /// Because applications can use rectangles for different purposes, the rectangle functions do not use an explicit unit of measure. /// Instead, all rectangle coordinates and dimensions are given in signed, logical values. The mapping mode and the function in which /// the rectangle is used determine the units of measure. /// </para> /// <para>Examples</para> /// <para>For an example, see Using Rectangles.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-offsetrect BOOL OffsetRect( LPRECT lprc, int dx, int dy ); [DllImport(Lib.User32, SetLastError = false, ExactSpelling = true)] [PInvokeData("winuser.h", MSDNShortId = "14101ad3-8c6e-459a-974a-1a8a4d8d7906")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool OffsetRect(ref RECT lprc, int dx, int dy); /// <summary> /// The <c>PtInRect</c> function determines whether the specified point lies within the specified rectangle. A point is within a /// rectangle if it lies on the left or top side or is within all four sides. A point on the right or bottom side is considered /// outside the rectangle. /// </summary> /// <param name="lprc">A pointer to a RECT structure that contains the specified rectangle.</param> /// <param name="pt">A POINT structure that contains the specified point.</param> /// <returns> /// <para>If the specified point lies within the rectangle, the return value is nonzero.</para> /// <para>If the specified point does not lie within the rectangle, the return value is zero.</para> /// </returns> /// <remarks> /// <para> /// The rectangle must be normalized before <c>PtInRect</c> is called. That is, lprc.right must be greater than lprc.left and /// lprc.bottom must be greater than lprc.top. If the rectangle is not normalized, a point is never considered inside of the rectangle. /// </para> /// <para> /// Because applications can use rectangles for different purposes, the rectangle functions do not use an explicit unit of measure. /// Instead, all rectangle coordinates and dimensions are given in signed, logical values. The mapping mode and the function in which /// the rectangle is used determine the units of measure. /// </para> /// <para>Examples</para> /// <para>For an example, see Using Rectangles.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-ptinrect BOOL PtInRect( const RECT *lprc, POINT pt ); [DllImport(Lib.User32, SetLastError = false, ExactSpelling = true)] [PInvokeData("winuser.h", MSDNShortId = "8a47a238-082c-44b8-a270-5ebb4d3d9fc8")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool PtInRect(in RECT lprc, Point pt); /// <summary> /// The <c>SetRect</c> function sets the coordinates of the specified rectangle. This is equivalent to assigning the left, top, /// right, and bottom arguments to the appropriate members of the <c>RECT</c> structure. /// </summary> /// <param name="lprc">Pointer to the RECT structure that contains the rectangle to be set.</param> /// <param name="xLeft">Specifies the x-coordinate of the rectangle's upper-left corner.</param> /// <param name="yTop">Specifies the y-coordinate of the rectangle's upper-left corner.</param> /// <param name="xRight">Specifies the x-coordinate of the rectangle's lower-right corner.</param> /// <param name="yBottom">Specifies the y-coordinate of the rectangle's lower-right corner.</param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero.</para> /// </returns> /// <remarks> /// <para> /// Because applications can use rectangles for different purposes, the rectangle functions do not use an explicit unit of measure. /// Instead, all rectangle coordinates and dimensions are given in signed, logical values. The mapping mode and the function in which /// the rectangle is used determine the units of measure. /// </para> /// <para>Examples</para> /// <para>For an example, see Using Rectangles.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-setrect BOOL SetRect( LPRECT lprc, int xLeft, int yTop, // int xRight, int yBottom ); [DllImport(Lib.User32, SetLastError = false, ExactSpelling = true)] [PInvokeData("winuser.h", MSDNShortId = "346c573b-eaf7-4ca6-bd36-18074f7eccf5")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetRect(out RECT lprc, int xLeft, int yTop, int xRight, int yBottom); /// <summary>The <c>SetRectEmpty</c> function creates an empty rectangle in which all coordinates are set to zero.</summary> /// <param name="lprc">Pointer to the RECT structure that contains the coordinates of the rectangle.</param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero.</para> /// </returns> /// <remarks> /// <para> /// Because applications can use rectangles for different purposes, the rectangle functions do not use an explicit unit of measure. /// Instead, all rectangle coordinates and dimensions are given in signed, logical values. The mapping mode and the function in which /// the rectangle is used determine the units of measure. /// </para> /// <para>Examples</para> /// <para>For an example, see Using Rectangles.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-setrectempty BOOL SetRectEmpty( LPRECT lprc ); [DllImport(Lib.User32, SetLastError = false, ExactSpelling = true)] [PInvokeData("winuser.h", MSDNShortId = "d3c677ae-e45c-4d54-8521-75954a466a68")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetRectEmpty(ref RECT lprc); /// <summary> /// The <c>SubtractRect</c> function determines the coordinates of a rectangle formed by subtracting one rectangle from another. /// </summary> /// <param name="lprcDst"> /// A pointer to a RECT structure that receives the coordinates of the rectangle determined by subtracting the rectangle pointed to /// by lprcSrc2 from the rectangle pointed to by lprcSrc1. /// </param> /// <param name="lprcSrc1">A pointer to a RECT structure from which the function subtracts the rectangle pointed to by lprcSrc2.</param> /// <param name="lprcSrc2">A pointer to a RECT structure that the function subtracts from the rectangle pointed to by lprcSrc1.</param> /// <returns> /// <para>If the resulting rectangle is empty, the return value is zero.</para> /// <para>If the resulting rectangle is not empty, the return value is nonzero.</para> /// </returns> /// <remarks> /// <para> /// The function only subtracts the rectangle specified by lprcSrc2 from the rectangle specified by lprcSrc1 when the rectangles /// intersect completely in either the x- or y-direction. For example, if *lprcSrc1 has the coordinates (10,10,100,100) and *lprcSrc2 /// has the coordinates (50,50,150,150), the function sets the coordinates of the rectangle pointed to by lprcDst to (10,10,100,100). /// If *lprcSrc1 has the coordinates (10,10,100,100) and *lprcSrc2 has the coordinates (50,10,150,150), however, the function sets /// the coordinates of the rectangle pointed to by lprcDst to (10,10,50,100). In other words, the resulting rectangle is the bounding /// box of the geometric difference. /// </para> /// <para> /// Because applications can use rectangles for different purposes, the rectangle functions do not use an explicit unit of measure. /// Instead, all rectangle coordinates and dimensions are given in signed, logical values. The mapping mode and the function in which /// the rectangle is used determine the units of measure. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-subtractrect BOOL SubtractRect( LPRECT lprcDst, const RECT // *lprcSrc1, const RECT *lprcSrc2 ); [DllImport(Lib.User32, SetLastError = false, ExactSpelling = true)] [PInvokeData("winuser.h", MSDNShortId = "85c8edae-af2b-4c6c-af37-2631e8b4edcd")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SubtractRect(out RECT lprcDst, in RECT lprcSrc1, in RECT lprcSrc2); /// <summary> /// The <c>UnionRect</c> function creates the union of two rectangles. The union is the smallest rectangle that contains both source rectangles. /// </summary> /// <param name="lprcDst"> /// A pointer to the RECT structure that will receive a rectangle containing the rectangles pointed to by the lprcSrc1 and lprcSrc2 parameters. /// </param> /// <param name="lprcSrc1">A pointer to the RECT structure that contains the first source rectangle.</param> /// <param name="lprcSrc2">A pointer to the RECT structure that contains the second source rectangle.</param> /// <returns> /// <para>If the specified structure contains a nonempty rectangle, the return value is nonzero.</para> /// <para>If the specified structure does not contain a nonempty rectangle, the return value is zero.</para> /// </returns> /// <remarks> /// <para> /// The system ignores the dimensions of an empty rectangle that is, a rectangle in which all coordinates are set to zero, so that it /// has no height or no width. /// </para> /// <para> /// Because applications can use rectangles for different purposes, the rectangle functions do not use an explicit unit of measure. /// Instead, all rectangle coordinates and dimensions are given in signed, logical values. The mapping mode and the function in which /// the rectangle is used determine the units of measure. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-unionrect BOOL UnionRect( LPRECT lprcDst, const RECT // *lprcSrc1, const RECT *lprcSrc2 ); [DllImport(Lib.User32, SetLastError = false, ExactSpelling = true)] [PInvokeData("winuser.h", MSDNShortId = "f2da2df4-3f09-4c54-afd1-c728805f0f64")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool UnionRect(out RECT lprcDst, in RECT lprcSrc1, in RECT lprcSrc2); } }
// SharpMath - C# Mathematical Library // Copyright (c) 2014 Morten Bakkedal // This code is published under the MIT License. using System; using System.Diagnostics; namespace SharpMath.Optimization.DualNumbers { /// <summary> /// This class represents a function value and its first, second, and third order partial derivatives at a given point. Several standard /// mathematical operations are defined. If specified, the third order partial derivatives are fully computed for the first few variables /// only. The class is immutable. Compare with <see cref="DualNumber" />. /// </summary> [Serializable] [DebuggerStepThrough] [DebuggerDisplay("{Value}")] public sealed class ExtendedDualNumber { private static ExtendedDualNumber zero; private double value; private int n, n0; private double[] gradientArray, hessianArray, thirdArray; [NonSerialized] private Vector gradient; [NonSerialized] private Matrix hessian; [NonSerialized] private Tensor third; static ExtendedDualNumber() { zero = new ExtendedDualNumber(0.0); } public ExtendedDualNumber(double value) : this(value, null) { } public ExtendedDualNumber(double value, Vector gradient) : this(value, gradient, null) { } public ExtendedDualNumber(double value, Vector gradient, Matrix hessian) : this(value, gradient, hessian, gradient != null ? gradient.Length : 0) { } public ExtendedDualNumber(double value, int n0) : this(value, null, n0) { } public ExtendedDualNumber(double value, Vector gradient, int n0) : this(value, gradient, null, n0) { } public ExtendedDualNumber(double value, Vector gradient, Matrix hessian, int n0) { this.value = value; this.gradient = gradient; this.hessian = hessian; this.n0 = n0; if (gradient != null) { n = gradient.Length; if (n0 > n) { throw new ArgumentException("Invalid number of fully computed third derivatives."); } gradientArray = gradient.ToArray(); } if (hessian != null) { if (gradient == null) { throw new ArgumentException("The gradient must be specified if the Hessian is specified."); } if (hessian.Rows != n || hessian.Columns != n) { throw new ArgumentException("Inconsistent number of derivatives."); } // Since the Hessian is symmetric we only need to store the upper triangular part of it. Use a // one dimensional array until the matrix is requested (if ever). Doing it this way is almost // a factor of 10 faster than using naive matrix operations. hessianArray = new double[HessianSize(n)]; for (int i = 0, l = 0; i < n; i++) { for (int j = i; j < n; j++, l++) { if (hessian[i, j] != hessian[j, i] && !(double.IsNaN(hessian[i, j]) && double.IsNaN(hessian[j, i])) && !(double.IsPositiveInfinity(hessian[i, j]) && double.IsPositiveInfinity(hessian[j, i])) && !(double.IsNegativeInfinity(hessian[i, j]) && double.IsNegativeInfinity(hessian[j, i]))) { throw new ArgumentException("The Hessian must be symmetric."); } hessianArray[l] = hessian[i, j]; } } } } public ExtendedDualNumber(double value, double[] gradientArray, double[] hessianArray, double[] thirdArray) : this(value, gradientArray, hessianArray, thirdArray, gradientArray != null ? gradientArray.Length : 0) { } public ExtendedDualNumber(double value, double[] gradientArray, double[] hessianArray, double[] thirdArray, int n0) { this.value = value; this.n0 = n0; if (gradientArray != null) { n = gradientArray.Length; if (n0 < 0 || n0 > n) { throw new ArgumentException("Invalid number of fully computed third derivatives."); } this.gradientArray = (double[])gradientArray.Clone(); } if (hessianArray != null) { if (gradientArray == null) { throw new ArgumentException("The gradient must be specified if the Hessian is specified."); } if (hessianArray.Length != HessianSize(n)) { throw new ArgumentException("Inconsistent number of derivatives."); } this.hessianArray = (double[])hessianArray.Clone(); } if (thirdArray != null) { if (gradientArray == null || hessianArray == null) { throw new ArgumentException("The gradient and the Hessian must be specified if the third derivatives are specified."); } if (thirdArray.Length != ThirdReducedSize(n, n0) && thirdArray.Length != ThirdSize(n)) { throw new ArgumentException("Inconsistent number of derivatives."); } this.thirdArray = (double[])thirdArray.Clone(); } } public ExtendedDualNumber(ExtendedDualNumber f, double g, double g1, double g11, double g111) { value = g; if (f.gradientArray != null) { n = f.n; n0 = f.n0; gradientArray = new double[n]; if (g1 != 0.0) { for (int i = 0; i < n; i++) { gradientArray[i] += g1 * f.gradientArray[i]; } } if (f.hessianArray != null || g11 != 0.0 || g111 != 0.0) { hessianArray = new double[HessianSize(n)]; if (g1 != 0.0 && f.hessianArray != null) { for (int i = 0, l = 0; i < n; i++) { for (int j = i; j < n; j++, l++) { hessianArray[l] += g1 * f.hessianArray[l]; } } } if (g11 != 0.0) { for (int i = 0, l = 0; i < n; i++) { for (int j = i; j < n; j++, l++) { hessianArray[l] += g11 * f.gradientArray[i] * f.gradientArray[j]; } } } if (f.hessianArray != null || g111 != 0.0) { thirdArray = new double[ThirdReducedSize(n, n0)]; // See how the counters work in the constructor below. if (g1 != 0.0 && f.thirdArray != null) { for (int i = 0, m = 0; i < n0; i++) { for (int j = i; j < n; j++) { for (int k = j; k < n; k++, m++) { thirdArray[m] += g1 * f.thirdArray[m]; } } } } if (g11 != 0.0 && f.hessianArray != null) { for (int i = 0, l1 = 0, l2 = 0, m = 0; i < n0; i++) { for (int j = i, l3 = l2; j < n; j++, l1++, l2 -= n - j) { for (int k = j; k < n; k++, l2++, l3++, m++) { thirdArray[m] += g11 * (f.gradientArray[i] * f.hessianArray[l3] + f.gradientArray[j] * f.hessianArray[l2] + f.gradientArray[k] * f.hessianArray[l1]); } } } } if (g111 != 0.0) { for (int i = 0, m = 0; i < n0; i++) { for (int j = i; j < n; j++) { for (int k = j; k < n; k++, m++) { thirdArray[m] += g111 * f.gradientArray[i] * f.gradientArray[j] * f.gradientArray[k]; } } } } } } } } public ExtendedDualNumber(ExtendedDualNumber f1, ExtendedDualNumber f2, double g, double g1, double g2, double g11, double g12, double g22, double g111, double g112, double g122, double g222) { value = g; if (f1.gradientArray != null || f2.gradientArray != null) { if (f1.gradientArray != null && f2.gradientArray != null && (f1.n != f2.n || f1.n0 != f2.n0)) { throw new ArgumentException("Inconsistent number of derivatives."); } // One of the counters may be zero if the corresponding ExtendedDualNumber is a constant. n = Math.Max(f1.n, f2.n); n0 = Math.Max(f1.n0, f2.n0); gradientArray = new double[n]; if (g1 != 0.0 && f1.gradientArray != null) { for (int i = 0; i < n; i++) { gradientArray[i] += g1 * f1.gradientArray[i]; } } if (g2 != 0.0 && f2.gradientArray != null) { for (int i = 0; i < n; i++) { gradientArray[i] += g2 * f2.gradientArray[i]; } } if (f1.hessianArray != null || f2.hessianArray != null || g11 != 0.0 || g12 != 0.0 || g22 != 0.0 || g111 != 0.0 || g112 != 0.0 || g122 != 0.0 || g222 != 0.0) { hessianArray = new double[HessianSize(n)]; if (g1 != 0.0 && f1.hessianArray != null) { for (int i = 0, l = 0; i < n; i++) { for (int j = i; j < n; j++, l++) { hessianArray[l] += g1 * f1.hessianArray[l]; } } } if (g2 != 0.0 && f2.hessianArray != null) { for (int i = 0, l = 0; i < n; i++) { for (int j = i; j < n; j++, l++) { hessianArray[l] += g2 * f2.hessianArray[l]; } } } if (g11 != 0.0 && f1.gradientArray != null) { for (int i = 0, l = 0; i < n; i++) { for (int j = i; j < n; j++, l++) { hessianArray[l] += g11 * f1.gradientArray[i] * f1.gradientArray[j]; } } } if (g22 != 0.0 && f2.gradientArray != null) { for (int i = 0, l = 0; i < n; i++) { for (int j = i; j < n; j++, l++) { hessianArray[l] += g22 * f2.gradientArray[i] * f2.gradientArray[j]; } } } if (g12 != 0.0 && f1.gradientArray != null && f2.gradientArray != null) { for (int i = 0, l = 0; i < n; i++) { for (int j = i; j < n; j++, l++) { hessianArray[l] += g12 * (f1.gradientArray[i] * f2.gradientArray[j] + f2.gradientArray[i] * f1.gradientArray[j]); } } } if (f1.hessianArray != null || f2.hessianArray != null || g111 != 0.0 || g112 != 0.0 || g122 != 0.0 || g222 != 0.0) { thirdArray = new double[ThirdReducedSize(n, n0)]; // The counters below are constructed so that: // // hessianArray[l1] is the (i,j)th entry of the Hessian, // hessianArray[l2] is the (i,k)th entry of the Hessian, // hessianArray[l3] is the (j,k)th entry of the Hessian, // thirdArray[m] is the (i,j,k)th entry of the third derivatives tensor. // // It's made this way to eliminate redundant entries. In case of the Hessian, only // the upper triangular part is stored. if (g1 != 0.0 && f1.thirdArray != null) { for (int i = 0, m = 0; i < n0; i++) { for (int j = i; j < n; j++) { for (int k = j; k < n; k++, m++) { thirdArray[m] += g1 * f1.thirdArray[m]; } } } } if (g2 != 0.0 && f2.thirdArray != null) { for (int i = 0, m = 0; i < n0; i++) { for (int j = i; j < n; j++) { for (int k = j; k < n; k++, m++) { thirdArray[m] += g2 * f2.thirdArray[m]; } } } } if (g11 != 0.0 && f1.hessianArray != null) { for (int i = 0, l1 = 0, l2 = 0, m = 0; i < n0; i++) { for (int j = i, l3 = l2; j < n; j++, l1++, l2 -= n - j) { for (int k = j; k < n; k++, l2++, l3++, m++) { thirdArray[m] += g11 * (f1.gradientArray[i] * f1.hessianArray[l3] + f1.gradientArray[j] * f1.hessianArray[l2] + f1.gradientArray[k] * f1.hessianArray[l1]); } } } } if (g22 != 0.0 && f2.hessianArray != null) { for (int i = 0, l1 = 0, l2 = 0, m = 0; i < n0; i++) { for (int j = i, l3 = l2; j < n; j++, l1++, l2 -= n - j) { for (int k = j; k < n; k++, l2++, l3++, m++) { thirdArray[m] += g22 * (f2.gradientArray[i] * f2.hessianArray[l3] + f2.gradientArray[j] * f2.hessianArray[l2] + f2.gradientArray[k] * f2.hessianArray[l1]); } } } } if (g12 != 0.0 && f1.gradientArray != null && f2.hessianArray != null) { for (int i = 0, l1 = 0, l2 = 0, m = 0; i < n0; i++) { for (int j = i, l3 = l2; j < n; j++, l1++, l2 -= n - j) { for (int k = j; k < n; k++, l2++, l3++, m++) { thirdArray[m] += g12 * (f1.gradientArray[i] * f2.hessianArray[l3] + f1.gradientArray[j] * f2.hessianArray[l2] + f1.gradientArray[k] * f2.hessianArray[l1]); } } } } if (g12 != 0.0 && f2.gradientArray != null && f1.hessianArray != null) { for (int i = 0, l1 = 0, l2 = 0, m = 0; i < n0; i++) { for (int j = i, l3 = l2; j < n; j++, l1++, l2 -= n - j) { for (int k = j; k < n; k++, l2++, l3++, m++) { thirdArray[m] += g12 * (f2.gradientArray[i] * f1.hessianArray[l3] + f2.gradientArray[j] * f1.hessianArray[l2] + f2.gradientArray[k] * f1.hessianArray[l1]); } } } } if (g111 != 0.0 && f1.gradientArray != null) { for (int i = 0, m = 0; i < n0; i++) { for (int j = i; j < n; j++) { for (int k = j; k < n; k++, m++) { thirdArray[m] += g111 * f1.gradientArray[i] * f1.gradientArray[j] * f1.gradientArray[k]; } } } } if (g222 != 0.0 && f2.gradientArray != null) { for (int i = 0, m = 0; i < n0; i++) { for (int j = i; j < n; j++) { for (int k = j; k < n; k++, m++) { thirdArray[m] += g222 * f2.gradientArray[i] * f2.gradientArray[j] * f2.gradientArray[k]; } } } } if (g112 != 0.0 && f1.gradientArray != null && f2.gradientArray != null) { for (int i = 0, m = 0; i < n0; i++) { for (int j = i; j < n; j++) { for (int k = j; k < n; k++, m++) { thirdArray[m] += g112 * (f1.gradientArray[i] * f1.gradientArray[j] * f2.gradientArray[k] + f1.gradientArray[i] * f2.gradientArray[j] * f1.gradientArray[k] + f2.gradientArray[i] * f1.gradientArray[j] * f1.gradientArray[k]); } } } } if (g122 != 0.0 && f1.gradientArray != null && f2.gradientArray != null) { for (int i = 0, m = 0; i < n0; i++) { for (int j = i; j < n; j++) { for (int k = j; k < n; k++, m++) { thirdArray[m] += g122 * (f2.gradientArray[i] * f2.gradientArray[j] * f1.gradientArray[k] + f2.gradientArray[i] * f1.gradientArray[j] * f2.gradientArray[k] + f1.gradientArray[i] * f2.gradientArray[j] * f2.gradientArray[k]); } } } } } } } } public double[] ToGradientArray() { if (gradientArray == null) { return null; } return (double[])gradientArray.Clone(); } public double[] ToHessianArray() { if (hessianArray == null) { return null; } return (double[])hessianArray.Clone(); } public double[] ToThirdArray() { if (thirdArray == null) { return null; } return (double[])thirdArray.Clone(); } /// <summary> /// Size of the linearized Hessian array given the size of the gradient. /// </summary> public static int HessianSize(int n) { if (n < 0) { throw new ArgumentOutOfRangeException(); } return n * (n + 1) / 2; } /// <summary> /// Size of the array of third partial derivatives given the size of the gradient. /// </summary> public static int ThirdSize(int n) { if (n < 0) { throw new ArgumentOutOfRangeException(); } return n * (n + 1) * (n + 2) / 6; } /// <summary> /// Size of the array of third partial derivatives given the size of the gradient, /// where only some of the third derivatives are fully computed. /// </summary> public static int ThirdReducedSize(int n, int n0) { if (n0 < 0 || n0 > n) { throw new ArgumentOutOfRangeException(); } // Mathematica: Sum[Sum[Sum[1,{k,j,n-1}],{j,i,n-1}],{i,0,n0-1}] return n0 * (2 + 3 * n * (n - n0 + 2) + n0 * (n0 - 3)) / 6; } public static int HessianIndex(int n, int i, int j) { if (i > j) { return HessianIndex(n, j, i); } // Now i <= j as required. if (i < 0 || j >= n) { throw new ArgumentOutOfRangeException(); } // This is the same as: // return HessianSize(n) - HessianSize(n - i) + j - i; return i * (1 - i) / 2 + i * n + j - i; } public static int ThirdIndex(int n, int n0, int i, int j, int k) { return ThirdReducedIndex(n, n, i, j, k); } public static int ThirdReducedIndex(int n, int n0, int i, int j, int k) { if (i > j) { return ThirdReducedIndex(n, n0, j, i, k); } if (j > k) { return ThirdReducedIndex(n, n0, i, k, j); } // Now i <= j and j <= k as required. if (i < 0 || i >= n0 || k >= n) { throw new ArgumentOutOfRangeException(); } // Find a formula for this. throw new NotImplementedException(); } public static ExtendedDualNumber Basis(double value, int n, int i) { return Basis(value, n, i, n); } public static ExtendedDualNumber Basis(double value, int n, int i, int n0) { return new ExtendedDualNumber(value, Vector.Basis(n, i), Matrix.Zero(n, n), n0); } public static ExtendedDualNumber Exp(ExtendedDualNumber f) { double g = Math.Exp(f.value); double g1 = g; double g11 = g; double g111 = g; return new ExtendedDualNumber(f, g, g1, g11, g111); } public static ExtendedDualNumber Log(ExtendedDualNumber f) { double g = Math.Log(f.value); double g1 = 1.0 / f.value; double g11 = -g1 / f.value; double g111 = -2.0 * g11 / f.value; return new ExtendedDualNumber(f, g, g1, g11, g111); } public static ExtendedDualNumber Sqr(ExtendedDualNumber f) { return new ExtendedDualNumber(f, f.value * f.value, 2.0 * f.value, 2.0, 0.0); } public static ExtendedDualNumber Sqrt(ExtendedDualNumber f) { double g = Math.Sqrt(f.value); double g1 = 0.5 / g; double g11 = -0.5 * g1 / f.value; double g111 = -3.0 * g11 / (2.0 * f.value); return new ExtendedDualNumber(f, g, g1, g11, g111); } public static ExtendedDualNumber Pow(ExtendedDualNumber f1, ExtendedDualNumber f2) { // FIXME Optimize this! double g = Math.Pow(f1.value, f2.value); double g1 = f2.value * Math.Pow(f1.value, f2.value - 1.0); double g2 = Math.Log(f1.value) * Math.Pow(f1.value, f2.value); double g11 = f2.value * (f2.value - 1.0) * Math.Pow(f1.value, f2.value - 2.0); double g22 = Math.Log(f1.value) * Math.Log(f1.value) * Math.Pow(f1.value, f2.value); double g12 = Math.Pow(f1.value, f2.value - 1.0) * (1.0 + Math.Log(f1.value) * f2.value); double g111 = f2.value * (f2.value - 1.0) * (f2.value - 2.0) * Math.Pow(f1.value, f2.value - 3.0); double g222 = Math.Log(f1.value) * Math.Log(f1.value) * Math.Log(f1.value) * Math.Pow(f1.value, f2.value); double g112 = (2.0 * f2.value - 1.0 + f2.value * (f2.value - 1.0) * Math.Log(f1.value)) * Math.Pow(f1.value, f2.value - 2.0); double g122 = 2.0 * Math.Log(f1.value) / f1.value * Math.Pow(f1.value, f2.value) + Math.Log(f1.value) * Math.Log(f1.value) * f2.value * Math.Pow(f1.value, f2.value - 1.0); return new ExtendedDualNumber(f1, f2, g, g1, g2, g11, g12, g22, g111, g112, g122, g222); } public static ExtendedDualNumber Cos(ExtendedDualNumber f) { double g = Math.Cos(f.value); double g111 = Math.Sin(f.value); double g1 = -g111; double g11 = -g; return new ExtendedDualNumber(f, g, g1, g11, g111); } public static ExtendedDualNumber Sin(ExtendedDualNumber f) { double g = Math.Sin(f.value); double g1 = Math.Cos(f.value); double g11 = -g; double g111 = -g1; return new ExtendedDualNumber(f, g, g1, g11, g111); } public static implicit operator ExtendedDualNumber(double a) { if (a == 0.0) { return zero; } return new ExtendedDualNumber(a); } public static ExtendedDualNumber operator +(ExtendedDualNumber f1, ExtendedDualNumber f2) { return new ExtendedDualNumber(f1, f2, f1.value + f2.value, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); } public static ExtendedDualNumber operator -(ExtendedDualNumber f) { return new ExtendedDualNumber(f, -f.value, -1.0, 0.0, 0.0); } public static ExtendedDualNumber operator -(ExtendedDualNumber f1, ExtendedDualNumber f2) { return new ExtendedDualNumber(f1, f2, f1.value - f2.value, 1.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); } public static ExtendedDualNumber operator *(ExtendedDualNumber f1, ExtendedDualNumber f2) { return new ExtendedDualNumber(f1, f2, f1.value * f2.value, f2.value, f1.value, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0); } public static ExtendedDualNumber operator /(ExtendedDualNumber f1, ExtendedDualNumber f2) { double g = f1.value / f2.value; double g1 = 1.0 / f2.value; double g2 = -g / f2.value; double g11 = 0.0; double g12 = -g1 / f2.value; double g22 = -2.0 * g2 / f2.value; double g111 = 0.0; double g112 = 0.0; double g122 = 2.0 / (f2.value * f2.value * f2.value); // FIXME optimize! double g222 = -6.0 * f1.value / (f2.value * f2.value * f2.value * f2.value); return new ExtendedDualNumber(f1, f2, g, g1, g2, g11, g12, g22, g111, g112, g122, g222); } /// <summary> /// Number of variables. /// </summary> public int N { get { return n; } } /// <summary> /// Number of fully computed variables in third derivatives. /// </summary> public int N0 { get { return n0; } } /// <summary> /// The numerical value of the <see cref="DualNumber" />, i.e. the pure value without derivatives. /// </summary> public double Value { get { return value; } } /// <summary> /// A <see cref="Vector" /> representation of the gradient. /// </summary> public Vector Gradient { get { if (gradient == null && gradientArray != null) { gradient = new Vector(gradientArray); } return gradient; } } /// <summary> /// A <see cref="Matrix " /> representation of the Hessian. The Hessian is converted from the internal /// linearized representation as returned by <see cref="ToHessianArray" />. /// </summary> public Matrix Hessian { get { if (hessian == null && hessianArray != null) { double[,] a = new double[n, n]; for (int i = 0, k = 0; i < n; i++) { for (int j = i; j < n; j++, k++) { a[i, j] = a[j, i] = hessianArray[k]; } } hessian = new Matrix(a); } return hessian; } } /// <summary> /// A <see cref="Tensor " /> representation of the third derivatives. Converted from the internal /// linearized representation as returned by <see cref="ToThirdArray" />. /// </summary> public Tensor Third { get { if (third == null && thirdArray != null) { double[, ,] a = new double[n0, n, n]; for (int i = 0, m = 0; i < n0; i++) { for (int j = i; j < n; j++) { for (int k = j; k < n; k++, m++) { a[i, j, k] = a[i, k, j] = thirdArray[m]; if (j < n0) { a[j, i, k] = a[j, k, i] = thirdArray[m]; } if (k < n0) { a[k, i, j] = a[k, j, i] = thirdArray[m]; } } } } third = new Tensor(a); } return third; } } /*private class ThirdTensor : Tensor { private int n, n0; private double[] thirdArray; public ThirdTensor(int n, int n0, double[] thirdArray) : base(null) { this.n = n; this.n0 = n0; this.thirdArray = thirdArray; } public override double this[int i, int j, int k] { get { return thirdArray[ExtendedDualNumber.ThirdReducedIndex(n, n0, i, j, k)]; } } public override double[, ,] ToArray() { double[, ,] a = new double[n0, n, n]; for (int i = 0, m = 0; i < n0; i++) { for (int j = i; j < n; j++) { for (int k = j; k < n; k++, m++) { a[i, j, k] = a[i, k, j] = thirdArray[m]; if (j < n0) { a[j, i, k] = a[j, k, i] = thirdArray[m]; } if (k < n0) { a[k, i, j] = a[k, j, i] = thirdArray[m]; } } } } return a; } }*/ } }
#region License /* ********************************************************************************** * Copyright (c) Roman Ivantsov * This source code is subject to terms and conditions of the MIT License * for Irony. A copy of the license can be found in the License.txt file * at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * MIT License. * You must not remove this notice from this software. * **********************************************************************************/ #endregion using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Text; using System.Runtime.InteropServices; using System.Diagnostics; using System.Globalization; namespace Irony.Parsing { [Flags] public enum ParseOptions { Reserved = 0x01, AnalyzeCode = 0x10, //run code analysis; effective only in Module mode } public enum ParseMode { File, //default, continuous input file VsLineScan, // line-by-line scanning in VS integration for syntax highlighting CommandLine, //line-by-line from console } public enum ParserStatus { Init, //initial state Parsing, Previewing, //previewing tokens Recovering, //recovering from error Accepted, AcceptedPartial, Error, } // The purpose of this class is to provide a container for information shared // between parser, scanner and token filters. public partial class ParsingContext { public readonly Parser Parser; public readonly LanguageData Language; //Parser settings public ParseOptions Options; public bool TracingEnabled; public ParseMode Mode = ParseMode.File; public int MaxErrors = 20; //maximum error count to report public CultureInfo Culture; //defaults to Grammar.DefaultCulture, might be changed by app code #region properties and fields //Parser fields public ParseTree CurrentParseTree { get; internal set; } public readonly TokenStack OpenBraces = new TokenStack(); public ParserTrace ParserTrace = new ParserTrace(); internal readonly ParserStack ParserStack = new ParserStack(); public ParserState CurrentParserState { get; internal set; } public ParseTreeNode CurrentParserInput { get; internal set; } public Token CurrentToken; //The token just scanned by Scanner public TokenList CurrentCommentTokens = new TokenList(); //accumulated comment tokens public Token PreviousToken; public SourceLocation PreviousLineStart; //Location of last line start //list for terminals - for current parser state and current input char public TerminalList CurrentTerminals = new TerminalList(); public ISourceStream Source; //Internal fields internal TokenFilterList TokenFilters = new TokenFilterList(); internal TokenStack BufferedTokens = new TokenStack(); internal IEnumerator<Token> FilteredTokens; //stream of tokens after filter internal TokenStack PreviewTokens = new TokenStack(); internal ParsingEventArgs SharedParsingEventArgs; internal ValidateTokenEventArgs SharedValidateTokenEventArgs; public VsScannerStateMap VsLineScanState; //State variable used in line scanning mode for VS integration public ParserStatus Status { get; internal set; } public bool HasErrors; //error flag, once set remains set //values dictionary to use by custom language implementations to save some temporary values during parsing public readonly Dictionary<string, object> Values = new Dictionary<string, object>(); public int TabWidth = 8; #endregion #region constructors public ParsingContext(Parser parser) { this.Parser = parser; this.Language = this.Parser.Language; this.Culture = this.Language.Grammar.DefaultCulture; //This might be a problem for multi-threading - if we have several contexts on parallel threads with different culture. //Resources.Culture is static property (this is not Irony's fault, this is auto-generated file). Resources.Culture = this.Culture; this.SharedParsingEventArgs = new ParsingEventArgs(this); this.SharedValidateTokenEventArgs = new ValidateTokenEventArgs(this); } #endregion #region Events: TokenCreated public event EventHandler<ParsingEventArgs> TokenCreated; internal void OnTokenCreated() { if (this.TokenCreated != null) { this.TokenCreated(this, this.SharedParsingEventArgs); } } #endregion #region Error handling and tracing public Token CreateErrorToken(string message, params object[] args) { if (args != null && args.Length > 0) { message = string.Format(message, args); } return this.Source.CreateToken(this.Language.Grammar.SyntaxError, message); } public void AddParserError(string message, params object[] args) { var location = this.CurrentParserInput == null ? this.Source.Location : this.CurrentParserInput.Span.Location; this.HasErrors = true; this.AddParserMessage(ErrorLevel.Error, location, message, args); } public void AddParserMessage(ErrorLevel level, SourceLocation location, string message, params object[] args) { if (this.CurrentParseTree == null) { return; } if (this.CurrentParseTree.ParserMessages.Count >= this.MaxErrors) { return; } if (args != null && args.Length > 0) { message = string.Format(message, args); } this.CurrentParseTree.ParserMessages.Add(new LogMessage(level, location, message, this.CurrentParserState)); if (this.TracingEnabled) { this.AddTrace(true, message); } } public void AddTrace(string message, params object[] args) { this.AddTrace(false, message, args); } public void AddTrace(bool asError, string message, params object[] args) { if (!this.TracingEnabled) { return; } if (args != null && args.Length > 0) { message = string.Format(message, args); } this.ParserTrace.Add(new ParserTraceEntry(this.CurrentParserState, this.ParserStack.Top, this.CurrentParserInput, message, asError)); } #region comments // Computes set of expected terms in a parser state. While there may be extended list of symbols expected at some point, // we want to reorganize and reduce it. For example, if the current state expects all arithmetic operators as an input, // it would be better to not list all operators (+, -, *, /, etc) but simply put "operator" covering them all. // To achieve this grammar writer can group operators (or any other terminals) into named groups using Grammar's methods // AddTermReportGroup, AddNoReportGroup etc. Then instead of reporting each operator separately, Irony would include // a single "group name" to represent them all. // The "expected report set" is not computed during parser construction (it would take considerable time), // but does it on demand during parsing, when error is detected and the expected set is actually needed for error message. // Multi-threading concerns. When used in multi-threaded environment (web server), the LanguageData would be shared in // application-wide cache to avoid rebuilding the parser data on every request. The LanguageData is immutable, except // this one case - the expected sets are constructed late by CoreParser on the when-needed basis. // We don't do any locking here, just compute the set and on return from this function the state field is assigned. // We assume that this field assignment is an atomic, concurrency-safe operation. The worst thing that might happen // is "double-effort" when two threads start computing the same set around the same time, and the last one to finish would // leave its result in the state field. #endregion internal static StringSet ComputeGroupedExpectedSetForState(Grammar grammar, ParserState state) { var terms = new TerminalSet(); terms.UnionWith(state.ExpectedTerminals); var result = new StringSet(); //Eliminate no-report terminals foreach (var group in grammar.TermReportGroups) { if (group.GroupType == TermReportGroupType.DoNotReport) { terms.ExceptWith(group.Terminals); } } //Add normal and operator groups foreach (var group in grammar.TermReportGroups) { if ((group.GroupType == TermReportGroupType.Normal || group.GroupType == TermReportGroupType.Operator) && terms.Overlaps(group.Terminals)) { result.Add(group.Alias); terms.ExceptWith(group.Terminals); } } //Add remaining terminals "as is" foreach (var terminal in terms) { result.Add(terminal.ErrorAlias); } return result; } #endregion internal void Reset() { this.CurrentParserState = this.Parser.InitialState; this.CurrentParserInput = null; this.CurrentCommentTokens = new TokenList(); this.ParserStack.Clear(); this.HasErrors = false; this.ParserStack.Push(new ParseTreeNode(this.CurrentParserState)); this.CurrentParseTree = null; this.OpenBraces.Clear(); this.ParserTrace.Clear(); this.CurrentTerminals.Clear(); this.CurrentToken = null; this.PreviousToken = null; this.PreviousLineStart = new SourceLocation(0, -1, 0); this.BufferedTokens.Clear(); this.PreviewTokens.Clear(); this.Values.Clear(); foreach (var filter in this.TokenFilters) { filter.Reset(); } } public void SetSourceLocation(SourceLocation location) { foreach (var filter in this.TokenFilters) { filter.OnSetSourceLocation(location); } this.Source.Location = location; } public SourceSpan ComputeStackRangeSpan(int nodeCount) { if (nodeCount == 0) { return new SourceSpan(this.CurrentParserInput.Span.Location, 0); } var first = this.ParserStack[this.ParserStack.Count - nodeCount]; var last = this.ParserStack.Top; return new SourceSpan(first.Span.Location, last.Span.EndPosition - first.Span.Location.Position); } #region Expected term set computations public StringSet GetExpectedTermSet() { if (this.CurrentParserState == null) { return new StringSet(); } //See note about multi-threading issues in ComputeReportedExpectedSet comments. if (this.CurrentParserState.ReportedExpectedSet == null) { this.CurrentParserState.ReportedExpectedSet = Construction.ParserDataBuilder.ComputeGroupedExpectedSetForState(this.Language.Grammar, this.CurrentParserState); } //Filter out closing braces which are not expected based on previous input. // While the closing parenthesis ")" might be expected term in a state in general, // if there was no opening parenthesis in preceding input then we would not // expect a closing one. var expectedSet = this.FilterBracesInExpectedSet(this.CurrentParserState.ReportedExpectedSet); return expectedSet; } private StringSet FilterBracesInExpectedSet(StringSet stateExpectedSet) { var result = new StringSet(); result.UnionWith(stateExpectedSet); //Find what brace we expect var nextClosingBrace = string.Empty; if (this.OpenBraces.Count > 0) { var lastOpenBraceTerm = this.OpenBraces.Peek().KeyTerm; var nextClosingBraceTerm = lastOpenBraceTerm.IsPairFor as KeyTerm; if (nextClosingBraceTerm != null) { nextClosingBrace = nextClosingBraceTerm.Text; } } //Now check all closing braces in result set, and leave only nextClosingBrace foreach (var term in this.Language.Grammar.KeyTerms.Values) { if (term.Flags.IsSet(TermFlags.IsCloseBrace)) { var brace = term.Text; if (result.Contains(brace) && brace != nextClosingBrace) { result.Remove(brace); } } }//foreach term return result; } #endregion }//class // A struct used for packing/unpacking ScannerState int value; used for VS integration. // When Terminal produces incomplete token, it sets // this state to non-zero value; this value identifies this terminal as the one who will continue scanning when // it resumes, and the terminal's internal state when there may be several types of multi-line tokens for one terminal. // For ex., there maybe several types of string literal like in Python. [StructLayout(LayoutKind.Explicit)] public struct VsScannerStateMap { [FieldOffset(0)] public int Value; [FieldOffset(0)] public byte TerminalIndex; //1-based index of active multiline term in MultilineTerminals [FieldOffset(1)] public byte TokenSubType; //terminal subtype (used in StringLiteral to identify string kind) [FieldOffset(2)] public short TerminalFlags; //Terminal flags }//struct }
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 RemFormulario class. /// </summary> [Serializable] public partial class RemFormularioCollection : ActiveList<RemFormulario, RemFormularioCollection> { public RemFormularioCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>RemFormularioCollection</returns> public RemFormularioCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { RemFormulario 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 Rem_Formulario table. /// </summary> [Serializable] public partial class RemFormulario : ActiveRecord<RemFormulario>, IActiveRecord { #region .ctors and Default Settings public RemFormulario() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public RemFormulario(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public RemFormulario(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public RemFormulario(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("Rem_Formulario", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdFormulario = new TableSchema.TableColumn(schema); colvarIdFormulario.ColumnName = "idFormulario"; colvarIdFormulario.DataType = DbType.Int32; colvarIdFormulario.MaxLength = 0; colvarIdFormulario.AutoIncrement = true; colvarIdFormulario.IsNullable = false; colvarIdFormulario.IsPrimaryKey = true; colvarIdFormulario.IsForeignKey = false; colvarIdFormulario.IsReadOnly = false; colvarIdFormulario.DefaultSetting = @""; colvarIdFormulario.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdFormulario); 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 = @"((0))"; colvarIdEfector.ForeignKeyTableName = "Sys_Efector"; schema.Columns.Add(colvarIdEfector); TableSchema.TableColumn colvarIdPaciente = new TableSchema.TableColumn(schema); colvarIdPaciente.ColumnName = "idPaciente"; colvarIdPaciente.DataType = DbType.Int32; colvarIdPaciente.MaxLength = 0; colvarIdPaciente.AutoIncrement = false; colvarIdPaciente.IsNullable = false; colvarIdPaciente.IsPrimaryKey = false; colvarIdPaciente.IsForeignKey = true; colvarIdPaciente.IsReadOnly = false; colvarIdPaciente.DefaultSetting = @"((0))"; colvarIdPaciente.ForeignKeyTableName = "Sys_Paciente"; schema.Columns.Add(colvarIdPaciente); TableSchema.TableColumn colvarIdObraSocial = new TableSchema.TableColumn(schema); colvarIdObraSocial.ColumnName = "idObraSocial"; colvarIdObraSocial.DataType = DbType.Int32; colvarIdObraSocial.MaxLength = 0; colvarIdObraSocial.AutoIncrement = false; colvarIdObraSocial.IsNullable = false; colvarIdObraSocial.IsPrimaryKey = false; colvarIdObraSocial.IsForeignKey = true; colvarIdObraSocial.IsReadOnly = false; colvarIdObraSocial.DefaultSetting = @""; colvarIdObraSocial.ForeignKeyTableName = "Sys_ObraSocial"; schema.Columns.Add(colvarIdObraSocial); TableSchema.TableColumn colvarNumeroFormulario = new TableSchema.TableColumn(schema); colvarNumeroFormulario.ColumnName = "numeroFormulario"; colvarNumeroFormulario.DataType = DbType.Int32; colvarNumeroFormulario.MaxLength = 0; colvarNumeroFormulario.AutoIncrement = false; colvarNumeroFormulario.IsNullable = false; colvarNumeroFormulario.IsPrimaryKey = false; colvarNumeroFormulario.IsForeignKey = false; colvarNumeroFormulario.IsReadOnly = false; colvarNumeroFormulario.DefaultSetting = @"((0))"; colvarNumeroFormulario.ForeignKeyTableName = ""; schema.Columns.Add(colvarNumeroFormulario); TableSchema.TableColumn colvarFechaEmpadronamiento = new TableSchema.TableColumn(schema); colvarFechaEmpadronamiento.ColumnName = "fechaEmpadronamiento"; colvarFechaEmpadronamiento.DataType = DbType.DateTime; colvarFechaEmpadronamiento.MaxLength = 0; colvarFechaEmpadronamiento.AutoIncrement = false; colvarFechaEmpadronamiento.IsNullable = false; colvarFechaEmpadronamiento.IsPrimaryKey = false; colvarFechaEmpadronamiento.IsForeignKey = false; colvarFechaEmpadronamiento.IsReadOnly = false; colvarFechaEmpadronamiento.DefaultSetting = @"(((1)/(1))/(1900))"; colvarFechaEmpadronamiento.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaEmpadronamiento); TableSchema.TableColumn colvarIdAgente = new TableSchema.TableColumn(schema); colvarIdAgente.ColumnName = "idAgente"; colvarIdAgente.DataType = DbType.Int32; colvarIdAgente.MaxLength = 0; colvarIdAgente.AutoIncrement = false; colvarIdAgente.IsNullable = true; colvarIdAgente.IsPrimaryKey = false; colvarIdAgente.IsForeignKey = true; colvarIdAgente.IsReadOnly = false; colvarIdAgente.DefaultSetting = @"((0))"; colvarIdAgente.ForeignKeyTableName = "Rem_Agente"; schema.Columns.Add(colvarIdAgente); TableSchema.TableColumn colvarIdMunicipio = new TableSchema.TableColumn(schema); colvarIdMunicipio.ColumnName = "idMunicipio"; colvarIdMunicipio.DataType = DbType.Int32; colvarIdMunicipio.MaxLength = 0; colvarIdMunicipio.AutoIncrement = false; colvarIdMunicipio.IsNullable = false; colvarIdMunicipio.IsPrimaryKey = false; colvarIdMunicipio.IsForeignKey = true; colvarIdMunicipio.IsReadOnly = false; colvarIdMunicipio.DefaultSetting = @"((0))"; colvarIdMunicipio.ForeignKeyTableName = "Sys_Municipio"; schema.Columns.Add(colvarIdMunicipio); TableSchema.TableColumn colvarSexo = new TableSchema.TableColumn(schema); colvarSexo.ColumnName = "sexo"; colvarSexo.DataType = DbType.Int32; colvarSexo.MaxLength = 0; colvarSexo.AutoIncrement = false; colvarSexo.IsNullable = false; colvarSexo.IsPrimaryKey = false; colvarSexo.IsForeignKey = false; colvarSexo.IsReadOnly = false; colvarSexo.DefaultSetting = @"((0))"; colvarSexo.ForeignKeyTableName = ""; schema.Columns.Add(colvarSexo); TableSchema.TableColumn colvarEdad = new TableSchema.TableColumn(schema); colvarEdad.ColumnName = "edad"; colvarEdad.DataType = DbType.Int32; colvarEdad.MaxLength = 0; colvarEdad.AutoIncrement = false; colvarEdad.IsNullable = false; colvarEdad.IsPrimaryKey = false; colvarEdad.IsForeignKey = false; colvarEdad.IsReadOnly = false; colvarEdad.DefaultSetting = @"((0))"; colvarEdad.ForeignKeyTableName = ""; schema.Columns.Add(colvarEdad); TableSchema.TableColumn colvarHta2 = new TableSchema.TableColumn(schema); colvarHta2.ColumnName = "hta2"; colvarHta2.DataType = DbType.Int32; colvarHta2.MaxLength = 0; colvarHta2.AutoIncrement = false; colvarHta2.IsNullable = false; colvarHta2.IsPrimaryKey = false; colvarHta2.IsForeignKey = false; colvarHta2.IsReadOnly = false; colvarHta2.DefaultSetting = @"((0))"; colvarHta2.ForeignKeyTableName = ""; schema.Columns.Add(colvarHta2); TableSchema.TableColumn colvarHta3 = new TableSchema.TableColumn(schema); colvarHta3.ColumnName = "hta3"; colvarHta3.DataType = DbType.Int32; colvarHta3.MaxLength = 0; colvarHta3.AutoIncrement = false; colvarHta3.IsNullable = false; colvarHta3.IsPrimaryKey = false; colvarHta3.IsForeignKey = false; colvarHta3.IsReadOnly = false; colvarHta3.DefaultSetting = @"((0))"; colvarHta3.ForeignKeyTableName = ""; schema.Columns.Add(colvarHta3); TableSchema.TableColumn colvarColesterol4 = new TableSchema.TableColumn(schema); colvarColesterol4.ColumnName = "colesterol4"; colvarColesterol4.DataType = DbType.Int32; colvarColesterol4.MaxLength = 0; colvarColesterol4.AutoIncrement = false; colvarColesterol4.IsNullable = false; colvarColesterol4.IsPrimaryKey = false; colvarColesterol4.IsForeignKey = false; colvarColesterol4.IsReadOnly = false; colvarColesterol4.DefaultSetting = @"((0))"; colvarColesterol4.ForeignKeyTableName = ""; schema.Columns.Add(colvarColesterol4); TableSchema.TableColumn colvarColesterol5 = new TableSchema.TableColumn(schema); colvarColesterol5.ColumnName = "colesterol5"; colvarColesterol5.DataType = DbType.Int32; colvarColesterol5.MaxLength = 0; colvarColesterol5.AutoIncrement = false; colvarColesterol5.IsNullable = false; colvarColesterol5.IsPrimaryKey = false; colvarColesterol5.IsForeignKey = false; colvarColesterol5.IsReadOnly = false; colvarColesterol5.DefaultSetting = @"((0))"; colvarColesterol5.ForeignKeyTableName = ""; schema.Columns.Add(colvarColesterol5); TableSchema.TableColumn colvarDtm26 = new TableSchema.TableColumn(schema); colvarDtm26.ColumnName = "dtm26"; colvarDtm26.DataType = DbType.Int32; colvarDtm26.MaxLength = 0; colvarDtm26.AutoIncrement = false; colvarDtm26.IsNullable = false; colvarDtm26.IsPrimaryKey = false; colvarDtm26.IsForeignKey = false; colvarDtm26.IsReadOnly = false; colvarDtm26.DefaultSetting = @"((0))"; colvarDtm26.ForeignKeyTableName = ""; schema.Columns.Add(colvarDtm26); TableSchema.TableColumn colvarDtm27 = new TableSchema.TableColumn(schema); colvarDtm27.ColumnName = "dtm27"; colvarDtm27.DataType = DbType.Int32; colvarDtm27.MaxLength = 0; colvarDtm27.AutoIncrement = false; colvarDtm27.IsNullable = false; colvarDtm27.IsPrimaryKey = false; colvarDtm27.IsForeignKey = false; colvarDtm27.IsReadOnly = false; colvarDtm27.DefaultSetting = @"((0))"; colvarDtm27.ForeignKeyTableName = ""; schema.Columns.Add(colvarDtm27); TableSchema.TableColumn colvarEcv8 = new TableSchema.TableColumn(schema); colvarEcv8.ColumnName = "ecv8"; colvarEcv8.DataType = DbType.Int32; colvarEcv8.MaxLength = 0; colvarEcv8.AutoIncrement = false; colvarEcv8.IsNullable = false; colvarEcv8.IsPrimaryKey = false; colvarEcv8.IsForeignKey = false; colvarEcv8.IsReadOnly = false; colvarEcv8.DefaultSetting = @"((0))"; colvarEcv8.ForeignKeyTableName = ""; schema.Columns.Add(colvarEcv8); TableSchema.TableColumn colvarTabaco9 = new TableSchema.TableColumn(schema); colvarTabaco9.ColumnName = "tabaco9"; colvarTabaco9.DataType = DbType.Int32; colvarTabaco9.MaxLength = 0; colvarTabaco9.AutoIncrement = false; colvarTabaco9.IsNullable = false; colvarTabaco9.IsPrimaryKey = false; colvarTabaco9.IsForeignKey = false; colvarTabaco9.IsReadOnly = false; colvarTabaco9.DefaultSetting = @"((0))"; colvarTabaco9.ForeignKeyTableName = ""; schema.Columns.Add(colvarTabaco9); TableSchema.TableColumn colvarSumatoria = new TableSchema.TableColumn(schema); colvarSumatoria.ColumnName = "sumatoria"; colvarSumatoria.DataType = DbType.Int32; colvarSumatoria.MaxLength = 0; colvarSumatoria.AutoIncrement = false; colvarSumatoria.IsNullable = false; colvarSumatoria.IsPrimaryKey = false; colvarSumatoria.IsForeignKey = false; colvarSumatoria.IsReadOnly = false; colvarSumatoria.DefaultSetting = @"((0))"; colvarSumatoria.ForeignKeyTableName = ""; schema.Columns.Add(colvarSumatoria); TableSchema.TableColumn colvarPoseeFirma = new TableSchema.TableColumn(schema); colvarPoseeFirma.ColumnName = "poseeFirma"; colvarPoseeFirma.DataType = DbType.Boolean; colvarPoseeFirma.MaxLength = 0; colvarPoseeFirma.AutoIncrement = false; colvarPoseeFirma.IsNullable = false; colvarPoseeFirma.IsPrimaryKey = false; colvarPoseeFirma.IsForeignKey = false; colvarPoseeFirma.IsReadOnly = false; colvarPoseeFirma.DefaultSetting = @"((1))"; colvarPoseeFirma.ForeignKeyTableName = ""; schema.Columns.Add(colvarPoseeFirma); TableSchema.TableColumn colvarCreatedBy = new TableSchema.TableColumn(schema); colvarCreatedBy.ColumnName = "CreatedBy"; colvarCreatedBy.DataType = DbType.Int32; colvarCreatedBy.MaxLength = 0; colvarCreatedBy.AutoIncrement = false; colvarCreatedBy.IsNullable = false; colvarCreatedBy.IsPrimaryKey = false; colvarCreatedBy.IsForeignKey = true; colvarCreatedBy.IsReadOnly = false; colvarCreatedBy.DefaultSetting = @"((0))"; colvarCreatedBy.ForeignKeyTableName = "Sys_Usuario"; 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 = false; colvarCreatedOn.IsPrimaryKey = false; colvarCreatedOn.IsForeignKey = false; colvarCreatedOn.IsReadOnly = false; colvarCreatedOn.DefaultSetting = @"(((1)/(1))/(1900))"; colvarCreatedOn.ForeignKeyTableName = ""; schema.Columns.Add(colvarCreatedOn); TableSchema.TableColumn colvarModifiedBy = new TableSchema.TableColumn(schema); colvarModifiedBy.ColumnName = "ModifiedBy"; colvarModifiedBy.DataType = DbType.Int32; colvarModifiedBy.MaxLength = 0; colvarModifiedBy.AutoIncrement = false; colvarModifiedBy.IsNullable = false; colvarModifiedBy.IsPrimaryKey = false; colvarModifiedBy.IsForeignKey = true; colvarModifiedBy.IsReadOnly = false; colvarModifiedBy.DefaultSetting = @"((0))"; colvarModifiedBy.ForeignKeyTableName = "Sys_Usuario"; 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 = false; colvarModifiedOn.IsPrimaryKey = false; colvarModifiedOn.IsForeignKey = false; colvarModifiedOn.IsReadOnly = false; colvarModifiedOn.DefaultSetting = @"(((1)/(1))/(1900))"; colvarModifiedOn.ForeignKeyTableName = ""; schema.Columns.Add(colvarModifiedOn); TableSchema.TableColumn colvarCentros = new TableSchema.TableColumn(schema); colvarCentros.ColumnName = "centros"; colvarCentros.DataType = DbType.AnsiString; colvarCentros.MaxLength = 50; colvarCentros.AutoIncrement = false; colvarCentros.IsNullable = false; colvarCentros.IsPrimaryKey = false; colvarCentros.IsForeignKey = false; colvarCentros.IsReadOnly = false; colvarCentros.DefaultSetting = @"('')"; colvarCentros.ForeignKeyTableName = ""; schema.Columns.Add(colvarCentros); TableSchema.TableColumn colvarVacunasCompletas = new TableSchema.TableColumn(schema); colvarVacunasCompletas.ColumnName = "vacunasCompletas"; colvarVacunasCompletas.DataType = DbType.Int32; colvarVacunasCompletas.MaxLength = 0; colvarVacunasCompletas.AutoIncrement = false; colvarVacunasCompletas.IsNullable = false; colvarVacunasCompletas.IsPrimaryKey = false; colvarVacunasCompletas.IsForeignKey = false; colvarVacunasCompletas.IsReadOnly = false; colvarVacunasCompletas.DefaultSetting = @"((0))"; colvarVacunasCompletas.ForeignKeyTableName = ""; schema.Columns.Add(colvarVacunasCompletas); TableSchema.TableColumn colvarPap = new TableSchema.TableColumn(schema); colvarPap.ColumnName = "pap"; colvarPap.DataType = DbType.Int32; colvarPap.MaxLength = 0; colvarPap.AutoIncrement = false; colvarPap.IsNullable = false; colvarPap.IsPrimaryKey = false; colvarPap.IsForeignKey = false; colvarPap.IsReadOnly = false; colvarPap.DefaultSetting = @"((0))"; colvarPap.ForeignKeyTableName = ""; schema.Columns.Add(colvarPap); 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 = @"((0))"; colvarIdProfesional.ForeignKeyTableName = "Sys_Profesional"; schema.Columns.Add(colvarIdProfesional); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Rem_Formulario",schema); } } #endregion #region Props [XmlAttribute("IdFormulario")] [Bindable(true)] public int IdFormulario { get { return GetColumnValue<int>(Columns.IdFormulario); } set { SetColumnValue(Columns.IdFormulario, value); } } [XmlAttribute("IdEfector")] [Bindable(true)] public int IdEfector { get { return GetColumnValue<int>(Columns.IdEfector); } set { SetColumnValue(Columns.IdEfector, value); } } [XmlAttribute("IdPaciente")] [Bindable(true)] public int IdPaciente { get { return GetColumnValue<int>(Columns.IdPaciente); } set { SetColumnValue(Columns.IdPaciente, value); } } [XmlAttribute("IdObraSocial")] [Bindable(true)] public int IdObraSocial { get { return GetColumnValue<int>(Columns.IdObraSocial); } set { SetColumnValue(Columns.IdObraSocial, value); } } [XmlAttribute("NumeroFormulario")] [Bindable(true)] public int NumeroFormulario { get { return GetColumnValue<int>(Columns.NumeroFormulario); } set { SetColumnValue(Columns.NumeroFormulario, value); } } [XmlAttribute("FechaEmpadronamiento")] [Bindable(true)] public DateTime FechaEmpadronamiento { get { return GetColumnValue<DateTime>(Columns.FechaEmpadronamiento); } set { SetColumnValue(Columns.FechaEmpadronamiento, value); } } [XmlAttribute("IdAgente")] [Bindable(true)] public int? IdAgente { get { return GetColumnValue<int?>(Columns.IdAgente); } set { SetColumnValue(Columns.IdAgente, value); } } [XmlAttribute("IdMunicipio")] [Bindable(true)] public int IdMunicipio { get { return GetColumnValue<int>(Columns.IdMunicipio); } set { SetColumnValue(Columns.IdMunicipio, value); } } [XmlAttribute("Sexo")] [Bindable(true)] public int Sexo { get { return GetColumnValue<int>(Columns.Sexo); } set { SetColumnValue(Columns.Sexo, value); } } [XmlAttribute("Edad")] [Bindable(true)] public int Edad { get { return GetColumnValue<int>(Columns.Edad); } set { SetColumnValue(Columns.Edad, value); } } [XmlAttribute("Hta2")] [Bindable(true)] public int Hta2 { get { return GetColumnValue<int>(Columns.Hta2); } set { SetColumnValue(Columns.Hta2, value); } } [XmlAttribute("Hta3")] [Bindable(true)] public int Hta3 { get { return GetColumnValue<int>(Columns.Hta3); } set { SetColumnValue(Columns.Hta3, value); } } [XmlAttribute("Colesterol4")] [Bindable(true)] public int Colesterol4 { get { return GetColumnValue<int>(Columns.Colesterol4); } set { SetColumnValue(Columns.Colesterol4, value); } } [XmlAttribute("Colesterol5")] [Bindable(true)] public int Colesterol5 { get { return GetColumnValue<int>(Columns.Colesterol5); } set { SetColumnValue(Columns.Colesterol5, value); } } [XmlAttribute("Dtm26")] [Bindable(true)] public int Dtm26 { get { return GetColumnValue<int>(Columns.Dtm26); } set { SetColumnValue(Columns.Dtm26, value); } } [XmlAttribute("Dtm27")] [Bindable(true)] public int Dtm27 { get { return GetColumnValue<int>(Columns.Dtm27); } set { SetColumnValue(Columns.Dtm27, value); } } [XmlAttribute("Ecv8")] [Bindable(true)] public int Ecv8 { get { return GetColumnValue<int>(Columns.Ecv8); } set { SetColumnValue(Columns.Ecv8, value); } } [XmlAttribute("Tabaco9")] [Bindable(true)] public int Tabaco9 { get { return GetColumnValue<int>(Columns.Tabaco9); } set { SetColumnValue(Columns.Tabaco9, value); } } [XmlAttribute("Sumatoria")] [Bindable(true)] public int Sumatoria { get { return GetColumnValue<int>(Columns.Sumatoria); } set { SetColumnValue(Columns.Sumatoria, value); } } [XmlAttribute("PoseeFirma")] [Bindable(true)] public bool PoseeFirma { get { return GetColumnValue<bool>(Columns.PoseeFirma); } set { SetColumnValue(Columns.PoseeFirma, value); } } [XmlAttribute("CreatedBy")] [Bindable(true)] public int CreatedBy { get { return GetColumnValue<int>(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 int ModifiedBy { get { return GetColumnValue<int>(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); } } [XmlAttribute("Centros")] [Bindable(true)] public string Centros { get { return GetColumnValue<string>(Columns.Centros); } set { SetColumnValue(Columns.Centros, value); } } [XmlAttribute("VacunasCompletas")] [Bindable(true)] public int VacunasCompletas { get { return GetColumnValue<int>(Columns.VacunasCompletas); } set { SetColumnValue(Columns.VacunasCompletas, value); } } [XmlAttribute("Pap")] [Bindable(true)] public int Pap { get { return GetColumnValue<int>(Columns.Pap); } set { SetColumnValue(Columns.Pap, value); } } [XmlAttribute("IdProfesional")] [Bindable(true)] public int? IdProfesional { get { return GetColumnValue<int?>(Columns.IdProfesional); } set { SetColumnValue(Columns.IdProfesional, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.SysRelFormularioCoberturaCollection colSysRelFormularioCoberturaRecords; public DalSic.SysRelFormularioCoberturaCollection SysRelFormularioCoberturaRecords { get { if(colSysRelFormularioCoberturaRecords == null) { colSysRelFormularioCoberturaRecords = new DalSic.SysRelFormularioCoberturaCollection().Where(SysRelFormularioCobertura.Columns.IdFormulario, IdFormulario).Load(); colSysRelFormularioCoberturaRecords.ListChanged += new ListChangedEventHandler(colSysRelFormularioCoberturaRecords_ListChanged); } return colSysRelFormularioCoberturaRecords; } set { colSysRelFormularioCoberturaRecords = value; colSysRelFormularioCoberturaRecords.ListChanged += new ListChangedEventHandler(colSysRelFormularioCoberturaRecords_ListChanged); } } void colSysRelFormularioCoberturaRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colSysRelFormularioCoberturaRecords[e.NewIndex].IdFormulario = IdFormulario; } } private DalSic.RemClasificacionCollection colRemClasificacionRecords; public DalSic.RemClasificacionCollection RemClasificacionRecords { get { if(colRemClasificacionRecords == null) { colRemClasificacionRecords = new DalSic.RemClasificacionCollection().Where(RemClasificacion.Columns.IdFormulario, IdFormulario).Load(); colRemClasificacionRecords.ListChanged += new ListChangedEventHandler(colRemClasificacionRecords_ListChanged); } return colRemClasificacionRecords; } set { colRemClasificacionRecords = value; colRemClasificacionRecords.ListChanged += new ListChangedEventHandler(colRemClasificacionRecords_ListChanged); } } void colRemClasificacionRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colRemClasificacionRecords[e.NewIndex].IdFormulario = IdFormulario; } } #endregion #region ForeignKey Properties /// <summary> /// Returns a SysEfector ActiveRecord object related to this RemFormulario /// /// </summary> public DalSic.SysEfector SysEfector { get { return DalSic.SysEfector.FetchByID(this.IdEfector); } set { SetColumnValue("idEfector", value.IdEfector); } } /// <summary> /// Returns a SysMunicipio ActiveRecord object related to this RemFormulario /// /// </summary> public DalSic.SysMunicipio SysMunicipio { get { return DalSic.SysMunicipio.FetchByID(this.IdMunicipio); } set { SetColumnValue("idMunicipio", value.IdMunicipio); } } /// <summary> /// Returns a SysObraSocial ActiveRecord object related to this RemFormulario /// /// </summary> public DalSic.SysObraSocial SysObraSocial { get { return DalSic.SysObraSocial.FetchByID(this.IdObraSocial); } set { SetColumnValue("idObraSocial", value.IdObraSocial); } } /// <summary> /// Returns a SysPaciente ActiveRecord object related to this RemFormulario /// /// </summary> public DalSic.SysPaciente SysPaciente { get { return DalSic.SysPaciente.FetchByID(this.IdPaciente); } set { SetColumnValue("idPaciente", value.IdPaciente); } } /// <summary> /// Returns a SysProfesional ActiveRecord object related to this RemFormulario /// /// </summary> public DalSic.SysProfesional SysProfesional { get { return DalSic.SysProfesional.FetchByID(this.IdProfesional); } set { SetColumnValue("idProfesional", value.IdProfesional); } } /// <summary> /// Returns a SysUsuario ActiveRecord object related to this RemFormulario /// /// </summary> public DalSic.SysUsuario SysUsuario { get { return DalSic.SysUsuario.FetchByID(this.ModifiedBy); } set { SetColumnValue("ModifiedBy", value.IdUsuario); } } /// <summary> /// Returns a SysUsuario ActiveRecord object related to this RemFormulario /// /// </summary> public DalSic.SysUsuario SysUsuarioToCreatedBy { get { return DalSic.SysUsuario.FetchByID(this.CreatedBy); } set { SetColumnValue("CreatedBy", value.IdUsuario); } } /// <summary> /// Returns a RemAgente ActiveRecord object related to this RemFormulario /// /// </summary> public DalSic.RemAgente RemAgente { get { return DalSic.RemAgente.FetchByID(this.IdAgente); } set { SetColumnValue("idAgente", value.IdAgente); } } #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 varIdEfector,int varIdPaciente,int varIdObraSocial,int varNumeroFormulario,DateTime varFechaEmpadronamiento,int? varIdAgente,int varIdMunicipio,int varSexo,int varEdad,int varHta2,int varHta3,int varColesterol4,int varColesterol5,int varDtm26,int varDtm27,int varEcv8,int varTabaco9,int varSumatoria,bool varPoseeFirma,int varCreatedBy,DateTime varCreatedOn,int varModifiedBy,DateTime varModifiedOn,string varCentros,int varVacunasCompletas,int varPap,int? varIdProfesional) { RemFormulario item = new RemFormulario(); item.IdEfector = varIdEfector; item.IdPaciente = varIdPaciente; item.IdObraSocial = varIdObraSocial; item.NumeroFormulario = varNumeroFormulario; item.FechaEmpadronamiento = varFechaEmpadronamiento; item.IdAgente = varIdAgente; item.IdMunicipio = varIdMunicipio; item.Sexo = varSexo; item.Edad = varEdad; item.Hta2 = varHta2; item.Hta3 = varHta3; item.Colesterol4 = varColesterol4; item.Colesterol5 = varColesterol5; item.Dtm26 = varDtm26; item.Dtm27 = varDtm27; item.Ecv8 = varEcv8; item.Tabaco9 = varTabaco9; item.Sumatoria = varSumatoria; item.PoseeFirma = varPoseeFirma; item.CreatedBy = varCreatedBy; item.CreatedOn = varCreatedOn; item.ModifiedBy = varModifiedBy; item.ModifiedOn = varModifiedOn; item.Centros = varCentros; item.VacunasCompletas = varVacunasCompletas; item.Pap = varPap; item.IdProfesional = varIdProfesional; 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 varIdFormulario,int varIdEfector,int varIdPaciente,int varIdObraSocial,int varNumeroFormulario,DateTime varFechaEmpadronamiento,int? varIdAgente,int varIdMunicipio,int varSexo,int varEdad,int varHta2,int varHta3,int varColesterol4,int varColesterol5,int varDtm26,int varDtm27,int varEcv8,int varTabaco9,int varSumatoria,bool varPoseeFirma,int varCreatedBy,DateTime varCreatedOn,int varModifiedBy,DateTime varModifiedOn,string varCentros,int varVacunasCompletas,int varPap,int? varIdProfesional) { RemFormulario item = new RemFormulario(); item.IdFormulario = varIdFormulario; item.IdEfector = varIdEfector; item.IdPaciente = varIdPaciente; item.IdObraSocial = varIdObraSocial; item.NumeroFormulario = varNumeroFormulario; item.FechaEmpadronamiento = varFechaEmpadronamiento; item.IdAgente = varIdAgente; item.IdMunicipio = varIdMunicipio; item.Sexo = varSexo; item.Edad = varEdad; item.Hta2 = varHta2; item.Hta3 = varHta3; item.Colesterol4 = varColesterol4; item.Colesterol5 = varColesterol5; item.Dtm26 = varDtm26; item.Dtm27 = varDtm27; item.Ecv8 = varEcv8; item.Tabaco9 = varTabaco9; item.Sumatoria = varSumatoria; item.PoseeFirma = varPoseeFirma; item.CreatedBy = varCreatedBy; item.CreatedOn = varCreatedOn; item.ModifiedBy = varModifiedBy; item.ModifiedOn = varModifiedOn; item.Centros = varCentros; item.VacunasCompletas = varVacunasCompletas; item.Pap = varPap; item.IdProfesional = varIdProfesional; 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 IdFormularioColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdEfectorColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdPacienteColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn IdObraSocialColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn NumeroFormularioColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn FechaEmpadronamientoColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn IdAgenteColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn IdMunicipioColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn SexoColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn EdadColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn Hta2Column { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn Hta3Column { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn Colesterol4Column { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn Colesterol5Column { get { return Schema.Columns[13]; } } public static TableSchema.TableColumn Dtm26Column { get { return Schema.Columns[14]; } } public static TableSchema.TableColumn Dtm27Column { get { return Schema.Columns[15]; } } public static TableSchema.TableColumn Ecv8Column { get { return Schema.Columns[16]; } } public static TableSchema.TableColumn Tabaco9Column { get { return Schema.Columns[17]; } } public static TableSchema.TableColumn SumatoriaColumn { get { return Schema.Columns[18]; } } public static TableSchema.TableColumn PoseeFirmaColumn { get { return Schema.Columns[19]; } } public static TableSchema.TableColumn CreatedByColumn { get { return Schema.Columns[20]; } } public static TableSchema.TableColumn CreatedOnColumn { get { return Schema.Columns[21]; } } public static TableSchema.TableColumn ModifiedByColumn { get { return Schema.Columns[22]; } } public static TableSchema.TableColumn ModifiedOnColumn { get { return Schema.Columns[23]; } } public static TableSchema.TableColumn CentrosColumn { get { return Schema.Columns[24]; } } public static TableSchema.TableColumn VacunasCompletasColumn { get { return Schema.Columns[25]; } } public static TableSchema.TableColumn PapColumn { get { return Schema.Columns[26]; } } public static TableSchema.TableColumn IdProfesionalColumn { get { return Schema.Columns[27]; } } #endregion #region Columns Struct public struct Columns { public static string IdFormulario = @"idFormulario"; public static string IdEfector = @"idEfector"; public static string IdPaciente = @"idPaciente"; public static string IdObraSocial = @"idObraSocial"; public static string NumeroFormulario = @"numeroFormulario"; public static string FechaEmpadronamiento = @"fechaEmpadronamiento"; public static string IdAgente = @"idAgente"; public static string IdMunicipio = @"idMunicipio"; public static string Sexo = @"sexo"; public static string Edad = @"edad"; public static string Hta2 = @"hta2"; public static string Hta3 = @"hta3"; public static string Colesterol4 = @"colesterol4"; public static string Colesterol5 = @"colesterol5"; public static string Dtm26 = @"dtm26"; public static string Dtm27 = @"dtm27"; public static string Ecv8 = @"ecv8"; public static string Tabaco9 = @"tabaco9"; public static string Sumatoria = @"sumatoria"; public static string PoseeFirma = @"poseeFirma"; public static string CreatedBy = @"CreatedBy"; public static string CreatedOn = @"CreatedOn"; public static string ModifiedBy = @"ModifiedBy"; public static string ModifiedOn = @"ModifiedOn"; public static string Centros = @"centros"; public static string VacunasCompletas = @"vacunasCompletas"; public static string Pap = @"pap"; public static string IdProfesional = @"idProfesional"; } #endregion #region Update PK Collections public void SetPKValues() { if (colSysRelFormularioCoberturaRecords != null) { foreach (DalSic.SysRelFormularioCobertura item in colSysRelFormularioCoberturaRecords) { if (item.IdFormulario != IdFormulario) { item.IdFormulario = IdFormulario; } } } if (colRemClasificacionRecords != null) { foreach (DalSic.RemClasificacion item in colRemClasificacionRecords) { if (item.IdFormulario != IdFormulario) { item.IdFormulario = IdFormulario; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colSysRelFormularioCoberturaRecords != null) { colSysRelFormularioCoberturaRecords.SaveAll(); } if (colRemClasificacionRecords != null) { colRemClasificacionRecords.SaveAll(); } } #endregion } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Message { #region usings using System; #endregion /// <summary> /// Implements SIP "name-addr" value. Defined in RFC 3261. /// </summary> /// <remarks> /// <code> /// RFC 3261 Syntax: /// name-addr = [ display-name ] LAQUOT addr-spec RAQUOT /// addr-spec = SIP-URI / SIPS-URI / absoluteURI /// </code> /// </remarks> public class SIP_t_NameAddress { #region Members private string m_DisplayName = ""; private AbsoluteUri m_pUri; #endregion #region Properties /// <summary> /// Gets or sets display name. /// </summary> public string DisplayName { get { return m_DisplayName; } set { if (value == null) { value = ""; } m_DisplayName = value; } } /// <summary> /// Gets or sets URI. This can be SIP-URI / SIPS-URI / absoluteURI. /// Examples: sip:ivar@lumisoft.ee,sips:ivar@lumisoft.ee,mailto:ivar@lumisoft.ee, .... . /// </summary> /// <exception cref="ArgumentNullException">Is raised when null reference passed.</exception> public AbsoluteUri Uri { get { return m_pUri; } set { if (value == null) { throw new ArgumentNullException("value"); } m_pUri = value; } } /// <summary> /// Gets if current URI is sip or sips URI. /// </summary> public bool IsSipOrSipsUri { get { return IsSipUri || IsSecureSipUri; } } /// <summary> /// Gets if current URI is SIP uri. /// </summary> public bool IsSipUri { get { if (m_pUri.Scheme == UriSchemes.sip) { return true; } return false; } } /// <summary> /// Gets if current URI is SIPS uri. /// </summary> public bool IsSecureSipUri { get { if (m_pUri.Scheme == UriSchemes.sips) { return true; } return false; } } /// <summary> /// Gets if current URI is MAILTO uri. /// </summary> public bool IsMailToUri { get { if (m_pUri.Scheme == UriSchemes.mailto) { return true; } return false; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SIP_t_NameAddress() {} /// <summary> /// Default constructor. /// </summary> /// <param name="value">SIP <b>name-addr</b> value.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public SIP_t_NameAddress(string value) { Parse(value); } /// <summary> /// Default constructor. /// </summary> /// <param name="displayName">Display name.</param> /// <param name="uri">Uri.</param> /// <exception cref="ArgumentNullException">Is raised when <b>uri</b> is null reference.</exception> public SIP_t_NameAddress(string displayName, AbsoluteUri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } DisplayName = displayName; Uri = uri; } #endregion #region Methods /// <summary> /// Parses "name-addr" or "addr-spec" from specified value. /// </summary> /// <param name="value">SIP "name-addr" or "addr-spec" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("reader"); } Parse(new StringReader(value)); } /// <summary> /// Parses "name-addr" or "addr-spec" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(StringReader reader) { /* RFC 3261. name-addr = [ display-name ] LAQUOT addr-spec RAQUOT addr-spec = SIP-URI / SIPS-URI / absoluteURI */ if (reader == null) { throw new ArgumentNullException("reader"); } reader.ReadToFirstChar(); // LAQUOT addr-spec RAQUOT if (reader.StartsWith("<")) { m_pUri = AbsoluteUri.Parse(reader.ReadParenthesized()); } else { string word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("Invalid 'name-addr' or 'addr-spec' value !"); } reader.ReadToFirstChar(); // name-addr if (reader.StartsWith("<")) { m_DisplayName = word; m_pUri = AbsoluteUri.Parse(reader.ReadParenthesized()); } // addr-spec else { m_pUri = AbsoluteUri.Parse(word); } } } /// <summary> /// Converts this to valid name-addr or addr-spec string as needed. /// </summary> /// <returns>Returns name-addr or addr-spec string.</returns> public string ToStringValue() { /* RFC 3261. name-addr = [ display-name ] LAQUOT addr-spec RAQUOT addr-spec = SIP-URI / SIPS-URI / absoluteURI */ // addr-spec if (string.IsNullOrEmpty(m_DisplayName)) { return "<" + m_pUri + ">"; } // name-addr else { return TextUtils.QuoteString(m_DisplayName) + " <" + m_pUri + ">"; } } #endregion } }
// Created by John Mandia (john.mandia@whitelightsolutions.com) using System; using System.Collections.Specialized; using System.Configuration; using System.Globalization; using System.Linq; using System.Text; using System.Web; using Appleseed.Framework.Site.Configuration; using Appleseed.Framework.Settings; using Appleseed.Framework.Exceptions; using Appleseed.Framework.Site.Data; using System.Data.SqlClient; using System.Collections.Generic; namespace Appleseed.Framework.Web { /// <summary> /// Appleseed standard implementation. /// This code has been developed and extended by John Mandia (www.whitelightsolutions.com), /// Manu (www.duemetri.com), Jes (www.marinateq.com) and Cory. /// </summary> [History("Ashish.patel@haptix.biz", "2014/12/24", "Changes into build url for friendly url")] public class SqlUrlBuilderProvider : UrlBuilderProvider { private string _defaultSplitter = "__"; private string _handlerFlag = string.Empty; private bool _aliasInUrl = false; private bool _langInUrl = false; private string _ignoreTargetPage = "tablayout.aspx"; private double _cacheMinutes = 5; private bool _pageidNoSplitter = false; private string _friendlyPageName = "default.aspx"; private StringDictionary queryList = new StringDictionary(); private bool Hieranchy = false; //Ashish.patel@haptix.biz - 2014/12/16 - Set default extension private string _friendlyUrlExtension = ".aspx"; //Ashish.patel@haptix.biz - 2017/07/20 - Set default NO Extension private bool _friendlyUrlNoExtension = false; /// <summary> /// Takes a Tab ID and builds the url for get the desidered page (non default) /// containing the application path, portal alias, tab ID, and language. /// </summary> /// <param name="targetPage">Linked page</param> /// <param name="pageID">ID of the page</param> /// <param name="modID">ID of the module</param> /// <param name="culture">Client culture</param> /// <param name="customAttributes">Any custom attribute that can be needed. Use the following format...single attribute: paramname--paramvalue . Multiple attributes: paramname--paramvalue/paramname2--paramvalue2/paramname3--paramvalue3 </param> /// <param name="currentAlias">Current Alias</param> /// <param name="urlKeywords">Add some keywords to uniquely identify this tab. Usual source is UrlKeyword from TabSettings.</param> public override string BuildUrl(string targetPage, int pageID, int modID, CultureInfo culture, string customAttributes, string currentAlias, string urlKeywords) { // Get Url Elements this helper method (Will either retrieve from cache or database) UrlElements urlElements = UrlBuilderHelper.GetUrlElements(pageID, _cacheMinutes); //2_aug_2004 Cory Isakson //Begin Navigation Enhancements if (!(targetPage.ToLower().EndsWith(_ignoreTargetPage.ToLower()))) // Do not modify URLs when working with TabLayout Administration Page { // if it is a placeholder it is not supposed to have any url if (urlElements.IsPlaceHolder) return string.Empty; // if it is a tab link it means it is a link to an external resource //if (urlElements.TabLink.Length != 0) return urlElements.TabLink; if (urlElements.TabLink.Length != 0) { if (urlElements.TabLink.ToLower().Contains("http://") || urlElements.TabLink.ToLower().Contains("https://")) return urlElements.TabLink; else return "http://" + urlElements.TabLink; } } //End Navigation Enhancements if (targetPage.StartsWith("~/")) { targetPage = targetPage.Substring(2); } //Ashish.patel@haptix.biz - 2014/12/24 - Added for getting friendly url from cache PageUrl pageurl = GetCachePageUrl(pageID); string cacheUrl = string.Empty; if (pageurl != null && (targetPage.Equals(HttpUrlBuilder.DefaultPage) || targetPage.Equals("DesktopDefault.aspx"))) { if (PortalSettings.HasEnablePageFriendlyUrl(pageID, currentAlias)) { if (!string.IsNullOrEmpty(pageurl.PageFriendlyUrl)) return pageurl.PageFriendlyUrl; } else { if (!string.IsNullOrEmpty(pageurl.PageNormalUrl)) return pageurl.PageNormalUrl; } } StringBuilder sb = new StringBuilder(); // Obtain ApplicationPath if (targetPage.StartsWith("~/")) { sb.Append(UrlBuilderHelper.ApplicationPath); targetPage = targetPage.Substring(2); } sb.Append("/"); //if (!targetPage.EndsWith(".aspx")) //Images //{ // sb.Append(targetPage); // return sb.ToString(); //} HttpContext.Current.Trace.Warn("Target Page = " + targetPage); // Separate path // If page contains path, or it is not an aspx // or handlerFlag is not set: do not use handler if (!targetPage.Equals(HttpUrlBuilder.DefaultPage) && !targetPage.Equals("DesktopDefault.aspx")) { sb.Append(targetPage); // if !!targetPage.EndsWith(".aspx") it's an image. Return if (!targetPage.EndsWith(".aspx")) { return sb.ToString(); } else { sb.Append("?"); // Add pageID to URL sb.Append("pageId="); sb.Append(pageID.ToString()); // Add Alias to URL if (_aliasInUrl) { sb.Append("&alias="); // changed for compatibility with handler sb.Append(currentAlias); } // Add ModID to URL if (modID > 0) { sb.Append("&mid="); sb.Append(modID.ToString()); } // Add Language to URL if (_langInUrl && culture != null) { sb.Append("&lang="); // changed for compatibility with handler sb.Append(culture.Name); // manu fix: culture.Name } // Add custom attributes if (customAttributes != null && customAttributes != string.Empty) { sb.Append("&"); customAttributes = customAttributes.ToString().Replace("/", "&"); customAttributes = customAttributes.ToString().Replace(_defaultSplitter, "="); sb.Append(customAttributes); } return sb.ToString().Replace("&&", "&"); } } else // use handler { PortalSettings settings = PortalSettings.GetPortalSettingsbyPageID(pageID, currentAlias); var hasFriendUrl = false; if (settings.EnablePageFriendlyUrl) { PagesDB pages = new PagesDB(); //Ashish.patel@haptix.biz - 2014/12/16 - Get friendlyUrl from database var friendlyURL = pages.GetFriendlyURl(pageID); //Ashish.patel@haptix.biz - 2014/12/16 - Check friendlyUrl not null if (friendlyURL != "") { hasFriendUrl = true; sb.Append(friendlyURL).ToString(); } } string queryLeft = ""; string queryRigth = ""; // Add custom attributes #region custom attributes if (customAttributes != null && customAttributes != string.Empty) { var parts = customAttributes.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < parts.Length; i++) { try { var key = parts[i].Split('=')[0]; if (!(key.Equals("pageId") || key.Equals("pageID"))) { if (queryList.ContainsKey(key)) { var q = parts[i].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries); queryRigth += HttpUtility.UrlEncode(q[0], System.Text.Encoding.GetEncoding(28591)) + "=" + HttpUtility.UrlEncode(q[1], System.Text.Encoding.GetEncoding(28591)) + "&"; } else { var q = parts[i].Split('='); queryLeft += HttpUtility.UrlEncode(q[0], System.Text.Encoding.GetEncoding(28591)) + "=" + HttpUtility.UrlEncode(q[1], System.Text.Encoding.GetEncoding(28591)) + "&"; } } } catch (Exception) { } } if (!string.IsNullOrEmpty(queryLeft)) { // If its null, all the attributes are at the end, else, should add the ones from the queryLeft queryLeft = queryLeft.Remove(queryLeft.Length - 1); queryLeft = queryLeft.Replace("+", "%20"); queryLeft = queryLeft.ToString().Replace("&", "/"); queryLeft = queryLeft.ToString().Replace("=", _defaultSplitter); } } #endregion if (!hasFriendUrl) { #region Existing Url Builing code // Add smarturl tag and if friendlyURL false if (!string.IsNullOrEmpty(_handlerFlag) && !settings.EnablePageFriendlyUrl) { sb.Append(_handlerFlag); sb.Append("/"); } // Add custom Keywords to the Url if (urlKeywords != null && urlKeywords != string.Empty) { sb.Append(urlKeywords); sb.Append("/"); } else { urlKeywords = urlElements.UrlKeywords; // Add custom Keywords to the Url if (urlKeywords != null && urlKeywords.Length != 0) { sb.Append(urlKeywords); sb.Append("/"); } } // Add Alias to URL if (_aliasInUrl) { sb.Append("alias"); sb.Append(_defaultSplitter + currentAlias); sb.Append("/"); } // Add Language to URL if (_langInUrl && culture != null) { sb.Append("lang"); sb.Append(_defaultSplitter + culture.Name); sb.Append("/"); } // Add ModID to URL if (modID > 0) { sb.Append("mid"); sb.Append(_defaultSplitter + modID.ToString()); sb.Append("/"); } if (!string.IsNullOrEmpty(queryLeft)) { sb.Append(queryLeft); sb.Append("/"); } //get setting from portalsettings //HttpContext.Item - add/update key all the codes are managed by this method //PortalSettings settings = PortalSettings.GetPortalSettingsbyPageID(Portal.PageID, Portal.UniqueID); //Ashish.patel@haptix.biz - 2014/12/16 - Appends if EnableFrindlyURl is false if (!settings.EnablePageFriendlyUrl) { sb.Append(pageID); sb.Append("/"); } if (!string.IsNullOrEmpty(urlElements.PageName))// TODO : Need to fix page names rewrites sb.Append(urlElements.PageName); else if (!string.IsNullOrEmpty(urlElements.PageTitle)) { string PageName = urlElements.PageTitle; // Write page Hieranchy if (Hieranchy) { int parentId = 0; bool found = false; //Get the parent pageId of the actual pageId for (int i = 0; i < settings.DesktopPages.Count && !found; i++) { if (settings.DesktopPages[i].PageID == pageID) { parentId = settings.DesktopPages[i].ParentPageID; found = true; } } if (found) { bool exit = false; // while the parentId it's diferent of 0 or the parentId isn't in settings while (parentId != 0 && !exit) { found = false; // find the parent in the setting for (int i = 0; i < settings.DesktopPages.Count && !found; i++) { if (settings.DesktopPages[i].PageID == parentId) { PageName = UrlBuilderHelper.CleanNoAlphanumerics(settings.DesktopPages[i].PageName) + "/" + PageName; parentId = settings.DesktopPages[i].ParentPageID; found = true; } } // If the parent isn't in settings the loop should stop if (!found) exit = true; } } } sb.Append(PageName); } else sb.Append(_friendlyPageName); #endregion } // Ashish.patel@haptix.biz - 2014/12/16 - // check friendly URL is enabled and requested file is exist physically or not. // If not exists and friendly url is enabled, the extension will be appended. if (settings.EnablePageFriendlyUrl && !System.IO.File.Exists(HttpContext.Current.Server.MapPath(sb.ToString())) && !_friendlyUrlNoExtension) { sb.Append(this._friendlyUrlExtension); } // Add the query at the end if (!string.IsNullOrEmpty(queryRigth)) { queryRigth = queryRigth.Remove(queryRigth.Length - 1); sb.Append("?" + queryRigth); } //Ashish.patel@haptix.biz - 2014/12/24 - Modified for setting friendly url into cache var url = sb.ToString().Replace("//", "/"); if (settings.EnablePageFriendlyUrl) SetCachePageUrl(pageID, string.Empty, url); else SetCachePageUrl(pageID, url, string.Empty); return url; } } /// <summary> /// The initialize method lets you retrieve provider specific settings from web.config /// </summary> /// <param name="name"></param> /// <param name="configValue"></param> public override void Initialize(string name, NameValueCollection configValue) { base.Initialize(name, configValue); // For legacy support first check provider settings then web.config/Appleseed.config legacy settings if (configValue["handlersplitter"] != null) { _defaultSplitter = configValue["handlersplitter"].ToString(); } else { if (ConfigurationManager.AppSettings["HandlerDefaultSplitter"] != null) _defaultSplitter = ConfigurationManager.AppSettings["HandlerDefaultSplitter"]; } // For legacy support first check provider settings then web.config/Appleseed.config legacy settings if (configValue["handlerflag"] != null) { _handlerFlag = configValue["handlerflag"].ToString(); } else { _handlerFlag = string.Empty; } //if (configValue["FriendlyUrlExtension"] != null) if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["FriendlyUrlExtension"])) { _friendlyUrlExtension = System.Configuration.ConfigurationManager.AppSettings["FriendlyUrlExtension"]; } else { _friendlyUrlExtension = ".aspx"; } //if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["friendlyUrlNoExtension"]) && System.Configuration.ConfigurationManager.AppSettings["friendlyUrlNoExtension"] == "1") if (PortalSettings.FriendlyUrlNoExtensionEnabled()) { _friendlyUrlNoExtension = true; } // For legacy support first check provider settings then web.config/Appleseed.config legacy settings if (configValue["aliasinurl"] != null) { _aliasInUrl = bool.Parse(configValue["aliasinurl"].ToString()); } else { if (ConfigurationManager.AppSettings["UseAlias"] != null) _aliasInUrl = bool.Parse(ConfigurationManager.AppSettings["UseAlias"]); } // For legacy support first check provider settings then web.config/Appleseed.config legacy settings if (configValue["langinurl"] != null) { _langInUrl = bool.Parse(configValue["langinurl"].ToString()); } else { if (ConfigurationManager.AppSettings["LangInURL"] != null) _langInUrl = bool.Parse(ConfigurationManager.AppSettings["LangInURL"]); } if (configValue["ignoretargetpage"] != null) { _ignoreTargetPage = configValue["ignoretargetpage"].ToString(); } if (configValue["cacheminutes"] != null) { _cacheMinutes = Convert.ToDouble(configValue["cacheminutes"].ToString()); } if (configValue["pageidnosplitter"] != null) { _pageidNoSplitter = bool.Parse(configValue["pageidnosplitter"].ToString()); } else { if (ConfigurationManager.AppSettings["PageIdNoSplitter"] != null) _pageidNoSplitter = bool.Parse(ConfigurationManager.AppSettings["PageIdNoSplitter"]); } // For legacy support first check provider settings then web.config/Appleseed.config legacy settings if (configValue["friendlypagename"] != null) { // TODO: Friendly url's need to be fixed _friendlyPageName = configValue["friendlypagename"].ToString(); } else { if (ConfigurationManager.AppSettings["FriendlyPageName"] != null) _friendlyPageName = ConfigurationManager.AppSettings["FriendlyPageName"]; } if (configValue["Querylist"] != null) { queryList = new StringDictionary(); string list = configValue["Querylist"].ToString(); var parts = list.Split(';'); for (int i = 0; i < parts.Length; i++) { queryList.Add(parts[i], parts[i]); } } if (configValue["ShowHieranchy"] != null) { string ShowHieranchy = configValue["ShowHieranchy"].ToString(); try { Hieranchy = bool.Parse(ShowHieranchy); } catch (Exception) { Hieranchy = false; } } } /// <summary> /// Determines if a tab is simply a placeholder in the navigation /// </summary> public override bool IsPlaceholder(int pageID) { return bool.Parse( UrlBuilderHelper.PageSpecificProperty(pageID, UrlBuilderHelper.IsPlaceHolderID, _cacheMinutes). ToString()); } /// <summary> /// Returns the URL for a tab that is a link only. /// </summary> public override string TabLink(int pageID) { return UrlBuilderHelper.PageSpecificProperty(pageID, UrlBuilderHelper.TabLinkID, _cacheMinutes); } /// <summary> /// Returns any keywords which are meant to be placed in the url /// </summary> public override string UrlKeyword(int pageID) { return UrlBuilderHelper.PageSpecificProperty(pageID, UrlBuilderHelper.UrlKeywordsID, _cacheMinutes).ToString(); } /// <summary> /// Returns the page name that has been specified. /// </summary> public override string UrlPageName(int pageID) { string _urlPageName = UrlBuilderHelper.PageSpecificProperty(pageID, UrlBuilderHelper.PageNameID, _cacheMinutes).ToString(); // TODO: URL Firendly names need to be fixed if (_urlPageName.Length == 0) _urlPageName = _friendlyPageName; return _urlPageName; } /// <summary> /// Gets the default page from web.config/Appleseed.config /// </summary> public override string DefaultPage { get { // TODO: Jes1111 - check this with John //string strTemp = ConfigurationSettings.AppSettings["HandlerTargetUrl"]; // TODO : JONATHAN - PROBLEM WITH DEFAULT PAGE LIKE THIS string strTemp = _friendlyPageName; // TODO : JONATHAN - PROBLEM WITH DEFAULT PAGE LIKE THIS if (strTemp.Length == 0 || strTemp == null) strTemp = "Default.aspx"; return strTemp; } } /// <summary> /// Returns the default paramater splitter from provider settings (or web.config/Appleseed.config if not specified in provider) /// </summary> public override string DefaultSplitter { get { return _defaultSplitter; } } /// <summary> /// Clears the cached url element settings /// </summary> public override void Clear(int pageID) { UrlBuilderHelper.ClearUrlElements(pageID); } /// <summary> /// Get the page url object from cache /// </summary> /// <param name="pageID"> page id</param> /// <returns> returns object of pageurl</returns> /// Ashish.patel@haptix.biz - 2014/12/24 - Added for getting page url from cache public PageUrl GetCachePageUrl(int pageID) { List<PageUrl> lstUrls = new List<PageUrl>(); if (HttpContext.Current.Cache["PageUrlList"] != null) { lstUrls = (List<PageUrl>)HttpContext.Current.Cache["PageUrlList"]; } return lstUrls.FirstOrDefault(url => url.PageID == pageID); } /// <summary> /// Set the url into cache /// </summary> /// <param name="pageID"> page id</param> /// <param name="pageUrl"> page url</param> /// <param name="pageFriendlyUrl"> page friendly url</param> /// Ashish.patel@haptix.biz - 2014/12/24 - Added for setting list of page url into cache public void SetCachePageUrl(int pageID, string pageUrl, string pageFriendlyUrl) { List<PageUrl> lstUrls = new List<PageUrl>(); if (HttpContext.Current.Cache["PageUrlList"] != null) lstUrls = (List<PageUrl>)HttpContext.Current.Cache["PageUrlList"]; else HttpContext.Current.Cache.Insert("PageUrlList", lstUrls); PageUrl pgurl = lstUrls.FirstOrDefault(url => url.PageID == pageID); if (pgurl == null) { pgurl = new PageUrl(); pgurl.PageID = pageID; lstUrls.Add(pgurl); } if (!string.IsNullOrEmpty(pageUrl) && !System.IO.File.Exists(HttpContext.Current.Server.MapPath(pageUrl.Split('?').GetValue(0).ToString()))) { pgurl.PageNormalUrl = pageUrl; } if (!string.IsNullOrEmpty(pageFriendlyUrl) && !System.IO.File.Exists(HttpContext.Current.Server.MapPath(pageUrl.Split('?').GetValue(0).ToString()))) { pgurl.PageFriendlyUrl = pageFriendlyUrl; } HttpContext.Current.Cache["PageUrlList"] = lstUrls; } /// <summary> /// It will clear page url from cache /// </summary> /// <param name="pageID">page id</param> /// Ashish.patel@haptix.biz - 2014/12/24 - Added for clearing list of page url from cache public static void ClearCachePageUrl(int pageID) { List<PageUrl> lstUrls = new List<PageUrl>(); if (HttpContext.Current.Cache["PageUrlList"] != null) lstUrls = (List<PageUrl>)HttpContext.Current.Cache["PageUrlList"]; else HttpContext.Current.Cache.Insert("PageUrlList", lstUrls); HttpContext.Current.Cache["PageUrlList"] = lstUrls.Where(url => url.PageID != pageID).ToList(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Reflection.Emit; namespace System.Linq.Expressions.Compiler { internal static class ILGen { internal static void Emit(this ILGenerator il, OpCode opcode, MethodBase methodBase) { Debug.Assert(methodBase is MethodInfo || methodBase is ConstructorInfo); var ctor = methodBase as ConstructorInfo; if ((object)ctor != null) { il.Emit(opcode, ctor); } else { il.Emit(opcode, (MethodInfo)methodBase); } } #region Instruction helpers internal static void EmitLoadArg(this ILGenerator il, int index) { Debug.Assert(index >= 0); switch (index) { case 0: il.Emit(OpCodes.Ldarg_0); break; case 1: il.Emit(OpCodes.Ldarg_1); break; case 2: il.Emit(OpCodes.Ldarg_2); break; case 3: il.Emit(OpCodes.Ldarg_3); break; default: if (index <= Byte.MaxValue) { il.Emit(OpCodes.Ldarg_S, (byte)index); } else { il.Emit(OpCodes.Ldarg, index); } break; } } internal static void EmitLoadArgAddress(this ILGenerator il, int index) { Debug.Assert(index >= 0); if (index <= Byte.MaxValue) { il.Emit(OpCodes.Ldarga_S, (byte)index); } else { il.Emit(OpCodes.Ldarga, index); } } internal static void EmitStoreArg(this ILGenerator il, int index) { Debug.Assert(index >= 0); if (index <= Byte.MaxValue) { il.Emit(OpCodes.Starg_S, (byte)index); } else { il.Emit(OpCodes.Starg, index); } } /// <summary> /// Emits a Ldind* instruction for the appropriate type /// </summary> internal static void EmitLoadValueIndirect(this ILGenerator il, Type type) { ContractUtils.RequiresNotNull(type, "type"); if (type.GetTypeInfo().IsValueType) { if (type == typeof(int)) { il.Emit(OpCodes.Ldind_I4); } else if (type == typeof(uint)) { il.Emit(OpCodes.Ldind_U4); } else if (type == typeof(short)) { il.Emit(OpCodes.Ldind_I2); } else if (type == typeof(ushort)) { il.Emit(OpCodes.Ldind_U2); } else if (type == typeof(long) || type == typeof(ulong)) { il.Emit(OpCodes.Ldind_I8); } else if (type == typeof(char)) { il.Emit(OpCodes.Ldind_I2); } else if (type == typeof(bool)) { il.Emit(OpCodes.Ldind_I1); } else if (type == typeof(float)) { il.Emit(OpCodes.Ldind_R4); } else if (type == typeof(double)) { il.Emit(OpCodes.Ldind_R8); } else { il.Emit(OpCodes.Ldobj, type); } } else { il.Emit(OpCodes.Ldind_Ref); } } /// <summary> /// Emits a Stind* instruction for the appropriate type. /// </summary> internal static void EmitStoreValueIndirect(this ILGenerator il, Type type) { ContractUtils.RequiresNotNull(type, "type"); if (type.GetTypeInfo().IsValueType) { if (type == typeof(int)) { il.Emit(OpCodes.Stind_I4); } else if (type == typeof(short)) { il.Emit(OpCodes.Stind_I2); } else if (type == typeof(long) || type == typeof(ulong)) { il.Emit(OpCodes.Stind_I8); } else if (type == typeof(char)) { il.Emit(OpCodes.Stind_I2); } else if (type == typeof(bool)) { il.Emit(OpCodes.Stind_I1); } else if (type == typeof(float)) { il.Emit(OpCodes.Stind_R4); } else if (type == typeof(double)) { il.Emit(OpCodes.Stind_R8); } else { il.Emit(OpCodes.Stobj, type); } } else { il.Emit(OpCodes.Stind_Ref); } } // Emits the Ldelem* instruction for the appropriate type internal static void EmitLoadElement(this ILGenerator il, Type type) { ContractUtils.RequiresNotNull(type, "type"); if (!type.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Ldelem_Ref); } else if (type.GetTypeInfo().IsEnum) { il.Emit(OpCodes.Ldelem, type); } else { switch (type.GetTypeCode()) { case TypeCode.Boolean: case TypeCode.SByte: il.Emit(OpCodes.Ldelem_I1); break; case TypeCode.Byte: il.Emit(OpCodes.Ldelem_U1); break; case TypeCode.Int16: il.Emit(OpCodes.Ldelem_I2); break; case TypeCode.Char: case TypeCode.UInt16: il.Emit(OpCodes.Ldelem_U2); break; case TypeCode.Int32: il.Emit(OpCodes.Ldelem_I4); break; case TypeCode.UInt32: il.Emit(OpCodes.Ldelem_U4); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Ldelem_I8); break; case TypeCode.Single: il.Emit(OpCodes.Ldelem_R4); break; case TypeCode.Double: il.Emit(OpCodes.Ldelem_R8); break; default: il.Emit(OpCodes.Ldelem, type); break; } } } /// <summary> /// Emits a Stelem* instruction for the appropriate type. /// </summary> internal static void EmitStoreElement(this ILGenerator il, Type type) { ContractUtils.RequiresNotNull(type, "type"); if (type.GetTypeInfo().IsEnum) { il.Emit(OpCodes.Stelem, type); return; } switch (type.GetTypeCode()) { case TypeCode.Boolean: case TypeCode.SByte: case TypeCode.Byte: il.Emit(OpCodes.Stelem_I1); break; case TypeCode.Char: case TypeCode.Int16: case TypeCode.UInt16: il.Emit(OpCodes.Stelem_I2); break; case TypeCode.Int32: case TypeCode.UInt32: il.Emit(OpCodes.Stelem_I4); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Stelem_I8); break; case TypeCode.Single: il.Emit(OpCodes.Stelem_R4); break; case TypeCode.Double: il.Emit(OpCodes.Stelem_R8); break; default: if (type.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Stelem, type); } else { il.Emit(OpCodes.Stelem_Ref); } break; } } internal static void EmitType(this ILGenerator il, Type type) { ContractUtils.RequiresNotNull(type, "type"); il.Emit(OpCodes.Ldtoken, type); il.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle")); } #endregion #region Fields, properties and methods internal static void EmitFieldAddress(this ILGenerator il, FieldInfo fi) { ContractUtils.RequiresNotNull(fi, "fi"); if (fi.IsStatic) { il.Emit(OpCodes.Ldsflda, fi); } else { il.Emit(OpCodes.Ldflda, fi); } } internal static void EmitFieldGet(this ILGenerator il, FieldInfo fi) { ContractUtils.RequiresNotNull(fi, "fi"); if (fi.IsStatic) { il.Emit(OpCodes.Ldsfld, fi); } else { il.Emit(OpCodes.Ldfld, fi); } } internal static void EmitFieldSet(this ILGenerator il, FieldInfo fi) { ContractUtils.RequiresNotNull(fi, "fi"); if (fi.IsStatic) { il.Emit(OpCodes.Stsfld, fi); } else { il.Emit(OpCodes.Stfld, fi); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] internal static void EmitNew(this ILGenerator il, ConstructorInfo ci) { ContractUtils.RequiresNotNull(ci, "ci"); if (ci.DeclaringType.GetTypeInfo().ContainsGenericParameters) { throw Error.IllegalNewGenericParams(ci.DeclaringType); } il.Emit(OpCodes.Newobj, ci); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] internal static void EmitNew(this ILGenerator il, Type type, Type[] paramTypes) { ContractUtils.RequiresNotNull(type, "type"); ContractUtils.RequiresNotNull(paramTypes, "paramTypes"); ConstructorInfo ci = type.GetConstructor(paramTypes); if (ci == null) throw Error.TypeDoesNotHaveConstructorForTheSignature(); il.EmitNew(ci); } #endregion #region Constants internal static void EmitNull(this ILGenerator il) { il.Emit(OpCodes.Ldnull); } internal static void EmitString(this ILGenerator il, string value) { ContractUtils.RequiresNotNull(value, "value"); il.Emit(OpCodes.Ldstr, value); } internal static void EmitBoolean(this ILGenerator il, bool value) { if (value) { il.Emit(OpCodes.Ldc_I4_1); } else { il.Emit(OpCodes.Ldc_I4_0); } } internal static void EmitChar(this ILGenerator il, char value) { il.EmitInt(value); il.Emit(OpCodes.Conv_U2); } internal static void EmitByte(this ILGenerator il, byte value) { il.EmitInt(value); il.Emit(OpCodes.Conv_U1); } internal static void EmitSByte(this ILGenerator il, sbyte value) { il.EmitInt(value); il.Emit(OpCodes.Conv_I1); } internal static void EmitShort(this ILGenerator il, short value) { il.EmitInt(value); il.Emit(OpCodes.Conv_I2); } internal static void EmitUShort(this ILGenerator il, ushort value) { il.EmitInt(value); il.Emit(OpCodes.Conv_U2); } internal static void EmitInt(this ILGenerator il, int value) { OpCode c; switch (value) { case -1: c = OpCodes.Ldc_I4_M1; break; case 0: c = OpCodes.Ldc_I4_0; break; case 1: c = OpCodes.Ldc_I4_1; break; case 2: c = OpCodes.Ldc_I4_2; break; case 3: c = OpCodes.Ldc_I4_3; break; case 4: c = OpCodes.Ldc_I4_4; break; case 5: c = OpCodes.Ldc_I4_5; break; case 6: c = OpCodes.Ldc_I4_6; break; case 7: c = OpCodes.Ldc_I4_7; break; case 8: c = OpCodes.Ldc_I4_8; break; default: if (value >= -128 && value <= 127) { il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); } else { il.Emit(OpCodes.Ldc_I4, value); } return; } il.Emit(c); } internal static void EmitUInt(this ILGenerator il, uint value) { il.EmitInt((int)value); il.Emit(OpCodes.Conv_U4); } internal static void EmitLong(this ILGenerator il, long value) { il.Emit(OpCodes.Ldc_I8, value); // // Now, emit convert to give the constant type information. // // Otherwise, it is treated as unsigned and overflow is not // detected if it's used in checked ops. // il.Emit(OpCodes.Conv_I8); } internal static void EmitULong(this ILGenerator il, ulong value) { il.Emit(OpCodes.Ldc_I8, (long)value); il.Emit(OpCodes.Conv_U8); } internal static void EmitDouble(this ILGenerator il, double value) { il.Emit(OpCodes.Ldc_R8, value); } internal static void EmitSingle(this ILGenerator il, float value) { il.Emit(OpCodes.Ldc_R4, value); } // matches TryEmitConstant internal static bool CanEmitConstant(object value, Type type) { if (value == null || CanEmitILConstant(type)) { return true; } Type t = value as Type; if (t != null && ShouldLdtoken(t)) { return true; } MethodBase mb = value as MethodBase; if (mb != null && ShouldLdtoken(mb)) { return true; } return false; } // matches TryEmitILConstant private static bool CanEmitILConstant(Type type) { switch (type.GetTypeCode()) { case TypeCode.Boolean: case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Char: case TypeCode.Byte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Decimal: case TypeCode.String: return true; } return false; } internal static void EmitConstant(this ILGenerator il, object value) { Debug.Assert(value != null); EmitConstant(il, value, value.GetType()); } // // Note: we support emitting more things as IL constants than // Linq does internal static void EmitConstant(this ILGenerator il, object value, Type type) { if (value == null) { // Smarter than the Linq implementation which uses the initobj // pattern for all value types (works, but requires a local and // more IL) il.EmitDefault(type); return; } // Handle the easy cases if (il.TryEmitILConstant(value, type)) { return; } // Check for a few more types that we support emitting as constants Type t = value as Type; if (t != null && ShouldLdtoken(t)) { il.EmitType(t); if (type != typeof(Type)) { il.Emit(OpCodes.Castclass, type); } return; } MethodBase mb = value as MethodBase; if (mb != null && ShouldLdtoken(mb)) { il.Emit(OpCodes.Ldtoken, mb); Type dt = mb.DeclaringType; if (dt != null && dt.GetTypeInfo().IsGenericType) { il.Emit(OpCodes.Ldtoken, dt); il.Emit(OpCodes.Call, typeof(MethodBase).GetMethod("GetMethodFromHandle", new Type[] { typeof(RuntimeMethodHandle), typeof(RuntimeTypeHandle) })); } else { il.Emit(OpCodes.Call, typeof(MethodBase).GetMethod("GetMethodFromHandle", new Type[] { typeof(RuntimeMethodHandle) })); } if (type != typeof(MethodBase)) { il.Emit(OpCodes.Castclass, type); } return; } throw ContractUtils.Unreachable; } internal static bool ShouldLdtoken(Type t) { return t.GetTypeInfo() is TypeBuilder || t.IsGenericParameter || t.GetTypeInfo().IsVisible; } internal static bool ShouldLdtoken(MethodBase mb) { // Can't ldtoken on a DynamicMethod if (mb is DynamicMethod) { return false; } Type dt = mb.DeclaringType; return dt == null || ShouldLdtoken(dt); } private static bool TryEmitILConstant(this ILGenerator il, object value, Type type) { switch (type.GetTypeCode()) { case TypeCode.Boolean: il.EmitBoolean((bool)value); return true; case TypeCode.SByte: il.EmitSByte((sbyte)value); return true; case TypeCode.Int16: il.EmitShort((short)value); return true; case TypeCode.Int32: il.EmitInt((int)value); return true; case TypeCode.Int64: il.EmitLong((long)value); return true; case TypeCode.Single: il.EmitSingle((float)value); return true; case TypeCode.Double: il.EmitDouble((double)value); return true; case TypeCode.Char: il.EmitChar((char)value); return true; case TypeCode.Byte: il.EmitByte((byte)value); return true; case TypeCode.UInt16: il.EmitUShort((ushort)value); return true; case TypeCode.UInt32: il.EmitUInt((uint)value); return true; case TypeCode.UInt64: il.EmitULong((ulong)value); return true; case TypeCode.Decimal: il.EmitDecimal((decimal)value); return true; case TypeCode.String: il.EmitString((string)value); return true; default: return false; } } #endregion #region Linq Conversions internal static void EmitConvertToType(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { if (TypeUtils.AreEquivalent(typeFrom, typeTo)) { return; } if (typeFrom == typeof(void) || typeTo == typeof(void)) { throw ContractUtils.Unreachable; } bool isTypeFromNullable = TypeUtils.IsNullableType(typeFrom); bool isTypeToNullable = TypeUtils.IsNullableType(typeTo); Type nnExprType = TypeUtils.GetNonNullableType(typeFrom); Type nnType = TypeUtils.GetNonNullableType(typeTo); if (typeFrom.GetTypeInfo().IsInterface || // interface cast typeTo.GetTypeInfo().IsInterface || typeFrom == typeof(object) || // boxing cast typeTo == typeof(object) || typeFrom == typeof(System.Enum) || typeFrom == typeof(System.ValueType) || TypeUtils.IsLegalExplicitVariantDelegateConversion(typeFrom, typeTo)) { il.EmitCastToType(typeFrom, typeTo); } else if (isTypeFromNullable || isTypeToNullable) { il.EmitNullableConversion(typeFrom, typeTo, isChecked); } else if (!(TypeUtils.IsConvertible(typeFrom) && TypeUtils.IsConvertible(typeTo)) // primitive runtime conversion && (nnExprType.IsAssignableFrom(nnType) || // down cast nnType.IsAssignableFrom(nnExprType))) // up cast { il.EmitCastToType(typeFrom, typeTo); } else if (typeFrom.IsArray && typeTo.IsArray) { // See DevDiv Bugs #94657. il.EmitCastToType(typeFrom, typeTo); } else { il.EmitNumericConversion(typeFrom, typeTo, isChecked); } } private static void EmitCastToType(this ILGenerator il, Type typeFrom, Type typeTo) { if (!typeFrom.GetTypeInfo().IsValueType && typeTo.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Unbox_Any, typeTo); } else if (typeFrom.GetTypeInfo().IsValueType && !typeTo.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Box, typeFrom); if (typeTo != typeof(object)) { il.Emit(OpCodes.Castclass, typeTo); } } else if (!typeFrom.GetTypeInfo().IsValueType && !typeTo.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Castclass, typeTo); } else { throw Error.InvalidCast(typeFrom, typeTo); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private static void EmitNumericConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { bool isFromUnsigned = TypeUtils.IsUnsigned(typeFrom); bool isFromFloatingPoint = TypeUtils.IsFloatingPoint(typeFrom); if (typeTo == typeof(Single)) { if (isFromUnsigned) il.Emit(OpCodes.Conv_R_Un); il.Emit(OpCodes.Conv_R4); } else if (typeTo == typeof(Double)) { if (isFromUnsigned) il.Emit(OpCodes.Conv_R_Un); il.Emit(OpCodes.Conv_R8); } else { TypeCode tc = typeTo.GetTypeCode(); if (isChecked) { // Overflow checking needs to know if the source value on the IL stack is unsigned or not. if (isFromUnsigned) { switch (tc) { case TypeCode.SByte: il.Emit(OpCodes.Conv_Ovf_I1_Un); break; case TypeCode.Int16: il.Emit(OpCodes.Conv_Ovf_I2_Un); break; case TypeCode.Int32: il.Emit(OpCodes.Conv_Ovf_I4_Un); break; case TypeCode.Int64: il.Emit(OpCodes.Conv_Ovf_I8_Un); break; case TypeCode.Byte: il.Emit(OpCodes.Conv_Ovf_U1_Un); break; case TypeCode.UInt16: case TypeCode.Char: il.Emit(OpCodes.Conv_Ovf_U2_Un); break; case TypeCode.UInt32: il.Emit(OpCodes.Conv_Ovf_U4_Un); break; case TypeCode.UInt64: il.Emit(OpCodes.Conv_Ovf_U8_Un); break; default: throw Error.UnhandledConvert(typeTo); } } else { switch (tc) { case TypeCode.SByte: il.Emit(OpCodes.Conv_Ovf_I1); break; case TypeCode.Int16: il.Emit(OpCodes.Conv_Ovf_I2); break; case TypeCode.Int32: il.Emit(OpCodes.Conv_Ovf_I4); break; case TypeCode.Int64: il.Emit(OpCodes.Conv_Ovf_I8); break; case TypeCode.Byte: il.Emit(OpCodes.Conv_Ovf_U1); break; case TypeCode.UInt16: case TypeCode.Char: il.Emit(OpCodes.Conv_Ovf_U2); break; case TypeCode.UInt32: il.Emit(OpCodes.Conv_Ovf_U4); break; case TypeCode.UInt64: il.Emit(OpCodes.Conv_Ovf_U8); break; default: throw Error.UnhandledConvert(typeTo); } } } else { switch (tc) { case TypeCode.SByte: il.Emit(OpCodes.Conv_I1); break; case TypeCode.Byte: il.Emit(OpCodes.Conv_U1); break; case TypeCode.Int16: il.Emit(OpCodes.Conv_I2); break; case TypeCode.UInt16: case TypeCode.Char: il.Emit(OpCodes.Conv_U2); break; case TypeCode.Int32: il.Emit(OpCodes.Conv_I4); break; case TypeCode.UInt32: il.Emit(OpCodes.Conv_U4); break; case TypeCode.Int64: if (isFromUnsigned) { il.Emit(OpCodes.Conv_U8); } else { il.Emit(OpCodes.Conv_I8); } break; case TypeCode.UInt64: if (isFromUnsigned || isFromFloatingPoint) { il.Emit(OpCodes.Conv_U8); } else { il.Emit(OpCodes.Conv_I8); } break; default: throw Error.UnhandledConvert(typeTo); } } } } private static void EmitNullableToNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { Debug.Assert(TypeUtils.IsNullableType(typeFrom)); Debug.Assert(TypeUtils.IsNullableType(typeTo)); Label labIfNull = default(Label); Label labEnd = default(Label); LocalBuilder locFrom = null; LocalBuilder locTo = null; locFrom = il.DeclareLocal(typeFrom); il.Emit(OpCodes.Stloc, locFrom); locTo = il.DeclareLocal(typeTo); // test for null il.Emit(OpCodes.Ldloca, locFrom); il.EmitHasValue(typeFrom); labIfNull = il.DefineLabel(); il.Emit(OpCodes.Brfalse_S, labIfNull); il.Emit(OpCodes.Ldloca, locFrom); il.EmitGetValueOrDefault(typeFrom); Type nnTypeFrom = TypeUtils.GetNonNullableType(typeFrom); Type nnTypeTo = TypeUtils.GetNonNullableType(typeTo); il.EmitConvertToType(nnTypeFrom, nnTypeTo, isChecked); // construct result type ConstructorInfo ci = typeTo.GetConstructor(new Type[] { nnTypeTo }); il.Emit(OpCodes.Newobj, ci); il.Emit(OpCodes.Stloc, locTo); labEnd = il.DefineLabel(); il.Emit(OpCodes.Br_S, labEnd); // if null then create a default one il.MarkLabel(labIfNull); il.Emit(OpCodes.Ldloca, locTo); il.Emit(OpCodes.Initobj, typeTo); il.MarkLabel(labEnd); il.Emit(OpCodes.Ldloc, locTo); } private static void EmitNonNullableToNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { Debug.Assert(!TypeUtils.IsNullableType(typeFrom)); Debug.Assert(TypeUtils.IsNullableType(typeTo)); LocalBuilder locTo = null; locTo = il.DeclareLocal(typeTo); Type nnTypeTo = TypeUtils.GetNonNullableType(typeTo); il.EmitConvertToType(typeFrom, nnTypeTo, isChecked); ConstructorInfo ci = typeTo.GetConstructor(new Type[] { nnTypeTo }); il.Emit(OpCodes.Newobj, ci); il.Emit(OpCodes.Stloc, locTo); il.Emit(OpCodes.Ldloc, locTo); } private static void EmitNullableToNonNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { Debug.Assert(TypeUtils.IsNullableType(typeFrom)); Debug.Assert(!TypeUtils.IsNullableType(typeTo)); if (typeTo.GetTypeInfo().IsValueType) il.EmitNullableToNonNullableStructConversion(typeFrom, typeTo, isChecked); else il.EmitNullableToReferenceConversion(typeFrom); } private static void EmitNullableToNonNullableStructConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { Debug.Assert(TypeUtils.IsNullableType(typeFrom)); Debug.Assert(!TypeUtils.IsNullableType(typeTo)); Debug.Assert(typeTo.GetTypeInfo().IsValueType); LocalBuilder locFrom = null; locFrom = il.DeclareLocal(typeFrom); il.Emit(OpCodes.Stloc, locFrom); il.Emit(OpCodes.Ldloca, locFrom); il.EmitGetValue(typeFrom); Type nnTypeFrom = TypeUtils.GetNonNullableType(typeFrom); il.EmitConvertToType(nnTypeFrom, typeTo, isChecked); } private static void EmitNullableToReferenceConversion(this ILGenerator il, Type typeFrom) { Debug.Assert(TypeUtils.IsNullableType(typeFrom)); // We've got a conversion from nullable to Object, ValueType, Enum, etc. Just box it so that // we get the nullable semantics. il.Emit(OpCodes.Box, typeFrom); } private static void EmitNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { bool isTypeFromNullable = TypeUtils.IsNullableType(typeFrom); bool isTypeToNullable = TypeUtils.IsNullableType(typeTo); Debug.Assert(isTypeFromNullable || isTypeToNullable); if (isTypeFromNullable && isTypeToNullable) il.EmitNullableToNullableConversion(typeFrom, typeTo, isChecked); else if (isTypeFromNullable) il.EmitNullableToNonNullableConversion(typeFrom, typeTo, isChecked); else il.EmitNonNullableToNullableConversion(typeFrom, typeTo, isChecked); } internal static void EmitHasValue(this ILGenerator il, Type nullableType) { MethodInfo mi = nullableType.GetMethod("get_HasValue", BindingFlags.Instance | BindingFlags.Public); Debug.Assert(nullableType.GetTypeInfo().IsValueType); il.Emit(OpCodes.Call, mi); } internal static void EmitGetValue(this ILGenerator il, Type nullableType) { MethodInfo mi = nullableType.GetMethod("get_Value", BindingFlags.Instance | BindingFlags.Public); Debug.Assert(nullableType.GetTypeInfo().IsValueType); il.Emit(OpCodes.Call, mi); } internal static void EmitGetValueOrDefault(this ILGenerator il, Type nullableType) { MethodInfo mi = nullableType.GetMethod("GetValueOrDefault", System.Type.EmptyTypes); Debug.Assert(nullableType.GetTypeInfo().IsValueType); il.Emit(OpCodes.Call, mi); } #endregion #region Arrays /// <summary> /// Emits an array of constant values provided in the given list. /// The array is strongly typed. /// </summary> internal static void EmitArray<T>(this ILGenerator il, IList<T> items) { ContractUtils.RequiresNotNull(items, "items"); il.EmitInt(items.Count); il.Emit(OpCodes.Newarr, typeof(T)); for (int i = 0; i < items.Count; i++) { il.Emit(OpCodes.Dup); il.EmitInt(i); il.EmitConstant(items[i], typeof(T)); il.EmitStoreElement(typeof(T)); } } /// <summary> /// Emits an array of values of count size. The items are emitted via the callback /// which is provided with the current item index to emit. /// </summary> internal static void EmitArray(this ILGenerator il, Type elementType, int count, Action<int> emit) { ContractUtils.RequiresNotNull(elementType, "elementType"); ContractUtils.RequiresNotNull(emit, "emit"); if (count < 0) throw Error.CountCannotBeNegative(); il.EmitInt(count); il.Emit(OpCodes.Newarr, elementType); for (int i = 0; i < count; i++) { il.Emit(OpCodes.Dup); il.EmitInt(i); emit(i); il.EmitStoreElement(elementType); } } /// <summary> /// Emits an array construction code. /// The code assumes that bounds for all dimensions /// are already emitted. /// </summary> internal static void EmitArray(this ILGenerator il, Type arrayType) { ContractUtils.RequiresNotNull(arrayType, "arrayType"); if (!arrayType.IsArray) throw Error.ArrayTypeMustBeArray(); if (arrayType.IsVector()) { il.Emit(OpCodes.Newarr, arrayType.GetElementType()); } else { int rank = arrayType.GetArrayRank(); Type[] types = new Type[rank]; for (int i = 0; i < rank; i++) { types[i] = typeof(int); } il.EmitNew(arrayType, types); } } #endregion #region Support for emitting constants internal static void EmitDecimal(this ILGenerator il, decimal value) { if (Decimal.Truncate(value) == value) { if (Int32.MinValue <= value && value <= Int32.MaxValue) { int intValue = Decimal.ToInt32(value); il.EmitInt(intValue); il.EmitNew(typeof(Decimal).GetConstructor(new Type[] { typeof(int) })); } else if (Int64.MinValue <= value && value <= Int64.MaxValue) { long longValue = Decimal.ToInt64(value); il.EmitLong(longValue); il.EmitNew(typeof(Decimal).GetConstructor(new Type[] { typeof(long) })); } else { il.EmitDecimalBits(value); } } else { il.EmitDecimalBits(value); } } private static void EmitDecimalBits(this ILGenerator il, decimal value) { int[] bits = Decimal.GetBits(value); il.EmitInt(bits[0]); il.EmitInt(bits[1]); il.EmitInt(bits[2]); il.EmitBoolean((bits[3] & 0x80000000) != 0); il.EmitByte((byte)(bits[3] >> 16)); il.EmitNew(typeof(decimal).GetConstructor(new Type[] { typeof(int), typeof(int), typeof(int), typeof(bool), typeof(byte) })); } /// <summary> /// Emits default(T) /// Semantics match C# compiler behavior /// </summary> internal static void EmitDefault(this ILGenerator il, Type type) { switch (type.GetTypeCode()) { case TypeCode.Object: case TypeCode.DateTime: if (type.GetTypeInfo().IsValueType) { // Type.GetTypeCode on an enum returns the underlying // integer TypeCode, so we won't get here. Debug.Assert(!type.GetTypeInfo().IsEnum); // This is the IL for default(T) if T is a generic type // parameter, so it should work for any type. It's also // the standard pattern for structs. LocalBuilder lb = il.DeclareLocal(type); il.Emit(OpCodes.Ldloca, lb); il.Emit(OpCodes.Initobj, type); il.Emit(OpCodes.Ldloc, lb); } else { il.Emit(OpCodes.Ldnull); } break; case TypeCode.Empty: case TypeCode.String: il.Emit(OpCodes.Ldnull); break; case TypeCode.Boolean: case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: il.Emit(OpCodes.Ldc_I4_0); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Conv_I8); break; case TypeCode.Single: il.Emit(OpCodes.Ldc_R4, default(Single)); break; case TypeCode.Double: il.Emit(OpCodes.Ldc_R8, default(Double)); break; case TypeCode.Decimal: il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Newobj, typeof(Decimal).GetConstructor(new Type[] { typeof(int) })); break; default: throw ContractUtils.Unreachable; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using CodeFirstWebFramework; namespace AccountServer { /// <summary> /// Banking module has some functionality in common with Banking (e.g. NameAddress maintenance) /// </summary> public class Banking : BankingAccounting { protected override void Init() { base.Init(); InsertMenuOptions( new MenuOption("Listing", "/banking/default.html"), new MenuOption("Names", "/banking/names.html") ); if (!SecurityOn || UserAccessLevel >= AccessLevel.ReadWrite) InsertMenuOptions( new MenuOption("New Account", "/banking/detail.html?id=0") ); } /// <summary> /// List all bank accounts and credit cards /// </summary> /// <returns></returns> public object DefaultListing() { return Database.Query("Account.*, AcctType, SUM(Amount) AS Balance", "WHERE AccountTypeId " + Database.In(AcctType.Bank, AcctType.CreditCard, AcctType.OtherAsset, AcctType.OtherLiability) + " GROUP BY idAccount ORDER BY AccountName", "Account", "Journal"); } /// <summary> /// Retrieve a bank/credit card account for editing /// </summary> public void Detail(int id) { BankingDetail record = Database.QueryOne<BankingDetail>("Account.*, AcctType, SUM(Amount) AS Balance", "WHERE idAccount = " + id, "Account", "Journal"); // Subtract future transactions to get current balance record.CurrentBalance = record.Balance - Database.QueryOne("SELECT SUM(Amount) AS Future FROM Journal JOIN Document ON idDocument = DocumentId WHERE AccountId = " + id + " AND DocumentDate > " + Database.Quote(Utils.Today)).AsDecimal("Future"); if (record.Id != null) { checkAcctType(record.AccountTypeId, AcctType.Bank, AcctType.CreditCard, AcctType.OtherAsset, AcctType.OtherLiability); Title += " - " + record.AccountName; } JObject r = record.ToJObject(); addMenuOptionstoRecord(r, record); Record = r; } /// <summary> /// Journal listing for an account /// </summary> public IEnumerable<JObject> DetailListing(int id) { return detailsWithBalance(id).Reverse(); } /// <summary> /// Update account details after editing /// </summary> public AjaxReturn DetailSave(Account json) { checkAcctType(json.AccountTypeId, AcctType.Bank, AcctType.CreditCard, AcctType.OtherAsset, AcctType.OtherLiability); return SaveRecord(json, true); } void addMenuOptionstoRecord(JObject record, Account account) { List<JObject> plus = new List<JObject>(); List<JObject> minus = new List<JObject>(); if (account.AccountTypeId == (int)AcctType.CreditCard) { plus.Add(new JObject().AddRange("text", "Card Credit", "href", "document?id=0&type=" + (int)DocType.CreditCardCredit + "&acct=" + account.idAccount)); minus.Add(new JObject().AddRange("text", "Card Charge", "href", "document?id=0&type=" + (int)DocType.CreditCardCharge + "&acct=" + account.idAccount)); } else { plus.Add(new JObject().AddRange("text", "Deposit", "href", "document?id=0&type=" + (int)DocType.Deposit + "&acct=" + account.idAccount)); minus.Add(new JObject().AddRange("text", "Withdrawal", "href", "document?id=0&type=" + (int)DocType.Withdrawal + "&acct=" + account.idAccount)); } JObject c = Database.Query("SELECT COUNT(*) AS numAccounts FROM Account WHERE AccountTypeId " + Database.In((int)AcctType.Bank, (int)AcctType.CreditCard, AcctType.OtherAsset, AcctType.OtherLiability)).FirstOrDefault(); if (c != null && c.AsInt("numAccounts") > 1) { plus.Add(new JObject().AddRange("text", "Transfer", "href", "transfer?id=0&acct2=" + account.idAccount)); minus.Add(new JObject().AddRange("text", "Transfer", "href", "transfer?id=0&acct=" + account.idAccount)); } if (Settings.Customers) plus.Add(new JObject().AddRange("text", "Customer Payment", "href", "/customer/payment?id=0&acct=" + account.idAccount)); if (Settings.Suppliers) minus.Add(new JObject().AddRange("text", "Bill Payment", "href", "/supplier/payment?id=0&acct=" + account.idAccount)); if (Settings.Members) plus.Add(new JObject().AddRange("text", "Subscriptions", "href", "/members/document?id=0&acct=" + account.idAccount)); record.AddRange("plus", plus, "minus", minus); } /// <summary> /// Get a specific document (or a filled in new document) for this account /// </summary> internal JObject GetDocument(int id, DocType type) { Extended_Document header = getDocument<Extended_Document>(id); if (header.idDocument == null) { header.DocumentTypeId = (int)type; header.DocType = type.UnCamel(); header.DocumentDate = Utils.Today; header.DocumentName = ""; if (GetParameters["acct"].IsInteger()) { FullAccount acct = Database.QueryOne<FullAccount>("*", "WHERE idAccount = " + GetParameters["acct"], "Account"); if (acct.idAccount != null) { header.DocumentAccountId = (int)acct.idAccount; header.DocumentAccountName = acct.AccountName; } } } else { checkDocType(header.DocumentTypeId, DocType.Withdrawal, DocType.Deposit, DocType.CreditCardCharge, DocType.CreditCardCredit); } return new JObject().AddRange("header", header, "detail", Database.Query("idJournal, DocumentId, Line.VatCodeId, VatRate, JournalNum, Journal.AccountId, Memo, LineAmount, VatAmount", "WHERE Journal.DocumentId = " + id + " AND idLine IS NOT NULL ORDER BY JournalNum", "Document", "Journal", "Line")); } /// <summary> /// Get a document for editing /// </summary> public void Document(int id, DocType type) { Title = Title.Replace("Document", type.UnCamel()); JObject record = GetDocument(id, type); dynamic header = ((dynamic)record).header; nextPreviousDocument(record, "JOIN Journal ON DocumentId = idDocument WHERE DocumentTypeId = " + (int)type + (header.DocumentAccountId > 0 ? " AND AccountId = " + header.DocumentAccountId : "")); record.AddRange("Accounts", SelectAccounts(), "VatCodes", SelectVatCodes(), "Names", SelectOthers()); Record = record; } public AjaxReturn DocumentDelete(int id) { return deleteDocument(id, DocType.Withdrawal, DocType.Deposit, DocType.CreditCardCharge, DocType.CreditCardCredit); } /// <summary> /// Update a document after editing /// </summary> public AjaxReturn DocumentSave(BankingDocument json) { Database.BeginTransaction(); Extended_Document document = json.header; JObject oldDoc = getCompleteDocument(document.idDocument); DocType t = checkDocType(document.DocumentTypeId, DocType.Withdrawal, DocType.Deposit, DocType.CreditCardCharge, DocType.CreditCardCredit); FullAccount acct = Database.Get<FullAccount>((int)document.DocumentAccountId); checkAcctType(acct.AccountTypeId, AcctType.Bank, AcctType.CreditCard, AcctType.Investment, AcctType.OtherAsset, AcctType.OtherLiability); allocateDocumentIdentifier(document, acct); int sign = SignFor(t); Extended_Document original = getDocument(document); decimal vat = 0; decimal net = 0; bool lineVat = false; // Flag to indicate this is a withdrawal to pay the VAT to HMRC foreach (InvoiceLine detail in json.detail) { if (detail.AccountId == 0 || detail.AccountId == null) { Utils.Check(detail.LineAmount == 0 && detail.VatAmount == 0, "All lines must be allocated to an account"); continue; } net += detail.LineAmount; vat += detail.VatAmount; } Utils.Check(document.DocumentAmount == net + vat, "Document does not balance"); decimal changeInDocumentAmount = -sign * (document.DocumentAmount - original.DocumentAmount); int lineNum = 1; fixNameAddress(document, "O"); Database.Update(document); int nextDocid = Utils.ExtractNumber(document.DocumentIdentifier); if (nextDocid > 0 && acct.RegisterNumber(t, nextDocid)) Database.Update(acct); // Find any existing VAT record Journal vatJournal = Database.QueryOne<Journal>("SELECT * FROM Journal WHERE DocumentId = " + document.idDocument + " AND AccountId = " + (int)Acct.VATControl + " ORDER BY JournalNum DESC"); Journal journal = Database.Get(new Journal() { DocumentId = (int)document.idDocument, JournalNum = lineNum }); journal.DocumentId = (int)document.idDocument; journal.AccountId = document.DocumentAccountId; journal.NameAddressId = document.DocumentNameAddressId; journal.Memo = document.DocumentMemo; journal.JournalNum = lineNum++; journal.Amount += changeInDocumentAmount; journal.Outstanding += changeInDocumentAmount; Database.Update(journal); foreach (InvoiceLine detail in json.detail) { if (detail.AccountId == 0 || detail.AccountId == null) continue; Utils.Check(!lineVat, "Withdrawal to VAT account may only have 1 line"); if (detail.AccountId == (int)Acct.VATControl) { // This is a VAT payment to HMRC Utils.Check(lineNum == 2, "Withdrawal to VAT account may only have 1 line"); Utils.Check(vat == 0, "Withdrawal to VAT account may not have a VAT amount"); vat = detail.LineAmount; lineVat = true; } journal = Database.Get(new Journal() { DocumentId = (int)document.idDocument, JournalNum = lineNum }); journal.DocumentId = (int)document.idDocument; journal.JournalNum = lineNum++; journal.AccountId = (int)detail.AccountId; journal.NameAddressId = document.DocumentNameAddressId; journal.Memo = detail.Memo; journal.Amount = sign * detail.LineAmount; journal.Outstanding = sign * detail.LineAmount; Database.Update(journal); Line line = new Line() { idLine = journal.idJournal, Qty = 0, LineAmount = detail.LineAmount, VatCodeId = detail.VatCodeId, VatRate = detail.VatRate, VatAmount = detail.VatAmount }; Database.Update(line); } Database.Execute("DELETE FROM Line WHERE idLine IN (SELECT idJournal FROM Journal WHERE DocumentId = " + document.idDocument + " AND JournalNum >= " + lineNum + ")"); Database.Execute("DELETE FROM Journal WHERE DocumentId = " + document.idDocument + " AND JournalNum >= " + lineNum); if (vat != 0 || vatJournal.idJournal != null) { // Add the VAT journal at the end vat *= sign; decimal changeInVatAmount = vat - vatJournal.Amount; Utils.Check(document.VatPaid == null || document.VatPaid < 1 || changeInVatAmount == 0, "Cannot alter VAT on this document, it has already been declared"); if (!lineVat) { vatJournal.DocumentId = (int)document.idDocument; vatJournal.AccountId = (int)Acct.VATControl; vatJournal.NameAddressId = document.DocumentNameAddressId; vatJournal.Memo = "Total VAT"; vatJournal.JournalNum = lineNum++; vatJournal.Amount = vat; vatJournal.Outstanding += changeInVatAmount; Database.Update(vatJournal); } } JObject newDoc = getCompleteDocument(document.idDocument); Database.AuditUpdate("Document", document.idDocument, oldDoc, newDoc); Settings.RegisterNumber(this, document.DocumentTypeId, Utils.ExtractNumber(document.DocumentIdentifier)); Database.Commit(); return new AjaxReturn() { message = "Document saved", id = document.idDocument }; } /// <summary> /// Bank reconciliation /// </summary> /// <param name="id"></param> [Auth(AccessLevel.ReadWrite, Hide = true)] public void Reconcile(int id) { JObject header = Database.QueryOne("*", "WHERE idAccount = " + id, "Account"); JObject openingBalance = Database.QueryOne("SELECT SUM(Amount) AS OpeningBalance FROM Journal WHERE AccountId = " + id + " AND Cleared = 'X'"); header["OpeningBalance"] = openingBalance == null ? 0 : openingBalance.AsDecimal("OpeningBalance"); Title += " - " + header.AsString("AccountName"); checkAccountIsAcctType(id, AcctType.Bank, AcctType.CreditCard, AcctType.OtherAsset, AcctType.OtherLiability); Record = new JObject().AddRange("header", header, "detail", Database.Query(@"SELECT Extended_Document.*, Journal.idJournal, Journal.Cleared, Journal.Amount FROM Journal JOIN Extended_Document ON idDocument = DocumentId WHERE Journal.AccountId = " + id + @" AND Journal.Cleared <> 'X' ORDER BY DocumentDate, idDocument")); } /// <summary> /// Save bank reconciliation /// </summary> public AjaxReturn ReconcileSave(ReconcileDocument json) { // Temporary indicates they haven't finished - no need to check balances, save Clr marks as "*" instead of "X" string mark = json.Temporary ? "*" : "X"; decimal bal = json.header.OpeningBalance; Utils.Check(json.header.idAccount > 0, "Invalid account"); Database.BeginTransaction(); if (!json.Temporary) Database.Audit(AuditType.Reconcile, "Reconciliation", json.header.idAccount, json.ToJson(), null); Database.Execute("UPDATE Account SET EndingBalance = " + Database.Quote(json.Temporary ? json.header.EndingBalance : null) + " WHERE idAccount = " + json.header.idAccount); foreach (ReconcileLine line in json.detail) { string mk; if (line.Cleared == "1" || line.Cleared == "*") { bal += line.Amount; mk = mark; } else { mk = ""; } Database.Execute("UPDATE Journal SET Cleared = " + Database.Quote(mk) + " WHERE idJournal = " + line.idJournal); } Utils.Check(json.Temporary || json.header.EndingBalance != null, "You must enter an Ending Balance"); Utils.Check(json.Temporary || bal == json.header.EndingBalance && bal == json.header.ClearedBalance, "Reconcile does not balance"); Database.Commit(); return new AjaxReturn() { message = "Reconcile saved", redirect = json.print ? null : "/Banking/Detail?id=" + json.header.idAccount }; } /// <summary> /// Prepare to memorise a transaction for automatic retrieval and saving later. /// </summary> public void Memorise(int id) { dynamic record = GetDocument(id, DocType.Withdrawal); Utils.Check(record.header.idDocument != null, "Document {0} not found", id); DocType type = (DocType)record.header.DocumentTypeId; Schedule job = new Schedule() { ActionDate = record.header.DocumentDate, Task = type.UnCamel() + " " + record.header.DocumentAmount.ToString("0.00") + (type == DocType.Withdrawal || type == DocType.CreditCardCharge ? " to " : " from ") + record.header.DocumentName + " " + record.header.DocumentMemo, Url = "banking/standingordersave", Parameters = record.ToString(), RepeatFrequency = 1, Post = true }; Module = "home"; Method = "job"; Record = job; } /// <summary> /// Save a memorised transaction schedule record after editing/review /// </summary> public AjaxReturn MemoriseSave(Schedule json) { return SaveRecord(json, false); } /// <summary> /// Save a memorised transaction, then redirect to it for review /// </summary> public AjaxReturn StandingOrderSave(BankingDocument json, DateTime date) { json.header.idDocument = null; json.header.DocumentDate = date; if (Utils.ExtractNumber(json.header.DocumentIdentifier) > 0) json.header.DocumentIdentifier = ""; AjaxReturn result = DocumentSave(json); if (result.error == null && result.id > 0) result.redirect = "/banking/document.html?message=" + json.header.DocType.UnCamel() + "+saved&id=" + result.id + "&type=" + json.header.DocumentTypeId; return result; } /// <summary> /// Prepare to memorise a transaction for automatic retrieval and saving later. /// </summary> public void MemoriseTransfer(int id) { TransferDocument header = GetTransferDocument(id); Utils.Check(header.idDocument != null, "Transfer {0} not found", id); Account account = Database.Get<Account>((int)header.TransferAccountId); checkDocType(header.DocumentTypeId, DocType.Transfer); Schedule job = new Schedule() { ActionDate = header.DocumentDate, Task = "Transfer " + header.DocumentAmount.ToString("0.00") + " from " + header.DocumentAccountName + " to " + account.AccountName + " " + header.DocumentMemo, Url = "banking/repeattransfersave", Parameters = header.ToString(), RepeatFrequency = 1, Post = true }; Module = "home"; Method = "job"; Record = job; } /// <summary> /// Save a memorised transaction schedule record after editing/review /// </summary> public AjaxReturn MemoriseTransferSave(Schedule json) { return SaveRecord(json, false); } /// <summary> /// Save a memorised transaction, then redirect to it for review /// </summary> public AjaxReturn RepeatTransferSave(TransferDocument json, DateTime date) { json.idDocument = null; json.DocumentDate = date; AjaxReturn result = TransferSave(json); if (result.error == null && result.id > 0) result.redirect = "/banking/transfer.html?message=Transfer+saved&id=" + result.id; return result; } /// <summary> /// Show ImportHelp template /// </summary> public void ImportHelp() { } /// <summary> /// Statement import form /// </summary> [Auth(AccessLevel.ReadWrite, Hide = true)] public void StatementImport(int id) { Account account = Database.Get<Account>(id); checkAcctType(account.AccountTypeId, AcctType.Bank, AcctType.CreditCard, AcctType.OtherAsset, AcctType.OtherLiability); Title += " - " + account.AccountName; Record = new JObject().AddRange( "Id", id, "StatementFormat", account.StatementFormat); SessionData.Remove("StatementImport"); SessionData.Remove("StatementMatch"); } /// <summary> /// User wants to import a statement /// </summary> /// <param name="id">Account</param> /// <param name="format">Statement format (for pasted statement)</param> /// <param name="data">Pasted statement</param> /// <param name="file">Uploaded Qif statement</param> /// <param name="dateFormat">For Qif import</param> public void StatementImportSave(int id, string format, string data, UploadedFile file, string dateFormat) { Account account = Database.Get<Account>(id); checkAcctType(account.AccountTypeId, AcctType.Bank, AcctType.CreditCard, AcctType.OtherAsset, AcctType.OtherLiability); JArray result; DateTime minDate = DateTime.MaxValue; if (!string.IsNullOrWhiteSpace(file.Content)) { // They have uploaded a Qif file QifImporter qif = new QifImporter() { DateFormat = dateFormat }; result = qif.ImportTransactions(new System.IO.StreamReader(file.Stream()), this); Utils.Check(result.Count > 0, "No transactions found"); minDate = result.Min(i => (DateTime)i["Date"]); } else { // They have uploaded pasted data data = data.Replace("\r", "") + "\n"; Utils.Check(!string.IsNullOrWhiteSpace(format), "You must enter a Statement Format"); // See Import Help for details of format notation format = format.Replace("\r", "").Replace("\t", "{Tab}").Replace("\n", "{Newline}"); string regex = format .Replace("{Tab}", @"\t") .Replace("{Newline}", @"\n"); regex = Regex.Replace(regex, @"\{Any\}", delegate(Match m) { // Look at next character string terminator = regex.Substring(m.Index + m.Length, 1); switch (terminator) { case @"\n": case @"\t": break; default: // Terminate "ignore any" section at next newline or tab terminator = @"\t\n"; break; } return @"[^" + terminator + @"]*?"; }); regex = Regex.Replace(regex, @"\{Optional:([^}]+)\}", "(?:$1)?"); regex = Regex.Replace(regex, @"\{([^}]+)\}", delegate(Match m) { // Look at next character string terminator = m.Index + m.Length >= regex.Length ? "" : regex.Substring(m.Index + m.Length, 1); switch (terminator) { case @"\n": case @"\t": break; default: // Terminate field at next newline or tab terminator = @"\t\n"; break; } // Create named group with name from inside {} return @"(?<" + m.Groups[1] + @">[^" + terminator + @"]*?)"; }); regex = "(?<=^|\n)" + regex; result = new JArray(); Regex r = new Regex(regex, RegexOptions.Singleline); bool valid = false; foreach (Match m in r.Matches(data)) { JObject o = new JObject(); string value = null; try { decimal amount = 0; foreach (string groupName in r.GetGroupNames()) { value = m.Groups[groupName].Value; switch (groupName) { case "0": break; case "Date": DateTime date = DateTime.Parse(value); if (date < minDate) minDate = date; o["Date"] = date; break; case "Amount": Utils.Check(extractAmount(value, ref amount), "Unrecognised Amount {0}", value); o["Amount"] = -amount; break; case "Payment": if (extractAmount(value, ref amount)) o["Amount"] = -Math.Abs(amount); break; case "Deposit": if (extractAmount(value, ref amount)) o["Amount"] = Math.Abs(amount); break; default: o[groupName] = value; break; } } Utils.Check(o["Amount"] != null, "No Payment, Deposit or Amount"); Utils.Check(o["Date"] != null, "No Date"); valid = true; } catch (Exception ex) { o["@class"] = "warning"; o["Name"] = ex.Message + ":" + value + ":" + m.Value; } result.Add(o); } if (valid) { // The format was valid - save it to the account for next time account.StatementFormat = format; Database.Update(account); } } JObject record = new JObject().AddRange( "id", id, "import", result, "transactions", potentialMatches(id, minDate) ); addMenuOptionstoRecord(record, account); // Save data to session SessionData.StatementImport = record; SessionData.Remove("StatementMatch"); Redirect("/banking/statementmatching.html?from=%2Fbanking%2Fdetail%3Fid%3D" + id); } /// <summary> /// Extract monetary amount from a string. Return true if one was found /// </summary> static bool extractAmount(string a, ref decimal amount) { string dot = Regex.Escape(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator); Match v = Regex.Match(a.Replace(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyGroupSeparator, ""), @"([^\d" + dot + @"]*)([\d" + dot + @"]+)"); if (!v.Success) return false; amount = decimal.Parse(v.Groups[2].Value); a = v.Groups[1].Value; if(a.Contains("-") || a.Contains("CR")) amount = -amount; return true; } /// <summary> /// Return all possible potential matches for transactions after minDate - 7 days /// </summary> IEnumerable<JObject> potentialMatches(int id, DateTime minDate) { HashSet<string> existing = new HashSet<string>(); minDate = minDate.AddDays(-7); foreach (dynamic doc in DetailListing(id)) { if (doc.DocumentDate >= minDate || doc.Clr != "X") { // Unreconciled transaction in date range - all these are possible matches yield return doc; } else { // Otherwise return 1 transaction for each unique Name, Type, Memo string key = doc.DocumentName + ":" + doc.DocumentTypeId + ":" + doc.DocumentMemo; if (existing.Contains(key)) continue; existing.Add(key); yield return doc; } } } /// <summary> /// Return saved session data for statement matching /// </summary> [Auth(AccessLevel.ReadWrite, Hide = true)] public void StatementMatching() { Record = SessionData.StatementImport; SessionData.Remove("StatementMatch"); } /// <summary> /// Update 1 matched transaction /// </summary> public AjaxReturn StatementMatchingSave(MatchInfo json) { int acct = SessionData.StatementImport.id; checkAccountIsAcctType(acct, AcctType.Bank, AcctType.CreditCard, AcctType.OtherAsset, AcctType.OtherLiability); JObject current = SessionData.StatementImport.import[json.current]; Utils.Check(current != null, "Current not found"); if (json.transaction >= 0) { Extended_Document transaction = SessionData.StatementImport.transactions[json.transaction].ToObject<Extended_Document>(); checkDocType(transaction.DocumentTypeId, DocType.Payment, DocType.BillPayment, DocType.Withdrawal, DocType.Deposit, DocType.CreditCardCharge, DocType.CreditCardCredit, DocType.Transfer, DocType.Subscriptions); } // Save json to session SessionData.StatementMatch = json.ToJToken(); return new AjaxReturn() { redirect = "statementmatch.html?from=%2Fbanking%2Fstatementmatching.html" }; } /// <summary> /// Update a matched transaction /// </summary> [Auth(AccessLevel.ReadWrite, Hide = true)] public void StatementMatch() { Utils.Check(SessionData.StatementMatch != null, "Invalid call to StatementMatch"); MatchInfo match = SessionData.StatementMatch.ToObject<MatchInfo>(); int acct = SessionData.StatementImport.id; Account account = Database.Get<Account>(acct); // The existing transaction to match (or empty record if none) Extended_Document transaction = match.transaction < 0 ? Database.EmptyRecord<Extended_Document>() : SessionData.StatementImport.transactions[match.transaction].ToObject<Extended_Document>(); // The statement transaction dynamic current = SessionData.StatementImport.import[match.current]; Utils.Check(current != null, "No current transaction"); bool same = match.type == "Same"; bool documentHasVat = false; bool payment = false; decimal cAmount = current.Amount; int id = transaction.idDocument ?? 0; DocType type; if(match.transaction >= 0) type = (DocType)transaction.DocumentTypeId; else switch(match.type) { case "Deposit": Utils.Check(account.AccountTypeId == (int)AcctType.Bank || account.AccountTypeId == (int)AcctType.OtherAsset || account.AccountTypeId == (int)AcctType.OtherLiability, "Deposit not to bank account"); type = DocType.Deposit; break; case "CardCredit": Utils.Check(account.AccountTypeId == (int)AcctType.CreditCard, "Credit not to credit card"); type = DocType.CreditCardCredit; break; case "Transfer": type = DocType.Transfer; break; case "CustomerPayment": type = DocType.Payment; break; case "Subscriptions": type = DocType.Subscriptions; break; case "Withdrawal": Utils.Check(account.AccountTypeId == (int)AcctType.Bank || account.AccountTypeId == (int)AcctType.OtherAsset || account.AccountTypeId == (int)AcctType.OtherLiability, "Withdrawal not to bank account"); type = DocType.Withdrawal; break; case "CardCharge": Utils.Check(account.AccountTypeId == (int)AcctType.CreditCard, "Charge not to credit card"); type = DocType.CreditCardCharge; break; case "BillPayment": type = DocType.BillPayment; break; default: throw new CheckException("Unknown match type {0}", match.type); } GetParameters["acct"] = acct.ToString(); // This bank account string nameType = "O"; // Call appropriate method to get Record, and therefore transaction // Also set Module and Method, so appropriate template is used to display transaction before posting switch (type) { case DocType.Payment: Module = "customer"; Method = "payment"; Customer cust = new Customer() { CopyFrom = this }; cust.Payment(id); this.Record = cust.Record; this.Form = cust.Form; payment = true; nameType = "C"; break; case DocType.BillPayment: Module = "supplier"; Method = "payment"; Supplier supp = new Supplier() { CopyFrom = this }; supp.Payment(id); this.Record = supp.Record; this.Form = supp.Form; payment = true; nameType = "S"; break; case DocType.Withdrawal: case DocType.Deposit: case DocType.CreditCardCharge: case DocType.CreditCardCredit: Method = "document"; Document(id, type); documentHasVat = true; break; case DocType.Transfer: Method = "transfer"; Transfer(id); break; case DocType.Subscriptions: Module = "Members"; Method = "document"; Members member = new Members() { CopyFrom = this }; member.Document(id); this.Record = member.Record; this.Form = member.Form; nameType = "M"; break; default: throw new CheckException("Unexpected document type:{0}", type.UnCamel()); } dynamic record = (JObject)Record; dynamic doc = record.header; if (id == 0 && type == DocType.Transfer && cAmount > 0) { // New transfer in doc.TransferAccountId = acct; doc.DocumentAccountId = 0; doc.DocumentAccountName = ""; } if (string.IsNullOrWhiteSpace(doc.DocumentMemo.ToString())) { // Generate a memo string name = current.Name; string memo = current.Memo; if (string.IsNullOrWhiteSpace(memo)) memo = name; else if (!memo.Contains(name)) memo = name + " " + memo; doc.DocumentMemo = memo; } if (!same && type != DocType.Subscriptions) { // They want to create a new document - try to guess the DocumentName string name = doc.DocumentName; string currentName = current.Name; currentName = currentName.Split('\n', '\t')[0]; if (string.IsNullOrWhiteSpace(name) || (!payment && name.SimilarTo(currentName) < 0.5)) { doc.DocumentName = currentName; doc.DocumentNameAddressId = 0; float maxsimilarity = 0.4999f; foreach (NameAddress n in Database.Query<NameAddress>("SELECT * FROM NameAddress WHERE Type = " + Database.Quote(nameType) + " AND Name <= " + Database.Quote(currentName) + " AND Name LIKE " + Database.Quote(currentName.Length <= 5 ? currentName : currentName.Substring(0, 5) + "%"))) { float similarity = n.Name.SimilarTo(currentName); if (similarity > maxsimilarity) { doc.DocumentName = n.Name; doc.DocumentNameAddressId = n.idNameAddress; maxsimilarity = similarity; } } } } doc.DocumentDate = current.Date; decimal tAmount = doc.DocumentAmount; decimal diff = Math.Abs(cAmount) - Math.Abs(tAmount); doc.DocumentAmount += diff; if(same) Utils.Check(diff == 0, "Amounts must be the same"); else { // New transaction doc.DocumentOutstanding = doc.DocumentAmount; doc.Clr = ""; doc.idDocument = doc.Id = null; if (Utils.ExtractNumber(doc.DocumentIdentifier.ToString()) > 0) doc.DocumentIdentifier = "<next>"; } if(string.IsNullOrEmpty(doc.DocumentIdentifier.ToString())) { if (current.Id != null) { doc.DocumentIdentifier = current.Id; } else { int no = Utils.ExtractNumber(current.Name.ToString()); if (no != 0) doc.DocumentIdentifier = no.ToString(); } } if (diff != 0 && documentHasVat) { // Adjust first line to account for difference if (record.detail.Count == 0) record.detail.Add(new InvoiceLine().ToJToken()); dynamic line = record.detail[0]; decimal val = line.LineAmount + line.VatAmount + diff; if (line.VatRate != 0) { line.VatAmount = Math.Round(val * line.VatRate / (100 + line.VatRate), 2); val -= line.VatAmount; } line.LineAmount = val; } if (payment && !same) removePayments(record); record.StatementAccount = acct; if (same) { // Just post the new information if (type == DocType.Transfer) record = record.header; // Transfer posts header alone AjaxReturn p = StatementMatchSave((JObject)record); if (p.error == null) Redirect(p.redirect); // If no error, go on with matching } } void removePayments(dynamic record) { record.header.Allocated = 0M; record.header.Remaining = (decimal)record.header.DocumentAmount; int l = record.detail.Count; while(l-- > 0) { dynamic line = record.detail[l]; decimal amountPaid = line.AmountPaid; if (amountPaid != 0) { decimal outstanding = line.Outstanding - amountPaid; if (outstanding == 0) record.detail.RemoveAt(l); else line.Outstanding = outstanding; } } } /// <summary> /// Save a matched transaction. /// May be called direct from StatementMatch for Same transactions, /// or when the user presses "Save" for other transactions /// </summary> public AjaxReturn StatementMatchSave(JObject json) { Utils.Check(SessionData.StatementMatch != null, "Invalid call to StatementMatchSave"); MatchInfo match = SessionData.StatementMatch.ToObject<MatchInfo>(); JArray transactions = SessionData.StatementImport.transactions; dynamic transaction = match.transaction < 0 ? null : SessionData.StatementImport.transactions[match.transaction]; DocType type = match.transaction < 0 ? match.type == "Transfer" ? DocType.Transfer : DocType.Withdrawal : (DocType)((JObject)transactions[match.transaction]).AsInt("DocumentTypeId"); AjaxReturn result; switch (type) { case DocType.Payment: result = new Customer() { Context = Context, GetParameters = GetParameters, PostParameters = PostParameters, Parameters = Parameters, }.PaymentSave(json.To<CustomerSupplier.PaymentDocument>()); break; case DocType.BillPayment: result = new Supplier() { Context = Context, GetParameters = GetParameters, PostParameters = PostParameters, Parameters = Parameters, }.PaymentSave(json.To<CustomerSupplier.PaymentDocument>()); break; case DocType.Withdrawal: case DocType.Deposit: case DocType.CreditCardCharge: case DocType.CreditCardCredit: result = DocumentSave(json.To<BankingDocument>()); break; case DocType.Transfer: result = TransferSave(json.To<TransferDocument>()); break; case DocType.Subscriptions: result = new Members() { Context = Context, GetParameters = GetParameters, PostParameters = PostParameters, Parameters = Parameters, }.DocumentSave(json.To<Members.SubscriptionDocument>()); break; default: throw new CheckException("Unexpected document type:{0}", type.UnCamel()); } if (result.error == null) { if(match.transaction >= 0 && match.type == "Same") transaction.Matched = 1; JArray items = SessionData.StatementImport.import; items.RemoveAt(match.current); int acct = SessionData.StatementImport.id; result.redirect = "/banking/" + (items.Count == 0 ? "detail.html?id=" + acct : "statementmatching.html"); } return result; } public class MatchInfo : JsonObject { /// <summary> /// New, Transfer or Same /// </summary> public string type; /// <summary> /// Index of chosen record from statement /// </summary> public int current; /// <summary> /// Index of chosen transaction from matched transactions, or -1 if none /// </summary> public int transaction; } public class BankingDetail : Account { public decimal? Balance; public decimal? CurrentBalance; } public class BankingDocument : JsonObject { public Extended_Document header; public List<InvoiceLine> detail; } public class ReconcileHeader : Account { public decimal OpeningBalance; public decimal ClearedBalance; } public class ReconcileLine : Extended_Document { public int idJournal; public string Cleared; public decimal Amount; } public class ReconcileDocument { public bool Temporary; public ReconcileHeader header; public ReconcileLine[] detail; public bool print; } } public class FullAccount : Account { public string AcctType; public int NextNumber(DocType docType) { switch (docType) { case DocType.Withdrawal: case DocType.CreditCardCharge: return NextChequeNumber; case DocType.Deposit: case DocType.CreditCardCredit: return NextDepositNumber; default: return 0; } } public bool RegisterNumber(DocType docType, int current) { switch (docType) { case DocType.Withdrawal: case DocType.CreditCardCharge: return registerNumber(ref NextChequeNumber, current); case DocType.Deposit: case DocType.CreditCardCredit: return registerNumber(ref NextDepositNumber, current); } return false; } bool registerNumber(ref int next, int current) { if (current >= next) { next = current + 1; return true; } return false; } } }
// * ************************************************************************** // * Copyright (c) McCreary, Veselka, Bragg & Allen, P.C. // * This source code is subject to terms and conditions of the MIT License. // * A copy of the license can be found in the License.txt file // * at the root of this distribution. // * By using this source code in any fashion, you are agreeing to be bound by // * the terms of the MIT License. // * You must not remove this notice from this software. // * ************************************************************************** using FluentAssert; using FluentWebControls.Extensions; using MvbaCore; using NUnit.Framework; namespace FluentWebControls.Tests.Extensions { public class LinkDataExtensionsTest { public abstract class LinkDataExtensionsTestBase { protected LinkData LinkData; [SetUp] public void BeforeEachTest() { LinkData = new LinkData(); } } [TestFixture] public class When_asked_to_Disable : LinkDataExtensionsTestBase { [Test] public void Should_return_a_LinkData_that_is_disabled() { var link = LinkData.DisabledIf(true); Assert.AreSame(LinkData, link); LinkData.ToString().Contains("disabled").ShouldBeTrue(); } } [TestFixture] public class When_asked_to_add_href : LinkDataExtensionsTestBase { [Test] public void Should_return_a_LinkData_with_href() { const string href = "LinkPage"; var link = LinkData.WithUrl(href); Assert.AreSame(LinkData, link); link.ToString().ParseHtmlTag()["href"].ShouldBeEqualTo(href); LinkData.ToString().Contains(href).ShouldBeTrue(); } } [TestFixture] public class When_asked_to_add_queryParameter : LinkDataExtensionsTestBase { private readonly TestData.Item _item = new TestData.Item(1, "ItemName"); [Test] public void Should_return_a_LinkData_With_query_parameter_added_to_the_link_for_a_name_value_input_of_type_string() { var link = LinkData.WithQueryStringData("Name", "Value"); Assert.AreSame(LinkData, link); LinkData.ToString().Contains("Name=Value").ShouldBeTrue(); } [Test] public void Should_return_a_LinkData_With_query_parameter_added_to_the_link_for_an_expression_that_returns_int() { var link = LinkData.WithQueryStringData(() => _item.ItemId); Assert.AreSame(LinkData, link); LinkData.ToString().Contains($"{Reflection.GetPropertyName(() => _item.ItemId)}={_item.ItemId}").ShouldBeTrue(); } [Test] public void Should_return_a_LinkData_With_query_parameter_added_to_the_link_for_an_expression_that_returns_int_and_separate_value_provided() { var link = LinkData.WithQueryStringData(() => _item.ItemId, 10); Assert.AreSame(LinkData, link); LinkData.ToString().Contains($"{Reflection.GetPropertyName(() => _item.ItemId)}=10").ShouldBeTrue(); } [Test] public void Should_return_a_LinkData_With_query_parameter_added_to_the_link_for_an_expression_that_returns_nullable_int() { int? itemId = 5; var link = LinkData.WithQueryStringData(() => itemId); Assert.AreSame(LinkData, link); LinkData.ToString().Contains($"{Reflection.GetPropertyName(() => itemId)}={itemId}").ShouldBeTrue(); } [Test] public void Should_return_a_LinkData_With_query_parameter_added_to_the_link_for_an_expression_that_returns_nullable_int_and_separate_value_provided() { int? itemId = 5; int? newValue = 10; var link = LinkData.WithQueryStringData(() => itemId, newValue); Assert.AreSame(LinkData, link); LinkData.ToString().Contains($"{Reflection.GetPropertyName(() => itemId)}=10").ShouldBeTrue(); } [Test] public void Should_return_a_LinkData_With_query_parameter_added_to_the_link_for_an_expression_that_returns_string() { var link = LinkData.WithQueryStringData(() => _item.ItemName); Assert.AreSame(LinkData, link); LinkData.ToString().Contains($"{Reflection.GetPropertyName(() => _item.ItemName)}={_item.ItemName}").ShouldBeTrue(); } [Test] public void Should_return_a_LinkData_With_query_parameter_added_to_the_link_for_an_expression_that_returns_string_and_separate_value_provided() { var link = LinkData.WithQueryStringData(() => _item.ItemName, "Value"); Assert.AreSame(LinkData, link); LinkData.ToString().Contains($"{Reflection.GetPropertyName(() => _item.ItemName)}=Value").ShouldBeTrue(); } [Test] public void Should_return_a_LinkData_With_query_parameter_added_to_the_link_for_an_object_that_contains_the_specified_property() { var link = LinkData.WithQueryStringData(_item, item => item.ItemId, item => item.ItemId.ToString()); Assert.AreSame(LinkData, link); LinkData.ToString().Contains($"{Reflection.GetPropertyName(() => _item.ItemId)}={_item.ItemId}").ShouldBeTrue(); } } [TestFixture] public class When_asked_to_add_rel : LinkDataExtensionsTestBase { [Test] public void Should_return_a_LinkData_with_rel() { const string rel = "external"; var link = LinkData.WithRel(rel); Assert.AreSame(LinkData, link); link.ToString().ParseHtmlTag()["rel"].ShouldBeEqualTo(rel); LinkData.ToString().Contains(rel).ShouldBeTrue(); } } [TestFixture] public class When_asked_to_assign_CssClass : LinkDataExtensionsTestBase { [Test] public void Should_return_a_LinkData_With_CssClass_initialized() { const string cssClass = "Link"; var link = LinkData.WithCssClass(cssClass); Assert.AreSame(LinkData, link); link.ToString().ParseHtmlTag()["class"].ShouldBeEqualTo(cssClass); LinkData.ToString().Contains(cssClass).ShouldBeTrue(); } } [TestFixture] public class When_asked_to_assign_Image_Url : LinkDataExtensionsTestBase { [Test] public void Should_return_a_LinkData_With_Image_Url_initialized() { const string imageUrl = "ImageUrl"; const string alt = "alt"; const string text = "Text"; var link = LinkData.WithLinkText(text).WithLinkImageUrl(imageUrl, alt); Assert.AreSame(LinkData, link); LinkData.ToString().Contains(imageUrl).ShouldBeTrue(); LinkData.ToString().Contains("<img src='" + imageUrl + "' alt='" + alt + "'/>").ShouldBeTrue(); } [Test] public void Should_return_a_LinkData_Without_Text_initialized() { const string imageUrl = "ImageUrl"; const string alt = "alt"; const string text = "Text"; var link = LinkData.WithLinkImageUrl(imageUrl, alt); Assert.AreSame(LinkData, link); LinkData.ToString().Contains(text).ShouldBeFalse(); } } [TestFixture] public class When_asked_to_assign_MouseOverText : LinkDataExtensionsTestBase { [Test] public void Should_return_a_LinkData_With_MouseOverText_initialized() { const string text = "Text"; var link = LinkData.WithMouseOverText(text); Assert.AreSame(LinkData, link); link.ToString().ParseHtmlTag()["title"].ShouldBeEqualTo(text); LinkData.ToString().Contains(text).ShouldBeTrue(); } } [TestFixture] public class When_asked_to_assign_Text : LinkDataExtensionsTestBase { [Test] public void Should_return_a_LinkData_With_Text_initialized() { const string text = "Text"; var link = LinkData.WithLinkText(text); Assert.AreSame(LinkData, link); LinkData.ToString().Contains(text).ShouldBeTrue(); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace MongoInClustorWithFailover.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
//----------------------------------------------------------------------- // <copyright file="TaskImplHelper.cs" company="Microsoft"> // Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // <summary> // Contains code for the TaskImplHelper.cs class. // </summary> //----------------------------------------------------------------------- namespace Microsoft.WindowsAzure.StorageClient { using System; using System.Diagnostics; using Tasks; using TaskSequence = System.Collections.Generic.IEnumerable<Microsoft.WindowsAzure.StorageClient.Tasks.ITask>; /// <summary> /// Implementation helper for task sequences. /// </summary> internal static class TaskImplHelper { /// <summary> /// Executes the impl. /// </summary> /// <typeparam name="T">The result type.</typeparam> /// <param name="impl">The task implementation.</param> /// <returns>The result of the task.</returns> [DebuggerNonUserCode] internal static T ExecuteImpl<T>(Func<Action<T>, TaskSequence> impl) { CommonUtils.AssertNotNull("impl", impl); var invokerTask = new InvokeTaskSequenceTask<T>(impl); return invokerTask.ExecuteAndWait(); } /// <summary> /// Begins the impl. /// </summary> /// <typeparam name="T">The result type.</typeparam> /// <param name="impl">The task implementation.</param> /// <param name="callback">The callback.</param> /// <param name="state">The state.</param> /// <returns>An asynchronous result representing the operation.</returns> [DebuggerNonUserCode] internal static IAsyncResult BeginImpl<T>(Func<Action<T>, TaskSequence> impl, AsyncCallback callback, object state) { CommonUtils.AssertNotNull("impl", impl); var invokerTask = new InvokeTaskSequenceTask<T>(impl); return invokerTask.ToAsyncResult(callback, state); } /// <summary> /// Ends the impl. /// </summary> /// <typeparam name="T">The result type.</typeparam> /// <param name="asyncResult">The async result.</param> /// <returns>The task result.</returns> [DebuggerNonUserCode] internal static T EndImpl<T>(IAsyncResult asyncResult) { TaskAsyncResult<T> task = GetTaskFromAsyncResult<T>(asyncResult); var result = task.EndInvoke(); task.Dispose(); return result; } /// <summary> /// Executes the impl. /// </summary> /// <param name="impl">The task implemenetaion.</param> [DebuggerNonUserCode] internal static void ExecuteImpl(Func<TaskSequence> impl) { CommonUtils.AssertNotNull("impl", impl); InvokeTaskSequenceTask invokerTask = new InvokeTaskSequenceTask(impl); invokerTask.ExecuteAndWait(); } /// <summary> /// Begins the impl. /// </summary> /// <param name="impl">The task implementation.</param> /// <param name="callback">The callback.</param> /// <param name="state">The state.</param> /// <returns>An asynchronous result representing the operation.</returns> [DebuggerNonUserCode] internal static IAsyncResult BeginImpl(Func<TaskSequence> impl, AsyncCallback callback, object state) { CommonUtils.AssertNotNull("impl", impl); var invokerTask = new InvokeTaskSequenceTask(impl); return invokerTask.ToAsyncResult(callback, state); } /// <summary> /// Ends the impl. /// </summary> /// <param name="asyncResult">The async result.</param> [DebuggerNonUserCode] internal static void EndImpl(IAsyncResult asyncResult) { TaskAsyncResult<NullTaskReturn> task = GetTaskFromAsyncResult<NullTaskReturn>(asyncResult); task.EndInvoke(); task.Dispose(); } /// <summary> /// Executes the impl with retry. /// </summary> /// <typeparam name="T">The result type.</typeparam> /// <param name="impl">The task implementation.</param> /// <param name="policy">The policy.</param> /// <returns>The task result.</returns> [DebuggerNonUserCode] internal static T ExecuteImplWithRetry<T>(Func<Action<T>, TaskSequence> impl, RetryPolicy policy) { CommonUtils.AssertNotNull("impl", impl); CommonUtils.AssertNotNull("policy", policy); var retryableTask = GetRetryableAsyncTask(impl, policy); return retryableTask.ExecuteAndWait(); } /// <summary> /// Begins the impl with retry. /// </summary> /// <typeparam name="T">The result type.</typeparam> /// <param name="impl">The task implementation.</param> /// <param name="policy">The policy.</param> /// <param name="callback">The callback.</param> /// <param name="state">The state.</param> /// <returns>An asynchronous result representing the operation.</returns> [DebuggerNonUserCode] internal static IAsyncResult BeginImplWithRetry<T>(Func<Action<T>, TaskSequence> impl, RetryPolicy policy, AsyncCallback callback, object state) { CommonUtils.AssertNotNull("impl", impl); CommonUtils.AssertNotNull("policy", policy); var retryableTask = GetRetryableAsyncTask(impl, policy); return retryableTask.ToAsyncResult(callback, state); } /// <summary> /// Ends the impl with retry. /// </summary> /// <typeparam name="T">The result type.</typeparam> /// <param name="asyncResult">The async result.</param> /// <returns>The task result.</returns> [DebuggerNonUserCode] internal static T EndImplWithRetry<T>(IAsyncResult asyncResult) { return EndImpl<T>(asyncResult); } /// <summary> /// Executes the impl with retry. /// </summary> /// <param name="impl">The task implementation.</param> /// <param name="policy">The policy.</param> [DebuggerNonUserCode] internal static void ExecuteImplWithRetry(Func<TaskSequence> impl, RetryPolicy policy) { CommonUtils.AssertNotNull("impl", impl); CommonUtils.AssertNotNull("policy", policy); var retryableTask = GetRetryableAsyncTask(impl, policy); retryableTask.ExecuteAndWait(); } /// <summary> /// Executes the impl with retry. /// </summary> /// <typeparam name="TResult">The result type.</typeparam> /// <param name="syncTask">The task implementation.</param> /// <returns>The task result.</returns> [DebuggerNonUserCode] internal static TResult ExecuteSyncTask<TResult>(SynchronousTask<TResult> syncTask) { CommonUtils.AssertNotNull("syncTask", syncTask); return syncTask.Execute(); } /// <summary> /// Executes the impl with retry. /// </summary> /// <typeparam name="TResult">The result type.</typeparam> /// <param name="syncTask">The task implementation.</param> /// <param name="policy">The policy.</param> /// <returns>The task result.</returns> [DebuggerNonUserCode] internal static TResult ExecuteSyncTaskWithRetry<TResult>(SynchronousTask<TResult> syncTask, RetryPolicy policy) { CommonUtils.AssertNotNull("syncTask", syncTask); CommonUtils.AssertNotNull("policy", policy); var oracle = policy(); return RequestWithRetry.RequestWithRetrySyncImpl<TResult>(oracle, syncTask); } /// <summary> /// Begins the impl with retry. /// </summary> /// <param name="impl">The task implementation.</param> /// <param name="policy">The policy.</param> /// <param name="callback">The callback.</param> /// <param name="state">The state.</param> /// <returns>An asynchronous result representing the operation.</returns> [DebuggerNonUserCode] internal static IAsyncResult BeginImplWithRetry(Func<TaskSequence> impl, RetryPolicy policy, AsyncCallback callback, object state) { CommonUtils.AssertNotNull("impl", impl); CommonUtils.AssertNotNull("policy", policy); var retryableTask = GetRetryableAsyncTask(impl, policy); return retryableTask.ToAsyncResult(callback, state); } /// <summary> /// Ends the impl with retry. /// </summary> /// <param name="asyncResult">The async result.</param> [DebuggerNonUserCode] internal static void EndImplWithRetry(IAsyncResult asyncResult) { EndImpl(asyncResult); } /// <summary> /// Gets the retryable async task. /// </summary> /// <typeparam name="T">The result type.</typeparam> /// <param name="impl">The task implementation.</param> /// <param name="policy">The policy.</param> /// <returns>The retryable task.</returns> [DebuggerNonUserCode] internal static Task<T> GetRetryableAsyncTask<T>(Func<Action<T>, TaskSequence> impl, RetryPolicy policy) { CommonUtils.AssertNotNull("impl", impl); CommonUtils.AssertNotNull("policy", policy); ShouldRetry oracle = policy(); InvokeTaskSequenceTask<T> retryableTask = new InvokeTaskSequenceTask<T>( (setResult) => RequestWithRetry.RequestWithRetryImpl<T>(oracle, impl, setResult)); return retryableTask; } /// <summary> /// Gets the retryable async task. /// </summary> /// <param name="impl">The task implementation.</param> /// <param name="policy">The policy.</param> /// <returns>The retryable task.</returns> [DebuggerNonUserCode] internal static Task<NullTaskReturn> GetRetryableAsyncTask(Func<TaskSequence> impl, RetryPolicy policy) { CommonUtils.AssertNotNull("impl", impl); CommonUtils.AssertNotNull("policy", policy); ShouldRetry oracle = policy(); InvokeTaskSequenceTask retryableTask = new InvokeTaskSequenceTask( () => RequestWithRetry.RequestWithRetryImpl<NullTaskReturn>( oracle, (setResult) => impl(), (scratch) => { })); return retryableTask; } /// <summary> /// Gets the task from async result. /// </summary> /// <typeparam name="T">The type of the result.</typeparam> /// <param name="asyncResult">The async result.</param> /// <returns>The asynchronous result.</returns> [DebuggerNonUserCode] private static TaskAsyncResult<T> GetTaskFromAsyncResult<T>(IAsyncResult asyncResult) { CommonUtils.AssertNotNull("asyncResult", asyncResult); var task = asyncResult as TaskAsyncResult<T>; if (task == null) { throw new ArgumentException("invalid asyncresult"); } return task; } } }
using System.Diagnostics; namespace Community.CsharpSqlite { public partial class Sqlite3 { /* ** 2008 June 18 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This module implements the sqlite3_status() interface and related ** functionality. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e ** ************************************************************************* */ //#include "sqliteInt.h" //#include "vdbeInt.h" /* ** Variables in which to record status information. */ //typedef struct sqlite3StatType sqlite3StatType; public class sqlite3StatType { public int[] nowValue = new int[10]; /* Current value */ public int[] mxValue = new int[10]; /* Maximum value */ } public static sqlite3StatType sqlite3Stat = new sqlite3StatType(); /* The "wsdStat" macro will resolve to the status information ** state vector. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdStat can refer directly ** to the "sqlite3Stat" state vector declared above. */ #if SQLITE_OMIT_WSD //# define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat) //# define wsdStat x[0] #else //# define wsdStatInit private static void wsdStatInit() { } //# define wsdStat sqlite3Stat private static sqlite3StatType wsdStat = sqlite3Stat; #endif /* ** Return the current value of a status parameter. */ private static int sqlite3StatusValue(int op) { wsdStatInit(); Debug.Assert(op >= 0 && op < ArraySize(wsdStat.nowValue)); return wsdStat.nowValue[op]; } /* ** Add N to the value of a status record. It is assumed that the ** caller holds appropriate locks. */ private static void sqlite3StatusAdd(int op, int N) { wsdStatInit(); Debug.Assert(op >= 0 && op < ArraySize(wsdStat.nowValue)); wsdStat.nowValue[op] += N; if (wsdStat.nowValue[op] > wsdStat.mxValue[op]) { wsdStat.mxValue[op] = wsdStat.nowValue[op]; } } /* ** Set the value of a status to X. */ private static void sqlite3StatusSet(int op, int X) { wsdStatInit(); Debug.Assert(op >= 0 && op < ArraySize(wsdStat.nowValue)); wsdStat.nowValue[op] = X; if (wsdStat.nowValue[op] > wsdStat.mxValue[op]) { wsdStat.mxValue[op] = wsdStat.nowValue[op]; } } /* ** Query status information. ** ** This implementation assumes that reading or writing an aligned ** 32-bit integer is an atomic operation. If that assumption is not true, ** then this routine is not threadsafe. */ static public int sqlite3_status(int op, ref int pCurrent, ref int pHighwater, int resetFlag) { wsdStatInit(); if (op < 0 || op >= ArraySize(wsdStat.nowValue)) { return SQLITE_MISUSE_BKPT(); } pCurrent = wsdStat.nowValue[op]; pHighwater = wsdStat.mxValue[op]; if (resetFlag != 0) { wsdStat.mxValue[op] = wsdStat.nowValue[op]; } return SQLITE_OK; } /* ** Query status information for a single database connection */ static public int sqlite3_db_status( sqlite3 db, /* The database connection whose status is desired */ int op, /* Status verb */ ref int pCurrent, /* Write current value here */ ref int pHighwater, /* Write high-water mark here */ int resetFlag /* Reset high-water mark if true */ ) { int rc = SQLITE_OK; /* Return code */ sqlite3_mutex_enter(db.mutex); switch (op) { case SQLITE_DBSTATUS_LOOKASIDE_USED: { pCurrent = db.lookaside.nOut; pHighwater = db.lookaside.mxOut; if (resetFlag != 0) { db.lookaside.mxOut = db.lookaside.nOut; } break; } case SQLITE_DBSTATUS_LOOKASIDE_HIT: case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE: case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: { testcase(op == SQLITE_DBSTATUS_LOOKASIDE_HIT); testcase(op == SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE); testcase(op == SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL); Debug.Assert((op - SQLITE_DBSTATUS_LOOKASIDE_HIT) >= 0); Debug.Assert((op - SQLITE_DBSTATUS_LOOKASIDE_HIT) < 3); pCurrent = 0; pHighwater = db.lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT]; if (resetFlag != 0) { db.lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0; } break; } /* ** Return an approximation for the amount of memory currently used ** by all pagers associated with the given database connection. The ** highwater mark is meaningless and is returned as zero. */ case SQLITE_DBSTATUS_CACHE_USED: { int totalUsed = 0; int i; sqlite3BtreeEnterAll(db); for (i = 0; i < db.nDb; i++) { Btree pBt = db.aDb[i].pBt; if (pBt != null) { Pager pPager = sqlite3BtreePager(pBt); totalUsed += sqlite3PagerMemUsed(pPager); } } sqlite3BtreeLeaveAll(db); pCurrent = totalUsed; pHighwater = 0; break; } /* ** *pCurrent gets an accurate estimate of the amount of memory used ** to store the schema for all databases (main, temp, and any ATTACHed ** databases. *pHighwater is set to zero. */ case SQLITE_DBSTATUS_SCHEMA_USED: { int i; /* Used to iterate through schemas */ int nByte = 0; /* Used to accumulate return value */ sqlite3BtreeEnterAll(db); //db.pnBytesFreed = nByte; for (i = 0; i < db.nDb; i++) { Schema pSchema = db.aDb[i].pSchema; if (ALWAYS(pSchema != null)) { HashElem p; //nByte += (int)(sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * ( // pSchema.tblHash.count // + pSchema.trigHash.count // + pSchema.idxHash.count // + pSchema.fkeyHash.count //)); //nByte += (int)sqlite3MallocSize( pSchema.tblHash.ht ); //nByte += (int)sqlite3MallocSize( pSchema.trigHash.ht ); //nByte += (int)sqlite3MallocSize( pSchema.idxHash.ht ); //nByte += (int)sqlite3MallocSize( pSchema.fkeyHash.ht ); for (p = sqliteHashFirst(pSchema.trigHash); p != null; p = sqliteHashNext(p)) { Trigger t = (Trigger)sqliteHashData(p); sqlite3DeleteTrigger(db, ref t); } for (p = sqliteHashFirst(pSchema.tblHash); p != null; p = sqliteHashNext(p)) { Table t = (Table)sqliteHashData(p); sqlite3DeleteTable(db, ref t); } } } db.pnBytesFreed = 0; sqlite3BtreeLeaveAll(db); pHighwater = 0; pCurrent = nByte; break; } /* ** *pCurrent gets an accurate estimate of the amount of memory used ** to store all prepared statements. ** *pHighwater is set to zero. */ case SQLITE_DBSTATUS_STMT_USED: { Vdbe pVdbe; /* Used to iterate through VMs */ int nByte = 0; /* Used to accumulate return value */ //db.pnBytesFreed = nByte; for (pVdbe = db.pVdbe; pVdbe != null; pVdbe = pVdbe.pNext) { sqlite3VdbeDeleteObject(db, ref pVdbe); } db.pnBytesFreed = 0; pHighwater = 0; pCurrent = nByte; break; } default: { rc = SQLITE_ERROR; break; } } sqlite3_mutex_leave(db.mutex); return rc; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq; using Microsoft.Extensions.Configuration; using NetEscapades.Configuration.Tests.Common; using Xunit; namespace NetEscapades.Configuration.Yaml.Tests { public class SequenceTests { [Fact] public void SequencesAreConvertedToKeyValuePairs() { var yaml = @" ip: - '1.2.3.4' - '7.8.9.10' - '11.12.13.14' "; var yamlConfigSource = new YamlConfigurationProvider(new YamlConfigurationSource()); yamlConfigSource.Load(TestStreamHelpers.StringToStream(yaml)); Assert.Equal("1.2.3.4", yamlConfigSource.Get("ip:0")); Assert.Equal("7.8.9.10", yamlConfigSource.Get("ip:1")); Assert.Equal("11.12.13.14", yamlConfigSource.Get("ip:2")); } [Fact] public void SequenceOfObjects() { var yaml = @" ip: - address: '1.2.3.4' hidden: false - address: '5.6.7.8' hidden: true "; var yamlConfigSource = new YamlConfigurationProvider(new YamlConfigurationSource()); yamlConfigSource.Load(TestStreamHelpers.StringToStream(yaml)); Assert.Equal("1.2.3.4", yamlConfigSource.Get("ip:0:address")); Assert.Equal("false", yamlConfigSource.Get("ip:0:hidden")); Assert.Equal("5.6.7.8", yamlConfigSource.Get("ip:1:address")); Assert.Equal("true", yamlConfigSource.Get("ip:1:hidden")); } [Fact] public void NestedSequences() { var yaml = @" 'ip': - - '1.2.3.4' - '5.6.7.8' - - '9.10.11.12' - '13.14.15.16' "; var yamlConfigSource = new YamlConfigurationProvider(new YamlConfigurationSource()); yamlConfigSource.Load(TestStreamHelpers.StringToStream(yaml)); Assert.Equal("1.2.3.4", yamlConfigSource.Get("ip:0:0")); Assert.Equal("5.6.7.8", yamlConfigSource.Get("ip:0:1")); Assert.Equal("9.10.11.12", yamlConfigSource.Get("ip:1:0")); Assert.Equal("13.14.15.16", yamlConfigSource.Get("ip:1:1")); } [Fact] public void ImplicitSequenceItemReplacement() { var yaml1 = @" 'ip': - 1.2.3.4 - '7.8.9.10' - '11.12.13.14' "; var yaml2 = @" 'ip': - '15.16.17.18' "; var yamlConfigSource1 = new YamlConfigurationSource { FileProvider = TestStreamHelpers.StringToFileProvider(yaml1) }; var yamlConfigSource2 = new YamlConfigurationSource { FileProvider = TestStreamHelpers.StringToFileProvider(yaml2) }; var configurationBuilder = new ConfigurationBuilder(); configurationBuilder.Add(yamlConfigSource1); configurationBuilder.Add(yamlConfigSource2); var config = configurationBuilder.Build(); Assert.Equal(3, config.GetSection("ip").GetChildren().Count()); Assert.Equal("15.16.17.18", config["ip:0"]); Assert.Equal("7.8.9.10", config["ip:1"]); Assert.Equal("11.12.13.14", config["ip:2"]); } [Fact] public void ExplicitSequenceReplacement() { var yaml1 = @" 'ip': - 1.2.3.4 - '7.8.9.10' - '11.12.13.14' "; var yaml2 = @" 'ip': 1: '15.16.17.18' "; var yamlConfigSource1 = new YamlConfigurationSource { FileProvider = TestStreamHelpers.StringToFileProvider(yaml1) }; var yamlConfigSource2 = new YamlConfigurationSource { FileProvider = TestStreamHelpers.StringToFileProvider(yaml2) }; var configurationBuilder = new ConfigurationBuilder(); configurationBuilder.Add(yamlConfigSource1); configurationBuilder.Add(yamlConfigSource2); var config = configurationBuilder.Build(); Assert.Equal(3, config.GetSection("ip").GetChildren().Count()); Assert.Equal("1.2.3.4", config["ip:0"]); Assert.Equal("15.16.17.18", config["ip:1"]); Assert.Equal("11.12.13.14", config["ip:2"]); } [Fact] public void SequenceMerge() { var yaml1 = @" 'ip': - 1.2.3.4 - '7.8.9.10' - '11.12.13.14' "; var yaml2 = @" 'ip': 3: '15.16.17.18' "; var yamlConfigSource1 = new YamlConfigurationSource { FileProvider = TestStreamHelpers.StringToFileProvider(yaml1) }; var yamlConfigSource2 = new YamlConfigurationSource { FileProvider = TestStreamHelpers.StringToFileProvider(yaml2) }; var configurationBuilder = new ConfigurationBuilder(); configurationBuilder.Add(yamlConfigSource1); configurationBuilder.Add(yamlConfigSource2); var config = configurationBuilder.Build(); Assert.Equal(4, config.GetSection("ip").GetChildren().Count()); Assert.Equal("1.2.3.4", config["ip:0"]); Assert.Equal("7.8.9.10", config["ip:1"]); Assert.Equal("11.12.13.14", config["ip:2"]); Assert.Equal("15.16.17.18", config["ip:3"]); } [Fact] public void SequencesAreKeptInFileOrder() { var yaml = @" setting: - 'b' - 'a' - '2' "; var yamlConfigSource = new YamlConfigurationSource { FileProvider = TestStreamHelpers.StringToFileProvider(yaml) }; var configurationBuilder = new ConfigurationBuilder(); configurationBuilder.Add(yamlConfigSource); var config = configurationBuilder.Build(); var configurationSection = config.GetSection("setting"); var indexConfigurationSections = configurationSection.GetChildren().ToArray(); Assert.Equal(3, indexConfigurationSections.Count()); Assert.Equal("b", indexConfigurationSections[0].Value); Assert.Equal("a", indexConfigurationSections[1].Value); Assert.Equal("2", indexConfigurationSections[2].Value); } [Fact] public void PropertiesAreSortedByNumberOnlyFirst() { var yaml = @" setting: 'hello': 'a' 'bob': 'b' '42': 'c' '4': 'd' '10': 'e' '1text': 'f' "; var yamlConfigSource = new YamlConfigurationSource { FileProvider = TestStreamHelpers.StringToFileProvider(yaml) }; var configurationBuilder = new ConfigurationBuilder(); configurationBuilder.Add(yamlConfigSource); var config = configurationBuilder.Build(); var configurationSection = config.GetSection("setting"); var indexConfigurationSections = configurationSection.GetChildren().ToArray(); Assert.Equal(6, indexConfigurationSections.Count()); Assert.Equal("4", indexConfigurationSections[0].Key); Assert.Equal("10", indexConfigurationSections[1].Key); Assert.Equal("42", indexConfigurationSections[2].Key); Assert.Equal("1text", indexConfigurationSections[3].Key); Assert.Equal("bob", indexConfigurationSections[4].Key); Assert.Equal("hello", indexConfigurationSections[5].Key); } [Fact] public void FilesWithByteOrderMarkerAreParsedCorrectly() { var yaml = "setting1: '1'\nsetting2: '2'"; var yamlConfigSource = new YamlConfigurationProvider(new YamlConfigurationSource()); yamlConfigSource.Load(TestStreamHelpers.StringToStream(yaml, withBom: true)); Assert.Equal("1", yamlConfigSource.Get("setting1")); Assert.Equal("2", yamlConfigSource.Get("setting2")); } } }
// 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.Linq; using System.Reflection; using Gallio.Common.Reflection; using MbUnit.Framework; using MbUnit.Framework.ContractVerifiers; namespace Gallio.Tests.Common.Reflection { [TestFixture] [TestsOn(typeof(CodeReference))] public class CodeReferenceTest { private Assembly assembly; private string @namespace; private Type type; private MethodInfo member; private ParameterInfo parameter; [SetUp] public void SetUp() { type = typeof(CodeReferenceTest); assembly = type.Assembly; @namespace = type.Namespace; member = type.GetMethod("Dummy", BindingFlags.Instance | BindingFlags.NonPublic); parameter = member.GetParameters()[0]; } [VerifyContract] public readonly IContract HashCodeAcceptanceTests = new HashCodeAcceptanceContract<CodeReference> { CollisionProbabilityLimit = CollisionProbability.VeryLow, UniformDistributionQuality = UniformDistributionQuality.Excellent, DistinctInstances = DataGenerators.Join( DataGenerators.Random.Strings(10, @"[A-Za-z0-9]{5,30}"), DataGenerators.Random.Strings(10, @"[A-Za-z0-9]{5,30}"), DataGenerators.Random.Strings(10, @"[A-Za-z0-9]{5,30}"), DataGenerators.Random.Strings(10, @"[A-Za-z0-9]{5,30}"), DataGenerators.Random.Strings(10, @"[A-Za-z0-9]{5,30}")) .Select(x => new CodeReference((string)x[0], (string)x[1], (string)x[2], (string)x[3], (string)x[4])) }; [Test] public void Unknown_IsDefinedAsAllNulls() { Assert.IsNull(CodeReference.Unknown.AssemblyName); Assert.IsNull(CodeReference.Unknown.NamespaceName); Assert.IsNull(CodeReference.Unknown.TypeName); Assert.IsNull(CodeReference.Unknown.MemberName); Assert.IsNull(CodeReference.Unknown.ParameterName); Assert.AreEqual(CodeReferenceKind.Unknown, CodeReference.Unknown.Kind); } [Test] public void CreateByNameAndResolve() { var r = new CodeReference(assembly.FullName, type.Namespace, type.FullName, member.Name, parameter.Name); Assert.AreEqual(assembly.FullName, r.AssemblyName); Assert.AreEqual(type.Namespace, r.NamespaceName); Assert.AreEqual(type.FullName, r.TypeName); Assert.AreEqual(member.Name, r.MemberName); Assert.AreEqual(parameter.Name, r.ParameterName); Assert.AreEqual(CodeReferenceKind.Parameter, r.Kind); } [Test] public void CreateFromAssembly() { var r = CodeReference.CreateFromAssembly(assembly); Assert.AreEqual(assembly.FullName, r.AssemblyName); Assert.IsNull(r.NamespaceName); Assert.IsNull(r.TypeName); Assert.IsNull(r.MemberName); Assert.IsNull(r.ParameterName); Assert.AreEqual(CodeReferenceKind.Assembly, r.Kind); } [Test, ExpectedException(typeof(ArgumentNullException))] public void CreateFromAssembly_ThrowsIfNull() { CodeReference.CreateFromAssembly(null); } [Test] public void CreateFromNamespace() { CodeReference r = CodeReference.CreateFromNamespace(@namespace); Assert.IsNull(r.AssemblyName); Assert.AreEqual(@namespace, r.NamespaceName); Assert.IsNull(r.TypeName); Assert.IsNull(r.MemberName); Assert.IsNull(r.ParameterName); Assert.AreEqual(CodeReferenceKind.Namespace, r.Kind); } [Test, ExpectedException(typeof(ArgumentNullException))] public void CreateFromNamespace_ThrowsIfNull() { CodeReference.CreateFromNamespace(null); } [Test] public void CreateFromType() { var r = CodeReference.CreateFromType(type); Assert.AreEqual(assembly.FullName, r.AssemblyName); Assert.AreEqual(@namespace, r.NamespaceName); Assert.AreEqual(type.FullName, r.TypeName); Assert.IsNull(r.MemberName); Assert.IsNull(r.ParameterName); Assert.AreEqual(CodeReferenceKind.Type, r.Kind); } [Test, ExpectedException(typeof(ArgumentNullException))] public void CreateFromType_ThrowsIfNull() { CodeReference.CreateFromType(null); } [Test] public void CreateFromMember() { var r = CodeReference.CreateFromMember(member); Assert.AreEqual(assembly.FullName, r.AssemblyName); Assert.AreEqual(@namespace, r.NamespaceName); Assert.AreEqual(type.FullName, r.TypeName); Assert.AreEqual(member.Name, r.MemberName); Assert.IsNull(r.ParameterName); Assert.AreEqual(CodeReferenceKind.Member, r.Kind); } [Test, ExpectedException(typeof(ArgumentNullException))] public void CreateFromMember_ThrowsIfNull() { CodeReference.CreateFromMember(null); } [Test] public void CreateFromParameter() { var r = CodeReference.CreateFromParameter(parameter); Assert.AreEqual(assembly.FullName, r.AssemblyName); Assert.AreEqual(@namespace, r.NamespaceName); Assert.AreEqual(type.FullName, r.TypeName); Assert.AreEqual(member.Name, r.MemberName); Assert.AreEqual(parameter.Name, r.ParameterName); Assert.AreEqual(CodeReferenceKind.Parameter, r.Kind); } [Test, ExpectedException(typeof(ArgumentNullException))] public void CreateFromParameter_ThrowsIfNull() { CodeReference.CreateFromParameter(null); } [Test] public void Equality() { Assert.IsFalse(CodeReference.Unknown.Equals(null)); Assert.IsFalse(CodeReference.Unknown.Equals(CodeReference.CreateFromParameter(parameter))); Assert.IsFalse(CodeReference.Unknown == CodeReference.CreateFromParameter(parameter)); Assert.IsTrue(CodeReference.Unknown != CodeReference.CreateFromParameter(parameter)); Assert.IsTrue(CodeReference.CreateFromParameter(parameter).Equals(CodeReference.CreateFromParameter(parameter))); Assert.IsTrue(CodeReference.CreateFromParameter(parameter) == CodeReference.CreateFromParameter(parameter)); Assert.IsFalse(CodeReference.CreateFromParameter(parameter) != CodeReference.CreateFromParameter(parameter)); } [Test] public void GetHashCode_SeemsSane() { Assert.AreNotEqual(CodeReference.CreateFromParameter(parameter).GetHashCode(), CodeReference.Unknown.GetHashCode()); } [Test] public void TypeIsXmlSerializable() { Assert.IsXmlSerializableType(typeof(CodeReference)); } [Test] public void RoundTripXmlSerializationFullyPopulatedProperties() { var value = CodeReference.CreateFromParameter(parameter); Assert.AreEqual(value, Assert.XmlSerializeThenDeserialize(value)); } [Test] public void RoundTripXmlSerializationUnknown() { var value = CodeReference.Unknown; Assert.AreEqual(value, Assert.XmlSerializeThenDeserialize(value)); } internal void Dummy(object dummy) { } } }
#region License // Copyright 2014 MorseCode Software // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace MorseCode.RxMvvm.Observable.Property.Internal { using System; using System.Diagnostics.Contracts; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Runtime.Serialization; using System.Security.Permissions; using System.Threading.Tasks; using MorseCode.RxMvvm.Common; using MorseCode.RxMvvm.Common.DiscriminatedUnion; [Serializable] internal class CancellableAsyncCalculatedPropertyWithContext<TContext, TFirst, TSecond, TThird, T> : CalculatedPropertyBase<T>, ISerializable { private readonly TContext context; private readonly IObservable<TFirst> firstProperty; private readonly IObservable<TSecond> secondProperty; private readonly IObservable<TThird> thirdProperty; private readonly TimeSpan throttleTime; private readonly Func<AsyncCalculationHelper, TContext, TFirst, TSecond, TThird, Task<T>> calculateValue; private readonly bool isLongRunningCalculation; private IDisposable scheduledTask; internal CancellableAsyncCalculatedPropertyWithContext( TContext context, IObservable<TFirst> firstProperty, IObservable<TSecond> secondProperty, IObservable<TThird> thirdProperty, TimeSpan throttleTime, Func<AsyncCalculationHelper, TContext, TFirst, TSecond, TThird, Task<T>> calculateValue, bool isLongRunningCalculation) { Contract.Requires<ArgumentNullException>(firstProperty != null, "firstProperty"); Contract.Requires<ArgumentNullException>(secondProperty != null, "secondProperty"); Contract.Requires<ArgumentNullException>(thirdProperty != null, "thirdProperty"); Contract.Requires<ArgumentNullException>(calculateValue != null, "calculateValue"); Contract.Ensures(this.firstProperty != null); Contract.Ensures(this.secondProperty != null); Contract.Ensures(this.thirdProperty != null); Contract.Ensures(this.calculateValue != null); RxMvvmConfiguration.EnsureSerializableDelegateIfUsingSerialization(calculateValue); this.context = context; this.firstProperty = firstProperty; this.secondProperty = secondProperty; this.thirdProperty = thirdProperty; this.throttleTime = throttleTime; this.calculateValue = calculateValue; this.isLongRunningCalculation = isLongRunningCalculation; Func<AsyncCalculationHelper, TFirst, TSecond, TThird, Task<IDiscriminatedUnion<object, T, Exception>>> calculate = async (helper, first, second, third) => { IDiscriminatedUnion<object, T, Exception> discriminatedUnion; try { discriminatedUnion = DiscriminatedUnion.First<object, T, Exception>( await calculateValue(helper, context, first, second, third).ConfigureAwait(true)); } catch (Exception e) { discriminatedUnion = DiscriminatedUnion.Second<object, T, Exception>(e); } return discriminatedUnion; }; this.SetHelper(new CalculatedPropertyHelper( (resultSubject, isCalculatingSubject) => { CompositeDisposable d = new CompositeDisposable(); IScheduler scheduler = isLongRunningCalculation ? RxMvvmConfiguration.GetLongRunningCalculationScheduler() : RxMvvmConfiguration.GetCalculationScheduler(); IObservable<Tuple<TFirst, TSecond, TThird>> o = firstProperty.CombineLatest( secondProperty, thirdProperty, Tuple.Create); o = throttleTime > TimeSpan.Zero ? o.Throttle(throttleTime, scheduler) : o.ObserveOn(scheduler); d.Add( o.Subscribe( v => { using (this.scheduledTask) { } isCalculatingSubject.OnNext(true); this.scheduledTask = scheduler.ScheduleAsync( async (s, t) => { try { await s.Yield().ConfigureAwait(true); IDiscriminatedUnion<object, T, Exception> result = await calculate( new AsyncCalculationHelper(s, t), v.Item1, v.Item2, v.Item3).ConfigureAwait(true); await s.Yield().ConfigureAwait(true); resultSubject.OnNext(result); } catch (OperationCanceledException) { } catch (Exception e) { resultSubject.OnNext( DiscriminatedUnion.Second<object, T, Exception>(e)); } isCalculatingSubject.OnNext(false); }); })); return d; })); } /// <summary> /// Initializes a new instance of the <see cref="CancellableAsyncCalculatedPropertyWithContext{TContext,TFirst,TSecond,TThird,T}"/> class from serialized data. /// </summary> /// <param name="info"> /// The serialization info. /// </param> /// <param name="context"> /// The serialization context. /// </param> [ContractVerification(false)] // ReSharper disable UnusedParameter.Local protected CancellableAsyncCalculatedPropertyWithContext(SerializationInfo info, StreamingContext context) // ReSharper restore UnusedParameter.Local : this( (TContext)(info.GetValue("c", typeof(TContext)) ?? default(TContext)), (IObservable<TFirst>)info.GetValue("p1", typeof(IObservable<TFirst>)), (IObservable<TSecond>)info.GetValue("p2", typeof(IObservable<TSecond>)), (IObservable<TThird>)info.GetValue("p3", typeof(IObservable<TThird>)), (TimeSpan)(info.GetValue("t", typeof(TimeSpan)) ?? default(TimeSpan)), (Func<AsyncCalculationHelper, TContext, TFirst, TSecond, TThird, Task<T>>)info.GetValue("f", typeof(Func<AsyncCalculationHelper, TContext, TFirst, TSecond, TThird, Task<T>>)), (bool)info.GetValue("l", typeof(bool))) { } /// <summary> /// Gets the object data to serialize. /// </summary> /// <param name="info"> /// The serialization info. /// </param> /// <param name="streamingContext"> /// The serialization context. /// </param> [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public virtual void GetObjectData(SerializationInfo info, StreamingContext streamingContext) { info.AddValue("c", this.context); info.AddValue("p1", this.firstProperty); info.AddValue("p2", this.secondProperty); info.AddValue("p3", this.thirdProperty); info.AddValue("t", this.throttleTime); info.AddValue("f", this.calculateValue); info.AddValue("l", this.isLongRunningCalculation); } /// <summary> /// Disposes of the property. /// </summary> protected override void Dispose() { base.Dispose(); using (this.scheduledTask) { } } [ContractInvariantMethod] private void CodeContractsInvariants() { Contract.Invariant(this.firstProperty != null); Contract.Invariant(this.secondProperty != null); Contract.Invariant(this.thirdProperty != null); Contract.Invariant(this.calculateValue != null); } } }
using System; using System.Xml; using System.Xml.Serialization; using System.Collections.Generic; using System.IO; using System.Net; namespace Moscrif.IDE.Iface.Entities { [XmlRoot("banners")] public class Banners { public Banners() { Items = new List<Banner>(); IsCache = false; } [XmlElement("banner")] public List<Banner> Items {get;set;} [XmlIgnore] public bool IsCache {get;set;} [XmlIgnore] public string CacheFilePath { get{ return System.IO.Path.Combine(MainClass.Paths.BannerCache,"banners.xml"); } } public static Banners LoadBanners(string data){ try { XmlSerializer serializer = new XmlSerializer(typeof(Banners));//,xRoot); Banners banners= (Banners)serializer.Deserialize((new StringReader(data) )); return banners; }catch(Exception ex){ Moscrif.IDE.Tool.Logger.Error(ex.Message); Console.WriteLine(ex.Message); return new Banners(); } } public static Banners OpenBannerCache(){ string bannerCachePath = System.IO.Path.Combine(MainClass.Paths.BannerCache,"banners.xml"); if (File.Exists(bannerCachePath)){ using (FileStream fs = File.OpenRead(bannerCachePath)) { XmlSerializer serializer = new XmlSerializer(typeof(Banners)); Banners banners= (Banners)serializer.Deserialize(fs); banners.IsCache = true; return banners; } } return new Banners(); } public void SaveBannerCache(){ try{ XmlSerializer x_serial = new XmlSerializer(typeof(Banners)); using (XmlWriter wr = XmlWriter.Create( this.CacheFilePath )) { x_serial.Serialize( wr, this ); } /*StringWriter textWriter = new StringWriter(); x_serial.Serialize(textWriter, this); return textWriter.ToString();*/ }catch(Exception ex){ Tool.Logger.Error(ex.Message); } } } public class Banner { public Banner() { } private Gdk.Pixbuf bannerPixbuf; [XmlElement("name")] public string Name ; [XmlElement("description")] public string Description; [XmlElement("url")] public string Url; [XmlElement("image")] public string Image; [XmlIgnore] public string CacheFilePath{ get{ return System.IO.Path.Combine(MainClass.Paths.BannerCache,CacheFileName); } } [XmlIgnore] public string CacheFileName{ get{ //MainClass.Tools.GetMd5Sum return Moscrif.IDE.Tool.Cryptographer.MD5Hash(Image)+".png"; } } public void Load(){ try{ LoadFromUrl(); SaveCache(); } catch (Exception ex){ Console.WriteLine(ex.Message); LoadFromCache(); } } public void LoadFromCache(){ if(File.Exists(CacheFilePath)) this.BannerPixbuf =new Gdk.Pixbuf(CacheFilePath); else this.BannerPixbuf = null; } public void LoadFromUrl(){ using (WebClientTimeout client = new WebClientTimeout(5000)) { byte[] imageBuffer = client.DownloadData(this.Image); this.BannerPixbuf =new Gdk.Pixbuf(imageBuffer);//imageBuffer); } } public void SaveCache(){ try{ if(File.Exists(CacheFilePath)){ File.Delete(CacheFilePath); } if(BannerPixbuf!= null){ BannerPixbuf.Save(CacheFilePath,"png"); } }catch(Exception ex){ Tool.Logger.Error(ex.Message); } } [XmlIgnore] public Gdk.Pixbuf BannerPixbuf{ get{ return bannerPixbuf; } set { /**/ bannerPixbuf = value; } } [XmlIgnore] public Gdk.Pixbuf BannerPixbufResized200{ get{ Gdk.Pixbuf bannerPixbufResize = bannerPixbuf.Copy(); if(bannerPixbufResize.Width>200 || bannerPixbufResize.Height>40){ int newWidth = 200; int newHeight = 40; MainClass.Tools.RecalculateImageSize(bannerPixbufResize.Width,bannerPixbufResize.Height ,200,40,ref newWidth,ref newHeight); bannerPixbufResize = bannerPixbufResize.ScaleSimple(newWidth,newHeight, Gdk.InterpType.Bilinear); } return bannerPixbufResize; } } [XmlIgnore] public Gdk.Pixbuf BannerPixbufResized400{ get{ Gdk.Pixbuf bannerPixbufResize = bannerPixbuf.Copy(); if(bannerPixbufResize.Width>400 || bannerPixbufResize.Height>120){ int newWidth = 400; int newHeight = 120; MainClass.Tools.RecalculateImageSize(bannerPixbufResize.Width,bannerPixbufResize.Height ,400,120,ref newWidth,ref newHeight); bannerPixbufResize = bannerPixbufResize.ScaleSimple(newWidth,newHeight, Gdk.InterpType.Bilinear); } return bannerPixbufResize; } } } }
// PendingBuffer.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. namespace ICSharpCode.SharpZipLib.Zip.Compression { /// <summary> /// This class is general purpose class for writing data to a buffer. /// /// It allows you to write bits as well as bytes /// Based on DeflaterPending.java /// /// author of the original java version : Jochen Hoenicke /// </summary> public class PendingBuffer { #region Instance Fields /// <summary> /// Internal work buffer /// </summary> byte[] buffer_; int start; int end; uint bits; int bitCount; #endregion #region Constructors /// <summary> /// construct instance using default buffer size of 4096 /// </summary> public PendingBuffer() : this( 4096 ) { } /// <summary> /// construct instance using specified buffer size /// </summary> /// <param name="bufferSize"> /// size to use for internal buffer /// </param> public PendingBuffer(int bufferSize) { buffer_ = new byte[bufferSize]; } #endregion /// <summary> /// Clear internal state/buffers /// </summary> public void Reset() { start = end = bitCount = 0; } /// <summary> /// Write a byte to buffer /// </summary> /// <param name="value"> /// The value to write /// </param> public void WriteByte(int value) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif buffer_[end++] = unchecked((byte) value); } /// <summary> /// Write a short value to buffer LSB first /// </summary> /// <param name="value"> /// The value to write. /// </param> public void WriteShort(int value) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif buffer_[end++] = unchecked((byte) value); buffer_[end++] = unchecked((byte) (value >> 8)); } /// <summary> /// write an integer LSB first /// </summary> /// <param name="value">The value to write.</param> public void WriteInt(int value) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif buffer_[end++] = unchecked((byte) value); buffer_[end++] = unchecked((byte) (value >> 8)); buffer_[end++] = unchecked((byte) (value >> 16)); buffer_[end++] = unchecked((byte) (value >> 24)); } /// <summary> /// Write a block of data to buffer /// </summary> /// <param name="block">data to write</param> /// <param name="offset">offset of first byte to write</param> /// <param name="length">number of bytes to write</param> public void WriteBlock(byte[] block, int offset, int length) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif System.Array.Copy(block, offset, buffer_, end, length); end += length; } /// <summary> /// The number of bits written to the buffer /// </summary> public int BitCount { get { return bitCount; } } /// <summary> /// Align internal buffer on a byte boundary /// </summary> public void AlignToByte() { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif if (bitCount > 0) { buffer_[end++] = unchecked((byte) bits); if (bitCount > 8) { buffer_[end++] = unchecked((byte) (bits >> 8)); } } bits = 0; bitCount = 0; } /// <summary> /// Write bits to internal buffer /// </summary> /// <param name="b">source of bits</param> /// <param name="count">number of bits to write</param> public void WriteBits(int b, int count) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("writeBits("+b+","+count+")"); // } #endif bits |= (uint)(b << bitCount); bitCount += count; if (bitCount >= 16) { buffer_[end++] = unchecked((byte) bits); buffer_[end++] = unchecked((byte) (bits >> 8)); bits >>= 16; bitCount -= 16; } } /// <summary> /// Write a short value to internal buffer most significant byte first /// </summary> /// <param name="s">value to write</param> public void WriteShortMSB(int s) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif buffer_[end++] = unchecked((byte) (s >> 8)); buffer_[end++] = unchecked((byte) s); } /// <summary> /// Indicates if buffer has been flushed /// </summary> public bool IsFlushed { get { return end == 0; } } /// <summary> /// Flushes the pending buffer into the given output array. If the /// output array is to small, only a partial flush is done. /// </summary> /// <param name="output">The output array.</param> /// <param name="offset">The offset into output array.</param> /// <param name="length">The maximum number of bytes to store.</param> /// <returns>The number of bytes flushed.</returns> public int Flush(byte[] output, int offset, int length) { if (bitCount >= 8) { buffer_[end++] = unchecked((byte) bits); bits >>= 8; bitCount -= 8; } if (length > end - start) { length = end - start; System.Array.Copy(buffer_, start, output, offset, length); start = 0; end = 0; } else { System.Array.Copy(buffer_, start, output, offset, length); start += length; } return length; } /// <summary> /// Convert internal buffer to byte array. /// Buffer is empty on completion /// </summary> /// <returns> /// The internal buffer contents converted to a byte array. /// </returns> public byte[] ToByteArray() { byte[] result = new byte[end - start]; System.Array.Copy(buffer_, start, result, 0, result.Length); start = 0; end = 0; return result; } } }
// 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.Net.Http; using System.Threading; using System.Threading.Tasks; namespace System.Net { public class HttpWebRequest : WebRequest { private const int DefaultContinueTimeout = 350; // Current default value from .NET Desktop. private WebHeaderCollection _webHeaderCollection = new WebHeaderCollection(); private Uri _requestUri; private string _originVerb = HttpMethod.Get.Method; // We allow getting and setting this (to preserve app-compat). But we don't do anything with it // as the underlying System.Net.Http API doesn't support it. private int _continueTimeout = DefaultContinueTimeout; private bool _allowReadStreamBuffering = false; private CookieContainer _cookieContainer = null; private ICredentials _credentials = null; private IWebProxy _proxy = WebRequest.DefaultWebProxy; private Task<HttpResponseMessage> _sendRequestTask; private int _beginGetRequestStreamCalled = 0; private int _beginGetResponseCalled = 0; private int _endGetRequestStreamCalled = 0; private int _endGetResponseCalled = 0; private RequestStream _requestStream; private TaskCompletionSource<Stream> _requestStreamOperation = null; private TaskCompletionSource<WebResponse> _responseOperation = null; private AsyncCallback _requestStreamCallback = null; private AsyncCallback _responseCallback = null; private int _abortCalled = 0; private CancellationTokenSource _sendRequestCts; internal HttpWebRequest(Uri uri) { _requestUri = uri; } private void SetSpecialHeaders(string HeaderName, string value) { _webHeaderCollection.Remove(HeaderName); if (!string.IsNullOrEmpty(value)) { _webHeaderCollection[HeaderName] = value; } } public string Accept { get { return _webHeaderCollection[HttpKnownHeaderNames.Accept]; } set { SetSpecialHeaders(HttpKnownHeaderNames.Accept, value); } } public virtual bool AllowReadStreamBuffering { get { return _allowReadStreamBuffering; } set { _allowReadStreamBuffering = value; } } public override String ContentType { get { return _webHeaderCollection[HttpKnownHeaderNames.ContentType]; } set { SetSpecialHeaders(HttpKnownHeaderNames.ContentType, value); } } public int ContinueTimeout { get { return _continueTimeout; } set { if (RequestSubmitted) { throw new InvalidOperationException(SR.net_reqsubmitted); } if ((value < 0) && (value != System.Threading.Timeout.Infinite)) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero); } _continueTimeout = value; } } public virtual CookieContainer CookieContainer { get { return _cookieContainer; } set { _cookieContainer = value; } } public override ICredentials Credentials { get { return _credentials; } set { _credentials = value; } } public virtual bool HaveResponse { get { return (_sendRequestTask != null) && (_sendRequestTask.Status == TaskStatus.RanToCompletion); } } public override WebHeaderCollection Headers { get { return _webHeaderCollection; } set { // We can't change headers after they've already been sent. if (RequestSubmitted) { throw new InvalidOperationException(SR.net_reqsubmitted); } WebHeaderCollection webHeaders = value; WebHeaderCollection newWebHeaders = new WebHeaderCollection(); // Copy And Validate - // Handle the case where their object tries to change // name, value pairs after they call set, so therefore, // we need to clone their headers. foreach (String headerName in webHeaders.AllKeys) { newWebHeaders[headerName] = webHeaders[headerName]; } _webHeaderCollection = newWebHeaders; } } public override string Method { get { return _originVerb; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException(SR.net_badmethod, nameof(value)); } if (HttpValidationHelpers.IsInvalidMethodOrHeaderString(value)) { throw new ArgumentException(SR.net_badmethod, nameof(value)); } _originVerb = value; } } public override Uri RequestUri { get { return _requestUri; } } public virtual bool SupportsCookieContainer { get { return true; } } public override bool UseDefaultCredentials { get { return (_credentials == CredentialCache.DefaultCredentials); } set { if (RequestSubmitted) { throw new InvalidOperationException(SR.net_writestarted); } // Match Desktop behavior. Changing this property will also // change the .Credentials property as well. _credentials = value ? CredentialCache.DefaultCredentials : null; } } public override IWebProxy Proxy { get { return _proxy; } set { // We can't change the proxy while the request is already fired. if (RequestSubmitted) { throw new InvalidOperationException(SR.net_reqsubmitted); } _proxy = value; } } public override void Abort() { if (Interlocked.Exchange(ref _abortCalled, 1) != 0) { return; } // .NET Desktop behavior requires us to invoke outstanding callbacks // before returning if used in either the BeginGetRequestStream or // BeginGetResponse methods. // // If we can transition the task to the canceled state, then we invoke // the callback. If we can't transition the task, it is because it is // already in the terminal state and the callback has already been invoked // via the async task continuation. if (_responseOperation != null) { if (_responseOperation.TrySetCanceled() && _responseCallback != null) { _responseCallback(_responseOperation.Task); } // Cancel the underlying send operation. Debug.Assert(_sendRequestCts != null); _sendRequestCts.Cancel(); } else if (_requestStreamOperation != null) { if (_requestStreamOperation.TrySetCanceled() && _requestStreamCallback != null) { _requestStreamCallback(_requestStreamOperation.Task); } } } private Task<Stream> GetRequestStream() { CheckAbort(); if (RequestSubmitted) { throw new InvalidOperationException(SR.net_reqsubmitted); } // Match Desktop behavior: prevent someone from getting a request stream // if the protocol verb/method doesn't support it. Note that this is not // entirely compliant RFC2616 for the aforementioned compatibility reasons. if (string.Equals(HttpMethod.Get.Method, _originVerb, StringComparison.OrdinalIgnoreCase) || string.Equals(HttpMethod.Head.Method, _originVerb, StringComparison.OrdinalIgnoreCase) || string.Equals("CONNECT", _originVerb, StringComparison.OrdinalIgnoreCase)) { throw new ProtocolViolationException(SR.net_nouploadonget); } _requestStream = new RequestStream(); return Task.FromResult((Stream)_requestStream); } public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, Object state) { CheckAbort(); if (Interlocked.Exchange(ref _beginGetRequestStreamCalled, 1) != 0) { throw new InvalidOperationException(SR.net_repcall); } _requestStreamCallback = callback; _requestStreamOperation = GetRequestStream().ToApm(callback, state); return _requestStreamOperation.Task; } public override Stream EndGetRequestStream(IAsyncResult asyncResult) { CheckAbort(); if (asyncResult == null || !(asyncResult is Task<Stream>)) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } if (Interlocked.Exchange(ref _endGetRequestStreamCalled, 1) != 0) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetRequestStream")); } Stream stream; try { stream = ((Task<Stream>)asyncResult).GetAwaiter().GetResult(); } catch (Exception ex) { throw WebException.CreateCompatibleException(ex); } return stream; } private async Task<WebResponse> SendRequest() { if (RequestSubmitted) { throw new InvalidOperationException(SR.net_reqsubmitted); } var handler = new HttpClientHandler(); var client = new HttpClient(handler); var request = new HttpRequestMessage(new HttpMethod(_originVerb), _requestUri); if (_requestStream != null) { ArraySegment<byte> bytes = _requestStream.GetBuffer(); request.Content = new ByteArrayContent(bytes.Array, bytes.Offset, bytes.Count); } // Set to match original defaults of HttpWebRequest. // HttpClientHandler.AutomaticDecompression defaults to true; set it to false to match the desktop behavior handler.AutomaticDecompression = DecompressionMethods.None; handler.Credentials = _credentials; if (_cookieContainer != null) { handler.CookieContainer = _cookieContainer; Debug.Assert(handler.UseCookies); // Default of handler.UseCookies is true. } else { handler.UseCookies = false; } Debug.Assert(handler.UseProxy); // Default of handler.UseProxy is true. Debug.Assert(handler.Proxy == null); // Default of handler.Proxy is null. if (_proxy == null) { handler.UseProxy = false; } else { handler.Proxy = _proxy; } // Copy the HttpWebRequest request headers from the WebHeaderCollection into HttpRequestMessage.Headers and // HttpRequestMessage.Content.Headers. foreach (string headerName in _webHeaderCollection) { // The System.Net.Http APIs require HttpRequestMessage headers to be properly divided between the request headers // collection and the request content headers collection for all well-known header names. And custom headers // are only allowed in the request headers collection and not in the request content headers collection. if (IsWellKnownContentHeader(headerName)) { if (request.Content == null) { // Create empty content so that we can send the entity-body header. request.Content = new ByteArrayContent(Array.Empty<byte>()); } request.Content.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName]); } else { request.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName]); } } _sendRequestTask = client.SendAsync( request, _allowReadStreamBuffering ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead, _sendRequestCts.Token); HttpResponseMessage responseMessage = await _sendRequestTask.ConfigureAwait(false); HttpWebResponse response = new HttpWebResponse(responseMessage, _requestUri, _cookieContainer); if (!responseMessage.IsSuccessStatusCode) { throw new WebException( SR.Format(SR.net_servererror, (int)response.StatusCode, response.StatusDescription), null, WebExceptionStatus.ProtocolError, response); } return response; } public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state) { CheckAbort(); if (Interlocked.Exchange(ref _beginGetResponseCalled, 1) != 0) { throw new InvalidOperationException(SR.net_repcall); } _sendRequestCts = new CancellationTokenSource(); _responseCallback = callback; _responseOperation = SendRequest().ToApm(callback, state); return _responseOperation.Task; } public override WebResponse EndGetResponse(IAsyncResult asyncResult) { CheckAbort(); if (asyncResult == null || !(asyncResult is Task<WebResponse>)) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } if (Interlocked.Exchange(ref _endGetResponseCalled, 1) != 0) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetResponse")); } WebResponse response; try { response = ((Task<WebResponse>)asyncResult).GetAwaiter().GetResult(); } catch (Exception ex) { throw WebException.CreateCompatibleException(ex); } return response; } private bool RequestSubmitted { get { return _sendRequestTask != null; } } private void CheckAbort() { if (Volatile.Read(ref _abortCalled) == 1) { throw new WebException(SR.net_reqaborted, WebExceptionStatus.RequestCanceled); } } private readonly static string[] s_wellKnownContentHeaders = { HttpKnownHeaderNames.ContentDisposition, HttpKnownHeaderNames.ContentEncoding, HttpKnownHeaderNames.ContentLanguage, HttpKnownHeaderNames.ContentLength, HttpKnownHeaderNames.ContentLocation, HttpKnownHeaderNames.ContentMD5, HttpKnownHeaderNames.ContentRange, HttpKnownHeaderNames.ContentType, HttpKnownHeaderNames.Expires, HttpKnownHeaderNames.LastModified }; private bool IsWellKnownContentHeader(string header) { foreach (string contentHeaderName in s_wellKnownContentHeaders) { if (string.Equals(header, contentHeaderName, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } } }
using System; using System.Text; using System.Collections; using System.Reflection; namespace Zeus.DotNetScript { /// <summary> /// Summary description for DotNetScriptEngine. /// </summary> public class DotNetScriptEngine : IZeusScriptingEngine { protected DotNetScriptCodeParser _dotNetScriptCodeParser = null; protected DotNetScriptExecutioner _dotNetScriptExecutioner = null; internal const string DLLREF = "DLLREF"; internal const string USE_NAMESPACE = "USE"; protected string[] _supportedLanguages = new string[] { ZeusConstants.Languages.JSCRIPTNET, ZeusConstants.Languages.JSHARP, ZeusConstants.Languages.CSHARP, ZeusConstants.Languages.VBNET }; public DotNetScriptEngine() {} public string EngineName { get { return ZeusConstants.Engines.DOT_NET_SCRIPT; } } public IZeusCodeParser CodeParser { get { if (_dotNetScriptCodeParser == null) { _dotNetScriptCodeParser = new DotNetScriptCodeParser(this); } return _dotNetScriptCodeParser; } } public IZeusExecutioner Executioner { get { if (_dotNetScriptExecutioner == null) { _dotNetScriptExecutioner = new DotNetScriptExecutioner(this); } return _dotNetScriptExecutioner; } } public string[] SupportedLanguages { get { return _supportedLanguages; } } public bool IsSupportedLanguage(string language) { foreach (string lang in _supportedLanguages) { if (lang == language) return true; } return false; } public bool Execute(ZeusInput input, ZeusOutput output, string code) { return false; } #region Build extending Referece list classes internal ArrayList BuildDLLNames() { ArrayList list = new ArrayList(); foreach (ZeusScriptableObject scriptingObj in ZeusFactory.ScriptableObjects) { if (scriptingObj.DllReference != null) { if(!list.Contains(scriptingObj.DllReference)) list.Add(scriptingObj.DllReference); } } return list; } internal string BuildImportStatments(string language, ArrayList references) { StringBuilder builder = new StringBuilder(); foreach (string ns in references) { if (language == ZeusConstants.Languages.CSHARP) { builder.Append("using "); builder.Append(ns); builder.Append(";\r\n"); } else if (language == ZeusConstants.Languages.VBNET) { builder.Append("Imports "); builder.Append(ns); builder.Append("\r\n"); } } return builder.ToString(); } internal string BuildGuiClass(string language) { StringBuilder builder = new StringBuilder(); if (language == ZeusConstants.Languages.CSHARP) { builder.Append("//-- Class DotNetScriptGui Generated by Zeus\r\n"); builder.Append("namespace Zeus.DotNetScript\r\n"); builder.Append("{\r\n"); builder.Append("\tpublic abstract class DotNetScriptGui : _DotNetScriptGui\r\n"); builder.Append("\t{\r\n"); foreach (ZeusScriptableObject scriptingObj in ZeusFactory.ScriptableObjects) { builder.Append("\t\tprotected "); builder.Append(scriptingObj.ClassPath); builder.Append(" "); builder.Append(scriptingObj.VariableName); builder.Append(";\r\n"); } builder.Append("\t\tpublic DotNetScriptGui(ZeusGuiContext context) : base(context)\r\n"); builder.Append("\t\t{\r\n");; foreach (ZeusScriptableObject scriptingObj in ZeusFactory.ScriptableObjects) { builder.Append("\t\t\tthis."); builder.Append(scriptingObj.VariableName); builder.Append(" = context.Objects[\""); builder.Append(scriptingObj.VariableName); builder.Append("\"] as "); builder.Append(scriptingObj.ClassPath); builder.Append(";\r\n"); } builder.Append("\t\t}\r\n\t}\r\n}\r\n"); } else if (language == ZeusConstants.Languages.VBNET) { builder.Append("'-- Class DotNetScriptGui Generated by Zeus\r\n"); builder.Append("Public MustInherit Class DotNetScriptGui\r\n"); builder.Append("\t\tInherits _DotNetScriptGui\r\n"); foreach (ZeusScriptableObject scriptingObj in ZeusFactory.ScriptableObjects) { builder.Append("\tProtected "); builder.Append(scriptingObj.VariableName); builder.Append(" As "); builder.Append(scriptingObj.ClassPath); builder.Append("\r\n"); } builder.Append("\tPublic Sub New(context As ZeusGuiContext)\r\n"); builder.Append("\t\tMyBase.New(context)\r\n"); foreach (ZeusScriptableObject scriptingObj in ZeusFactory.ScriptableObjects) { builder.Append("\t\tMe."); builder.Append(scriptingObj.VariableName); builder.Append(" = CType(context.Objects.Item(\""); builder.Append(scriptingObj.VariableName); builder.Append("\"), "); builder.Append(scriptingObj.ClassPath); builder.Append(")\r\n"); } builder.Append("\tEnd Sub\r\nEnd Class\r\n"); } return builder.ToString(); } internal string BuildBodyClass(string language) { StringBuilder builder = new StringBuilder(); if (language == ZeusConstants.Languages.CSHARP) { builder.Append("//-- Class DotNetScriptTemplate Generated by Zeus\r\n"); builder.Append("namespace Zeus.DotNetScript\r\n"); builder.Append("{\r\n"); builder.Append("\tpublic abstract class DotNetScriptTemplate : _DotNetScriptTemplate\r\n"); builder.Append("\t{\r\n"); foreach (ZeusScriptableObject scriptingObj in ZeusFactory.ScriptableObjects) { builder.Append("\t\tprotected "); builder.Append(scriptingObj.ClassPath); builder.Append(" "); builder.Append(scriptingObj.VariableName); builder.Append(";\r\n"); } builder.Append("\t\tpublic DotNetScriptTemplate(ZeusTemplateContext context) : base(context)\r\n"); builder.Append("\t\t{\r\n"); foreach (ZeusScriptableObject scriptingObj in ZeusFactory.ScriptableObjects) { builder.Append("\t\t\tthis."); builder.Append(scriptingObj.VariableName); builder.Append(" = context.Objects[\""); builder.Append(scriptingObj.VariableName); builder.Append("\"] as "); builder.Append(scriptingObj.ClassPath); builder.Append(";\r\n"); } builder.Append("\t\t}\r\n\t}\r\n}\r\n"); } else if (language == ZeusConstants.Languages.VBNET) { builder.Append("'-- Class DotNetScriptTemplate Generated by Zeus\r\n"); builder.Append("Public MustInherit Class DotNetScriptTemplate\r\n"); builder.Append("\t\tInherits _DotNetScriptTemplate\r\n"); foreach (ZeusScriptableObject scriptingObj in ZeusFactory.ScriptableObjects) { builder.Append("\tProtected "); builder.Append(scriptingObj.VariableName); builder.Append(" As "); builder.Append(scriptingObj.ClassPath); builder.Append("\r\n"); } builder.Append("\tPublic Sub New(context As ZeusTemplateContext)\r\n"); builder.Append("\t\tMyBase.New(context)\r\n"); foreach (ZeusScriptableObject scriptingObj in ZeusFactory.ScriptableObjects) { builder.Append("\t\tMe."); builder.Append(scriptingObj.VariableName); builder.Append(" = CType(context.Objects.Item(\""); builder.Append(scriptingObj.VariableName); builder.Append("\"), "); builder.Append(scriptingObj.ClassPath); builder.Append(")\r\n"); } builder.Append("\tEnd Sub\r\nEnd Class\r\n"); } return builder.ToString(); } #endregion #region Default text for a new template public string GetNewTemplateText(string language) { StringBuilder builder = new StringBuilder(); if (language == ZeusConstants.Languages.VBNET) { //Set the Body Text builder.Append("<%\r\n"); builder.Append("Public Class GeneratedTemplate\r\n"); builder.Append("\t\t\tInherits DotNetScriptTemplate\r\n"); builder.Append("\r\n"); builder.Append("\tPublic Sub New(context As ZeusTemplateContext)\r\n"); builder.Append("\t\tMyBase.New(context)\r\n"); builder.Append("\tEnd Sub\r\n"); builder.Append("\r\n"); builder.Append("\tPublic Overrides Sub Render\r\n"); builder.Append("%>\r\n"); builder.Append("Literal content goes here.\r\n"); builder.Append("<%\r\n"); builder.Append("\tEnd Sub\r\n"); builder.Append("\r\n"); builder.Append("End Class\r\n"); builder.Append("%>"); } else if (language == ZeusConstants.Languages.CSHARP) { //Set the Body Text builder.Append("<%\r\n"); builder.Append("public class GeneratedTemplate : DotNetScriptTemplate\r\n"); builder.Append("{\r\n"); builder.Append("\tpublic GeneratedTemplate(ZeusTemplateContext context) : base(context) {}\r\n"); builder.Append("\r\n"); builder.Append("\tpublic override void Render()\r\n"); builder.Append("\t{\r\n"); builder.Append("%>\r\n"); builder.Append("Literal content goes here.\r\n"); builder.Append("<%\r\n"); builder.Append("\t}\r\n"); builder.Append("\r\n"); builder.Append("}\r\n"); builder.Append("%>"); } return builder.ToString(); } public string GetNewGuiText(string language) { StringBuilder builder = new StringBuilder(); if (language == ZeusConstants.Languages.VBNET) { //Set the Interface Text builder.Append("\r\n"); builder.Append("Public Class GeneratedGui\r\n"); builder.Append("\t\t\tInherits DotNetScriptGui\r\n"); builder.Append("\r\n"); builder.Append("\tPublic Sub New(context As ZeusGuiContext)\r\n"); builder.Append("\t\tMyBase.New(context)\r\n"); builder.Append("\tEnd Sub\r\n"); builder.Append("\r\n"); builder.Append("\tPublic Overrides Sub Setup\r\n"); builder.Append("\tEnd Sub\r\n"); builder.Append("\r\n"); builder.Append("End Class"); } else if (language == ZeusConstants.Languages.CSHARP) { //Set the Interface Text builder.Append("\r\n"); builder.Append("public class GeneratedGui : DotNetScriptGui\r\n"); builder.Append("{\r\n"); builder.Append("\tpublic GeneratedGui(ZeusGuiContext context) : base(context) {}\r\n"); builder.Append("\r\n"); builder.Append("\tpublic override void Setup()\r\n"); builder.Append("\t{\r\n"); builder.Append("\t}\r\n"); builder.Append("\r\n"); builder.Append("}"); } return builder.ToString(); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace VerifyInsurance.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; // //Module : AANEARPARABOLIC.CPP //Purpose: Implementation for the algorithms for a Near parabolic orbit //Created: PJN / 21-11-2006 //History: None // //Copyright (c) 2006 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) // //All rights reserved. // //Copyright / Usage Details: // //You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) //when your product is released in binary form. You are allowed to modify the source code in any way you want //except you cannot modify the copyright details at the top of each module. If you want to distribute source //code with your application, then you are only allowed to distribute versions released by the author. This is //to maintain a single distribution point for the source code. // // ////////////////////////////// Includes /////////////////////////////////////// /////////////////////// Includes ////////////////////////////////////////////// /////////////////////// Classes /////////////////////////////////////////////// public class CAANearParabolicObjectElements { //Constructors / Destructors public CAANearParabolicObjectElements() { q = 0; i = 0; w = 0; omega = 0; JDEquinox = 0; T = 0; e = 1.0; } //Member variables public double q; public double i; public double w; public double omega; public double JDEquinox; public double T; public double e; } public class CAANearParabolicObjectDetails { //Constructors / Destructors public CAANearParabolicObjectDetails() { HeliocentricEclipticLongitude = 0; HeliocentricEclipticLatitude = 0; TrueGeocentricRA = 0; TrueGeocentricDeclination = 0; TrueGeocentricDistance = 0; TrueGeocentricLightTime = 0; AstrometricGeocenticRA = 0; AstrometricGeocentricDeclination = 0; AstrometricGeocentricDistance = 0; AstrometricGeocentricLightTime = 0; Elongation = 0; PhaseAngle = 0; } //Member variables public CAA3DCoordinate HeliocentricRectangularEquatorial = new CAA3DCoordinate(); public CAA3DCoordinate HeliocentricRectangularEcliptical = new CAA3DCoordinate(); public double HeliocentricEclipticLongitude; public double HeliocentricEclipticLatitude; public double TrueGeocentricRA; public double TrueGeocentricDeclination; public double TrueGeocentricDistance; public double TrueGeocentricLightTime; public double AstrometricGeocenticRA; public double AstrometricGeocentricDeclination; public double AstrometricGeocentricDistance; public double AstrometricGeocentricLightTime; public double Elongation; public double PhaseAngle; } public class CAANearParabolic { //Static methods public static CAANearParabolicObjectDetails Calculate(double JD, CAANearParabolicObjectElements elements) { double Epsilon = CAANutation.MeanObliquityOfEcliptic(elements.JDEquinox); double JD0 = JD; //What will be the return value CAANearParabolicObjectDetails details = new CAANearParabolicObjectDetails(); Epsilon = CAACoordinateTransformation.DegreesToRadians(Epsilon); double omega = CAACoordinateTransformation.DegreesToRadians(elements.omega); double w = CAACoordinateTransformation.DegreesToRadians(elements.w); double i = CAACoordinateTransformation.DegreesToRadians(elements.i); double sinEpsilon = Math.Sin(Epsilon); double cosEpsilon = Math.Cos(Epsilon); double sinOmega = Math.Sin(omega); double cosOmega = Math.Cos(omega); double cosi = Math.Cos(i); double sini = Math.Sin(i); double F = cosOmega; double G = sinOmega * cosEpsilon; double H = sinOmega * sinEpsilon; double P = -sinOmega * cosi; double Q = cosOmega *cosi *cosEpsilon - sini *sinEpsilon; double R = cosOmega *cosi *sinEpsilon + sini *cosEpsilon; double a = Math.Sqrt(F *F + P *P); double b = Math.Sqrt(G *G + Q *Q); double c = Math.Sqrt(H *H + R *R); double A = Math.Atan2(F, P); double B = Math.Atan2(G, Q); double C = Math.Atan2(H, R); CAA3DCoordinate SunCoord = CAASun.EquatorialRectangularCoordinatesAnyEquinox(JD, elements.JDEquinox); for (int j =0; j<2; j++) { double v=0; double r=0; CalulateTrueAnnomalyAndRadius(JD0, elements, ref v, ref r); double x = r * a * Math.Sin(A + w + v); double y = r * b * Math.Sin(B + w + v); double z = r * c * Math.Sin(C + w + v); if (j == 0) { details.HeliocentricRectangularEquatorial.X = x; details.HeliocentricRectangularEquatorial.Y = y; details.HeliocentricRectangularEquatorial.Z = z; //Calculate the heliocentric ecliptic coordinates also double u = omega + v; double cosu = Math.Cos(u); double sinu = Math.Sin(u); details.HeliocentricRectangularEcliptical.X = r * (cosOmega *cosu - sinOmega *sinu *cosi); details.HeliocentricRectangularEcliptical.Y = r * (sinOmega *cosu + cosOmega *sinu *cosi); details.HeliocentricRectangularEcliptical.Z = r *sini *sinu; details.HeliocentricEclipticLongitude = Math.Atan2(y, x); details.HeliocentricEclipticLongitude = CAACoordinateTransformation.MapTo0To24Range(CAACoordinateTransformation.RadiansToDegrees(details.HeliocentricEclipticLongitude) / 15); details.HeliocentricEclipticLatitude = Math.Asin(z / r); details.HeliocentricEclipticLatitude = CAACoordinateTransformation.RadiansToDegrees(details.HeliocentricEclipticLatitude); } double psi = SunCoord.X + x; double nu = SunCoord.Y + y; double sigma = SunCoord.Z + z; double Alpha = Math.Atan2(nu, psi); Alpha = CAACoordinateTransformation.RadiansToDegrees(Alpha); double Delta = Math.Atan2(sigma, Math.Sqrt(psi *psi + nu *nu)); Delta = CAACoordinateTransformation.RadiansToDegrees(Delta); double Distance = Math.Sqrt(psi *psi + nu *nu + sigma *sigma); if (j == 0) { details.TrueGeocentricRA = CAACoordinateTransformation.MapTo0To24Range(Alpha / 15); details.TrueGeocentricDeclination = Delta; details.TrueGeocentricDistance = Distance; details.TrueGeocentricLightTime = CAAElliptical.DistanceToLightTime(Distance); } else { details.AstrometricGeocenticRA = CAACoordinateTransformation.MapTo0To24Range(Alpha / 15); details.AstrometricGeocentricDeclination = Delta; details.AstrometricGeocentricDistance = Distance; details.AstrometricGeocentricLightTime = CAAElliptical.DistanceToLightTime(Distance); double RES = Math.Sqrt(SunCoord.X *SunCoord.X + SunCoord.Y *SunCoord.Y + SunCoord.Z *SunCoord.Z); details.Elongation = CAACoordinateTransformation.RadiansToDegrees(Math.Acos((RES *RES + Distance *Distance - r *r) / (2 * RES * Distance))); details.PhaseAngle = CAACoordinateTransformation.RadiansToDegrees(Math.Acos((r *r + Distance *Distance - RES *RES) / (2 * r * Distance))); } if (j == 0) //Prepare for the next loop around JD0 = JD - details.TrueGeocentricLightTime; } return details; } ////////////////////////////// Implementation ///////////////////////////////// public static double cbrt(double x) { return Math.Pow(x, 1.0/3); } public static void CalulateTrueAnnomalyAndRadius(double JD, CAANearParabolicObjectElements elements, ref double v, ref double r) { double k = 0.01720209895; double a = 0.75 * (JD - elements.T) * k * Math.Sqrt((1 + elements.e) / (elements.q *elements.q *elements.q)); double b = Math.Sqrt(1 + a *a); double W = cbrt(b + a) - cbrt(b - a); double W2 = W *W; double W4 = W2 *W2; double f = (1 - elements.e) / (1 + elements.e); double a1 = (2.0/3) + (0.4) * W2; double a2 = (7.0/5) + (33.0/35) * W2 + (37.0/175) * W4; double a3 = W2 * ((432.0/175) + (956.0/1125) * W2 + (84.0/1575) * W4); double C = W2 / (1 + W2); double g = f * C * C; double w = W * (1 + f *C * (a1 + a2 *g + a3 *g *g)); double w2 = w *w; v = 2 * Math.Atan(w); r = elements.q * (1 + w2) / (1 + w2 * f); } }
// 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 Xunit; namespace System.Collections.Tests { /// <summary> /// Contains tests that ensure the correctness of the LinkedList class. /// </summary> public abstract partial class LinkedList_Generic_Tests<T> : ICollection_Generic_Tests<T> { [Fact] public void AddLast_T_Tests() { int arraySize = 16; int seed = 21543; T[] tempItems, headItems, tailItems; headItems = new T[16]; tailItems = new T[16]; for (int i = 0; i < 16; i++) { headItems[i] = CreateT(seed++); tailItems[i] = CreateT(seed++); } //[] Verify value is default(T) LinkedList<T> linkedList = new LinkedList<T>(); linkedList.AddLast(default(T)); InitialItems_Tests(linkedList, new T[] { default(T) }); //[] Call AddTail(T) several times linkedList.Clear(); for (int i = 0; i < arraySize; ++i) linkedList.AddLast(tailItems[i]); InitialItems_Tests(linkedList, tailItems); //[] Call AddTail(T) several times remove some of the items linkedList = new LinkedList<T>(); for (int i = 0; i < arraySize; ++i) linkedList.AddLast(tailItems[i]); linkedList.Remove(tailItems[2]); linkedList.Remove(tailItems[tailItems.Length - 3]); linkedList.Remove(tailItems[1]); linkedList.Remove(tailItems[tailItems.Length - 2]); linkedList.RemoveFirst(); linkedList.RemoveLast(); //With the above remove we should have removed the first and last 3 items tempItems = new T[tailItems.Length - 6]; Array.Copy(tailItems, 3, tempItems, 0, tailItems.Length - 6); InitialItems_Tests(linkedList, tempItems); //[] adding some more items to the tail of the linked list. for (int i = 0; i < arraySize; ++i) linkedList.AddLast(headItems[i]); T[] tempItems2 = new T[tempItems.Length + headItems.Length]; Array.Copy(tempItems, 0, tempItems2, 0, tempItems.Length); Array.Copy(headItems, 0, tempItems2, tempItems.Length, headItems.Length); InitialItems_Tests(linkedList, tempItems2); //[] Call AddTail(T) several times then call Clear linkedList = new LinkedList<T>(); for (int i = 0; i < arraySize; ++i) linkedList.AddLast(tailItems[i]); linkedList.Clear(); for (int i = 0; i < arraySize; ++i) linkedList.AddLast(headItems[i]); InitialItems_Tests(linkedList, headItems); //[] Mix AddTail and AddTail calls linkedList = new LinkedList<T>(); for (int i = 0; i < arraySize; ++i) { linkedList.AddFirst(headItems[i]); linkedList.AddLast(tailItems[i]); } tempItems = new T[headItems.Length]; // adding the headItems in reverse order. for (int i = 0; i < headItems.Length; i++) { int index = (headItems.Length - 1) - i; tempItems[i] = headItems[index]; } tempItems2 = new T[tempItems.Length + tailItems.Length]; Array.Copy(tempItems, 0, tempItems2, 0, tempItems.Length); Array.Copy(tailItems, 0, tempItems2, tempItems.Length, tailItems.Length); InitialItems_Tests(linkedList, tempItems2); } [Fact] public void AddLast_LinkedListNode() { LinkedList<T> linkedList = new LinkedList<T>(); int arraySize = 16; int seed = 21543; T[] tempItems, headItems, headItemsReverse, tailItems; headItems = new T[arraySize]; tailItems = new T[arraySize]; headItemsReverse = new T[arraySize]; for (int i = 0; i < arraySize; i++) { int index = (arraySize - 1) - i; T head = CreateT(seed++); T tail = CreateT(seed++); headItems[i] = head; headItemsReverse[index] = head; tailItems[i] = tail; } //[] Verify value is default(T) linkedList = new LinkedList<T>(); linkedList.AddLast(new LinkedListNode<T>(default(T))); InitialItems_Tests(linkedList, new T[] { default(T) }); //[] Call AddTail(LinkedListNode<T>) several times linkedList = new LinkedList<T>(); for (int i = 0; i < arraySize; ++i) linkedList.AddLast(new LinkedListNode<T>(tailItems[i])); InitialItems_Tests(linkedList, tailItems); //[] Call AddTail(LinkedListNode<T>) several times remove some of the items linkedList = new LinkedList<T>(); for (int i = 0; i < arraySize; ++i) linkedList.AddLast(new LinkedListNode<T>(tailItems[i])); linkedList.Remove(tailItems[2]); linkedList.Remove(tailItems[tailItems.Length - 3]); linkedList.Remove(tailItems[1]); linkedList.Remove(tailItems[tailItems.Length - 2]); linkedList.RemoveFirst(); linkedList.RemoveLast(); //With the above remove we should have removed the first and last 3 items tempItems = new T[tailItems.Length - 6]; Array.Copy(tailItems, 3, tempItems, 0, tailItems.Length - 6); InitialItems_Tests(linkedList, tempItems); for (int i = 0; i < arraySize; ++i) linkedList.AddLast(new LinkedListNode<T>(headItems[i])); T[] tempItems2 = new T[tempItems.Length + headItems.Length]; Array.Copy(tempItems, 0, tempItems2, 0, tempItems.Length); Array.Copy(headItems, 0, tempItems2, tempItems.Length, headItems.Length); InitialItems_Tests(linkedList, tempItems2); //[] Call AddTail(T) several times then call Clear linkedList = new LinkedList<T>(); for (int i = 0; i < arraySize; ++i) linkedList.AddLast(new LinkedListNode<T>(tailItems[i])); linkedList.Clear(); for (int i = 0; i < arraySize; ++i) linkedList.AddLast(new LinkedListNode<T>(headItems[i])); InitialItems_Tests(linkedList, headItems); //[] Mix AddTail and AddTail calls linkedList = new LinkedList<T>(); for (int i = 0; i < arraySize; ++i) { linkedList.AddFirst(new LinkedListNode<T>(headItems[i])); linkedList.AddLast(new LinkedListNode<T>(tailItems[i])); } tempItems = new T[headItemsReverse.Length + tailItems.Length]; Array.Copy(headItemsReverse, 0, tempItems, 0, headItemsReverse.Length); Array.Copy(tailItems, 0, tempItems, headItemsReverse.Length, tailItems.Length); InitialItems_Tests(linkedList, tempItems); } [Fact] public void AddLast_LinkedListNode_Negative() { LinkedList<T> linkedList = new LinkedList<T>(); LinkedList<T> tempLinkedList = new LinkedList<T>(); int seed = 21543; T[] items; //[] Verify Null node Assert.Throws<ArgumentNullException>(() => linkedList.AddLast(null)); //"Err_858ahia Expected null node to throws ArgumentNullException" InitialItems_Tests(linkedList, new T[0]); //[] Verify Node that already exists in this collection that is the Head linkedList = new LinkedList<T>(); items = new T[] { CreateT(seed++) }; linkedList.AddLast(items[0]); Assert.Throws<InvalidOperationException>(() => linkedList.AddLast(linkedList.First)); //"Err_0568ajods Expected Node that already exists in this collection that is the Head throws InvalidOperationException\n" InitialItems_Tests(linkedList, items); //[] Verify Node that already exists in this collection that is the Tail linkedList = new LinkedList<T>(); items = new T[] { CreateT(seed++), CreateT(seed++) }; linkedList.AddLast(items[0]); linkedList.AddLast(items[1]); Assert.Throws<InvalidOperationException>(() => linkedList.AddLast(linkedList.Last)); //"Err_98809ahied Expected Node that already exists in this collection that is the Tail throws InvalidOperationException\n" InitialItems_Tests(linkedList, items); //[] Verify Node that already exists in another collection linkedList = new LinkedList<T>(); items = new T[] { CreateT(seed++), CreateT(seed++) }; linkedList.AddLast(items[0]); linkedList.AddLast(items[1]); tempLinkedList.Clear(); tempLinkedList.AddLast(CreateT(seed++)); tempLinkedList.AddLast(CreateT(seed++)); Assert.Throws<InvalidOperationException>(() => linkedList.AddLast(tempLinkedList.Last)); //"Err_98809ahied Node that already exists in another collection throws InvalidOperationException\n" InitialItems_Tests(linkedList, items); } } }
using UnityEngine; using System; using System.Collections; public class CubemanController : MonoBehaviour { public bool MoveVertically = false; public bool MirroredMovement = false; //public GameObject debugText; public GameObject Hip_Center; public GameObject Spine; public GameObject Shoulder_Center; public GameObject Head; public GameObject Shoulder_Left; public GameObject Elbow_Left; public GameObject Wrist_Left; public GameObject Hand_Left; public GameObject Shoulder_Right; public GameObject Elbow_Right; public GameObject Wrist_Right; public GameObject Hand_Right; public GameObject Hip_Left; public GameObject Knee_Left; public GameObject Ankle_Left; public GameObject Foot_Left; public GameObject Hip_Right; public GameObject Knee_Right; public GameObject Ankle_Right; public GameObject Foot_Right; public LineRenderer SkeletonLine; private GameObject[] bones; private LineRenderer[] lines; private int[] parIdxs; private Vector3 initialPosition; private Quaternion initialRotation; private Vector3 initialPosOffset = Vector3.zero; private ulong initialPosUserID = 0; void Start () { //store bones in a list for easier access bones = new GameObject[] { Hip_Center, Spine, Shoulder_Center, Head, // 0 - 3 Shoulder_Left, Elbow_Left, Wrist_Left, Hand_Left, // 4 - 7 Shoulder_Right, Elbow_Right, Wrist_Right, Hand_Right, // 8 - 11 Hip_Left, Knee_Left, Ankle_Left, Foot_Left, // 12 - 15 Hip_Right, Knee_Right, Ankle_Right, Foot_Right // 16 - 19 }; parIdxs = new int[] { 0, 0, 1, 2, 2, 4, 5, 6, 2, 8, 9, 10, 0, 12, 13, 14, 0, 16, 17, 18 }; // array holding the skeleton lines lines = new LineRenderer[bones.Length]; if(SkeletonLine) { for(int i = 0; i < lines.Length; i++) { lines[i] = Instantiate(SkeletonLine) as LineRenderer; lines[i].transform.parent = transform; } } initialPosition = transform.position; initialRotation = transform.rotation; //transform.rotation = Quaternion.identity; } // Update is called once per frame void Update () { KinectManager manager = KinectManager.Instance; // get 1st player ulong playerID = manager != null ? manager.GetPlayer1ID() : 0; if(playerID <= 0) { // reset the pointman position and rotation if(transform.position != initialPosition) { transform.position = initialPosition; } if(transform.rotation != initialRotation) { transform.rotation = initialRotation; } for(int i = 0; i < bones.Length; i++) { bones[i].gameObject.SetActive(true); bones[i].transform.localPosition = Vector3.zero; bones[i].transform.localRotation = Quaternion.identity; if(SkeletonLine) { lines[i].gameObject.SetActive(false); } } return; } // set the user position in space Vector3 posPointMan = manager.GetUserPosition(playerID); posPointMan.z = !MirroredMovement ? -posPointMan.z : posPointMan.z; // store the initial position if(initialPosUserID != playerID) { initialPosUserID = playerID; initialPosOffset = transform.position - (MoveVertically ? posPointMan : new Vector3(posPointMan.x, 0, posPointMan.z)); } transform.position = initialPosOffset + (MoveVertically ? posPointMan : new Vector3(posPointMan.x, 0, posPointMan.z)); // update the local positions of the bones for(int i = 0; i < bones.Length; i++) { if(bones[i] != null) { int joint = MirroredMovement ? RemoteKinectWrapper.GetSkeletonMirroredJoint(i): i; if(manager.IsJointTracked(playerID, joint)) { bones[i].gameObject.SetActive(true); Vector3 posJoint = manager.GetJointPosition(playerID, joint); posJoint.z = !MirroredMovement ? -posJoint.z : posJoint.z; Quaternion rotJoint = manager.GetJointOrientation(playerID, joint, !MirroredMovement); rotJoint = initialRotation * rotJoint; posJoint -= posPointMan; if(MirroredMovement) { posJoint.x = -posJoint.x; posJoint.z = -posJoint.z; } bones[i].transform.localPosition = posJoint; bones[i].transform.rotation = rotJoint; } else { bones[i].gameObject.SetActive(false); } } } if(SkeletonLine) { for(int i = 0; i < bones.Length; i++) { bool bLineDrawn = false; if(bones[i] != null) { if(bones[i].gameObject.activeSelf) { Vector3 posJoint = bones[i].transform.position; int parI = parIdxs[i]; Vector3 posParent = bones[parI].transform.position; if(bones[parI].gameObject.activeSelf) { lines[i].gameObject.SetActive(true); //lines[i].SetVertexCount(2); lines[i].SetPosition(0, posParent); lines[i].SetPosition(1, posJoint); bLineDrawn = true; } } } if(!bLineDrawn) { lines[i].gameObject.SetActive(false); } } } } }
using System; using System.Collections.Generic; using System.Data; using System.Reflection; using System.Runtime.CompilerServices; using Microsoft.VisualStudio.TestTools.UnitTesting; using NQuery.Runtime; namespace NQuery.Tests { [TestClass] public class BinderTests { private Query _query; private Expression<object> _expression; #region Custom Types public struct MyInt { private int _value; public MyInt(int value) { _value = value; } public int Value { get { return _value; } set { _value = value; } } public static implicit operator MyInt(int value) { return new MyInt(value); } public static explicit operator MyInt(MyLong myLong) { return new MyInt((int) myLong.Value); } public static bool operator ==(MyInt value1, MyInt value2) { return value1.Value == value2.Value; } public static bool operator !=(MyInt value1, MyInt value2) { return value1.Value != value2.Value; } public override int GetHashCode() { return _value; } public override bool Equals(object obj) { if (!(obj is MyInt)) return false; MyInt myInt = (MyInt) obj; if (_value != myInt._value) return false; return true; } } public class MyLong { private long _value; public MyLong(long value) { _value = value; } public long Value { get { return _value; } set { _value = value; } } public static implicit operator MyLong(long value) { return new MyLong(value); } public static implicit operator MyLong(MyInt myInt) { return new MyLong(myInt.Value); } public static bool operator ==(MyLong value1, MyLong value2) { return value1.Value == value2.Value; } public static bool operator !=(MyLong value1, MyLong value2) { return value1.Value != value2.Value; } public override int GetHashCode() { return (int) _value; } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; MyLong myLong = obj as MyLong; if (myLong == null) return false; if (_value != myLong._value) return false; return true; } } public class MyBaseOperator { private int _value; public MyBaseOperator(int value) { _value = value; } public int Value { get { return _value; } } public override string ToString() { return _value.ToString(); } public static MyBaseOperator operator+(MyBaseOperator left, MyBaseOperator right) { return new MyBaseOperator(left._value + right._value); } public static MyBaseOperator operator-(MyBaseOperator left, MyBaseOperator right) { return new MyBaseOperator(left._value - right._value); } } public class MyDerivedOperator : MyBaseOperator { public MyDerivedOperator(int value) : base(value) { } } public class MyDerivedOperatorRedeclared : MyBaseOperator { public MyDerivedOperatorRedeclared(int value) : base(value) { } public static MyDerivedOperatorRedeclared operator +(MyDerivedOperatorRedeclared left, MyDerivedOperatorRedeclared right) { return new MyDerivedOperatorRedeclared(left.Value + right.Value); } public static MyDerivedOperatorRedeclared operator -(MyDerivedOperatorRedeclared left, MyDerivedOperatorRedeclared right) { return new MyDerivedOperatorRedeclared(left.Value - right.Value); } } [Flags] public enum MyByteEnum : byte { None, Value1 = 0x0001, Value2 = 0x0002, Value3 = 0x0004 } [Flags] public enum MySByteEnum : sbyte { None, Value1 = 0x0001, Value2 = 0x0002, Value3 = 0x0004 } [Flags] public enum MyShortEnum : short { None, Value1 = 0x0001, Value2 = 0x0002, Value3 = 0x0004 } [Flags] public enum MyUShortEnum : ushort { None, Value1 = 0x0001, Value2 = 0x0002, Value3 = 0x0004 } [Flags] public enum MyIntEnum : int { None, Value1 = 0x0001, Value2 = 0x0002, Value3 = 0x0004 } [Flags] public enum MyUIntEnum : uint { None, Value1 = 0x0001, Value2 = 0x0002, Value3 = 0x0004 } [Flags] public enum MyLongEnum : long { None, Value1 = 0x0001, Value2 = 0x0002, Value3 = 0x0004 } [Flags] public enum MyULongEnum : ulong { None, Value1 = 0x0001, Value2 = 0x0002, Value3 = 0x0004 } public class MyClassWithEnumMembers { private MyByteEnum _myByteEnum; private MySByteEnum _mySByteEnum; private MyShortEnum _myShortEnum; private MyUShortEnum _myUShortEnum; private MyIntEnum _myIntEnum; private MyUIntEnum _myUIntEnum; private MyLongEnum _myLongEnum; private MyULongEnum _myULongEnum; public MyClassWithEnumMembers(int value) { _myByteEnum = (MyByteEnum) value; _mySByteEnum = (MySByteEnum) value; _myShortEnum = (MyShortEnum) value; _myUShortEnum = (MyUShortEnum) value; _myIntEnum = (MyIntEnum) value; _myUIntEnum = (MyUIntEnum) value; _myLongEnum = (MyLongEnum) value; _myULongEnum = (MyULongEnum) value; } public MyByteEnum MyByteEnum { get { return _myByteEnum; } set { _myByteEnum = value; } } public MySByteEnum MySByteEnum { get { return _mySByteEnum; } set { _mySByteEnum = value; } } public MyShortEnum MyShortEnum { get { return _myShortEnum; } set { _myShortEnum = value; } } public MyUShortEnum MyUShortEnum { get { return _myUShortEnum; } set { _myUShortEnum = value; } } public MyIntEnum MyIntEnum { get { return _myIntEnum; } set { _myIntEnum = value; } } public MyUIntEnum MyUIntEnum { get { return _myUIntEnum; } set { _myUIntEnum = value; } } public MyLongEnum MyLongEnum { get { return _myLongEnum; } set { _myLongEnum = value; } } public MyULongEnum MyULongEnum { get { return _myULongEnum; } set { _myULongEnum = value; } } } public struct MyStructWithoutEqualityOperators { private int _value; public MyStructWithoutEqualityOperators(int value) { _value = value; } public int Value { get { return _value; } } public override bool Equals(object obj) { MyStructWithoutEqualityOperators? other = obj as MyStructWithoutEqualityOperators?; if (other == null) return false; return _value == other.Value._value; } public override int GetHashCode() { // Just to avoid compiler warning. return base.GetHashCode(); } } public interface Interface0 { } public interface Interface1 { } public interface Interface2 { } public class BaseClass : Interface0 { } public class Derived1Class : BaseClass, Interface1 { } public class Derived2Class : BaseClass, Interface1, Interface2 { } #endregion #region Table Bindings public class MyIntRow { public MyInt Value; [IndexerName("Multiply")] public int this[int factor] { get { return Value.Value *factor; } } public override string ToString() { return Value.Value.ToString(); } } public class MyLongRow { public MyLong Value; } public class MyIntLongRow { public MyInt IntValue; public MyLong LongValue; } private static MyIntRow[] ProduceIntRows(int start, int end) { List<MyIntRow> rows = new List<MyIntRow>(end - start + 1); for (int i = start; i <= end; i++) { MyIntRow row = new MyIntRow(); row.Value = new MyInt(i); rows.Add(row); } return rows.ToArray(); } private static MyLongRow[] ProduceLongRows(int start, int end) { List<MyLongRow> rows = new List<MyLongRow>(end - start + 1); for (long i = start; i <= end; i++) { MyLongRow row = new MyLongRow(); row.Value = new MyLong(i); rows.Add(row); } return rows.ToArray(); } private static MyIntLongRow[] ProduceIntLongRows(int intStart, int intEnd, int longStart, int longEnd) { int count = (intEnd - intStart + 1)*(longEnd - longStart + 1); List<MyIntLongRow> rows = new List<MyIntLongRow>(count); for (int intValue = intStart; intValue <= intEnd; intValue++) { for (int longValue = longStart; longValue <= longEnd; longValue++) { MyIntLongRow row = new MyIntLongRow(); row.IntValue = new MyInt(intValue); row.LongValue = new MyLong(longValue); rows.Add(row); } } return rows.ToArray(); } #endregion #region Custom Functions public class Functions { [FunctionBinding("Calc", IsDeterministic = true)] public static string Calc(MyInt p1, MyInt p2) { return MethodInfo.GetCurrentMethod().ToString(); } [FunctionBinding("Calc", IsDeterministic = true)] public static string Calc(MyLong p1, MyLong p2) { return MethodInfo.GetCurrentMethod().ToString(); } [FunctionBinding("Calc", IsDeterministic = true)] public static string Calc(MyLong p1, MyInt p2) { return MethodInfo.GetCurrentMethod().ToString(); } [FunctionBinding("Calc", IsDeterministic = true)] public static string Calc(MyInt p1, MyLong p2) { return MethodInfo.GetCurrentMethod().ToString(); } [FunctionBinding("IntCalc", IsDeterministic = true)] public static string IntCalc(MyInt p1, MyInt p2) { return MethodInfo.GetCurrentMethod().ToString(); } [FunctionBinding("LongCalc", IsDeterministic = true)] public static string LongCalc(MyLong p1, MyLong p2) { return MethodInfo.GetCurrentMethod().ToString(); } } #endregion [TestInitialize] public void SetUp() { const int INT_START = 0; const int INT_END = 55; const int LONG_START = 50; const int LONG_END = 100; MyIntRow[] intRows = ProduceIntRows(INT_START, INT_END); MyLongRow[] longRows = ProduceLongRows(LONG_START, LONG_END); MyIntLongRow[] intLongRows = ProduceIntLongRows(INT_START, INT_END, LONG_START, LONG_END); _query = QueryFactory.CreateQuery(); _query.DataContext.Tables.Add(intRows, "IntTable"); _query.DataContext.Tables.Add(longRows, "LongTable"); _query.DataContext.Tables.Add(intLongRows, "IntLongTable"); _query.DataContext.Functions.AddFromContainer(typeof(Functions)); _expression = new Expression<object>(); _expression.DataContext = _query.DataContext; _expression.Parameters.Add("MyInt", typeof(MyInt), new MyInt(1)); _expression.Parameters.Add("MyLong", typeof(MyLong), new MyLong(2)); } [TestMethod] public void EqualsResolvesIfImplicitAndExplictAreApplicable() { _query.Text = "SELECT COUNT(*) FROM IntLongTable WHERE IntValue = LongValue"; int count = (int) _query.ExecuteScalar(); Assert.AreEqual(6, count); } [TestMethod] public void ImplictIsCalledWhenNothingElseIsAvailable() { _expression.Text = "IntCalc(1, 2)"; string result = (string) _expression.Evaluate(); Assert.AreEqual("System.String IntCalc(MyInt, MyInt)", result); } [TestMethod] public void ExplictIsCalledWhenNothingElseIsAvailable() { string result; _expression.Text = "IntCalc(@MyLong, @MyLong)"; result = (string) _expression.Evaluate(); Assert.AreEqual("System.String IntCalc(MyInt, MyInt)", result); _expression.Text = "IntCalc(@MyInt, @MyLong)"; result = (string) _expression.Evaluate(); Assert.AreEqual("System.String IntCalc(MyInt, MyInt)", result); _expression.Text = "IntCalc(@MyLong, @MyInt)"; result = (string) _expression.Evaluate(); Assert.AreEqual("System.String IntCalc(MyInt, MyInt)", result); } [TestMethod] public void ImplictIsBetterThanExplicit() { _expression.Text = "Calc(@MyInt, @MyLong)"; string result = (string) _expression.Evaluate(); Assert.AreEqual("System.String Calc(MyInt, MyLong)", result); } [TestMethod] public void ImplicitConversionToIntIsBetterThanLong() { _expression.Text = "Calc(1, 2)"; string result = (string) _expression.Evaluate(); Assert.AreEqual("System.String Calc(MyInt, MyInt)", result); } [TestMethod] public void SameTypeIsBetterThanAnyConversion() { string result; _expression.Text = "Calc(@MyInt, @MyInt)"; result = (string) _expression.Evaluate(); Assert.AreEqual("System.String Calc(MyInt, MyInt)", result); _expression.Text = "Calc(@MyLong, @MyLong)"; result = (string) _expression.Evaluate(); Assert.AreEqual("System.String Calc(MyLong, MyLong)", result); } [TestMethod] public void OperatorsWithMixedTypesWorkAsExpected() { MyDerivedOperatorRedeclared left = new MyDerivedOperatorRedeclared(13); MyBaseOperator right = new MyBaseOperator(11); MyBaseOperator result; Expression<MyBaseOperator> expression = new Expression<MyBaseOperator>(); expression.Parameters.Add("Left", left.GetType(), left); expression.Parameters.Add("Right", right.GetType(), right); expression.Text = "Left + Right"; result = expression.Evaluate(); Assert.AreEqual(24, result.Value); expression.Text = "Left - Right"; result = expression.Evaluate(); Assert.AreEqual(2, result.Value); } [TestMethod] public void OperatorsInBaseClassAreConsidered() { MyDerivedOperator left = new MyDerivedOperator(11); MyDerivedOperator right = new MyDerivedOperator(13); MyBaseOperator result; Expression<MyBaseOperator> expression = new Expression<MyBaseOperator>(); expression.Parameters.Add("Left", left.GetType(), left); expression.Parameters.Add("Right", right.GetType(), right); expression.Text = "Left + Right"; result = expression.Evaluate(); Assert.AreEqual(24, result.Value); expression.Text = "Left - Right"; result = expression.Evaluate(); Assert.AreEqual(-2, result.Value); } [TestMethod] public void OperatorsInBaseClassWorkAsExpected() { MyBaseOperator left = new MyBaseOperator(13); MyBaseOperator right = new MyBaseOperator(11); MyBaseOperator result; Expression<MyBaseOperator> expression = new Expression<MyBaseOperator>(); expression.Parameters.Add("Left", left.GetType(), left); expression.Parameters.Add("Right", right.GetType(), right); expression.Text = "Left + Right"; result = expression.Evaluate(); Assert.AreEqual(24, result.Value); expression.Text = "Left - Right"; result = expression.Evaluate(); Assert.AreEqual(2, result.Value); } [TestMethod] public void OperatorsInDerivedClassWorkAsExpected() { MyDerivedOperatorRedeclared left = new MyDerivedOperatorRedeclared(11); MyDerivedOperatorRedeclared right = new MyDerivedOperatorRedeclared(13); MyDerivedOperatorRedeclared result; Expression<MyDerivedOperatorRedeclared> expression = new Expression<MyDerivedOperatorRedeclared>(); expression.Parameters.Add("Left", left.GetType(), left); expression.Parameters.Add("Right", right.GetType(), right); expression.Text = "Left + Right"; result = expression.Evaluate(); Assert.AreEqual(24, result.Value); expression.Text = "Left - Right"; result = expression.Evaluate(); Assert.AreEqual(-2, result.Value); } [TestMethod] public void EnumBitTesting() { const int None = 0x0; const int Value1 = 0x0001; const int Value2 = 0x0002; const int Value3 = 0x0004; List<MyClassWithEnumMembers> myClasses = new List<MyClassWithEnumMembers>(); myClasses.Add(new MyClassWithEnumMembers(None)); myClasses.Add(new MyClassWithEnumMembers(Value1)); myClasses.Add(new MyClassWithEnumMembers(Value2)); myClasses.Add(new MyClassWithEnumMembers(Value3)); myClasses.Add(new MyClassWithEnumMembers(Value1 | Value2)); myClasses.Add(new MyClassWithEnumMembers(Value3 | Value2)); myClasses.Add(new MyClassWithEnumMembers(Value1 | Value3)); myClasses.Add(new MyClassWithEnumMembers(Value2 | Value3)); DataTable result; Query query = new Query(); query.DataContext.Tables.Add(myClasses, "MyClasses"); query.Parameters.Add("MyByteEnum", typeof (MyByteEnum), MyByteEnum.Value1); query.Parameters.Add("MySByteEnum", typeof (MySByteEnum), MySByteEnum.Value1); query.Parameters.Add("MyShortEnum", typeof (MyShortEnum), MyShortEnum.Value1); query.Parameters.Add("MyUShortEnum", typeof (MyUShortEnum), MyUShortEnum.Value1); query.Parameters.Add("MyIntEnum", typeof (MyIntEnum), MyIntEnum.Value1); query.Parameters.Add("MyUIntEnum", typeof (MyUIntEnum), MyUIntEnum.Value1); query.Parameters.Add("MyLongEnum", typeof (MyLongEnum), MyLongEnum.Value1); query.Parameters.Add("MyULongEnum", typeof (MyULongEnum), MyULongEnum.Value1); // Check bitwise-AND query.Text = @" SELECT c.MyByteEnum, c.MySByteEnum, c.MyShortEnum, c.MyUShortEnum, c.MyIntEnum, c.MyUIntEnum, c.MyLongEnum, c.MyULongEnum FROM MyClasses c WHERE (c.MyByteEnum & @MyByteEnum) != 0 AND (c.MySByteEnum & @MySByteEnum) != 0 AND (c.MyShortEnum & @MyShortEnum) != 0 AND (c.MyUShortEnum & @MyUShortEnum) != 0 AND (c.MyIntEnum & @MyIntEnum) != 0 AND (c.MyUIntEnum & @MyUIntEnum) != 0 AND (c.MyLongEnum & @MyLongEnum) != 0 AND (c.MyULongEnum & @MyULongEnum) != 0 "; result = query.ExecuteDataTable(); Assert.AreEqual(3, result.Rows.Count); Assert.AreEqual(MyByteEnum.Value1, (MyByteEnum) result.Rows[0][0]); Assert.AreEqual(MySByteEnum.Value1, (MySByteEnum)result.Rows[0][1]); Assert.AreEqual(MyShortEnum.Value1, (MyShortEnum)result.Rows[0][2]); Assert.AreEqual(MyUShortEnum.Value1, (MyUShortEnum)result.Rows[0][3]); Assert.AreEqual(MyIntEnum.Value1, (MyIntEnum)result.Rows[0][4]); Assert.AreEqual(MyUIntEnum.Value1, (MyUIntEnum)result.Rows[0][5]); Assert.AreEqual(MyLongEnum.Value1, (MyLongEnum)result.Rows[0][6]); Assert.AreEqual(MyULongEnum.Value1, (MyULongEnum)result.Rows[0][7]); Assert.AreEqual(MyByteEnum.Value1 | MyByteEnum.Value2, (MyByteEnum)result.Rows[1][0]); Assert.AreEqual(MySByteEnum.Value1 | MySByteEnum.Value2, (MySByteEnum)result.Rows[1][1]); Assert.AreEqual(MyShortEnum.Value1 | MyShortEnum.Value2, (MyShortEnum)result.Rows[1][2]); Assert.AreEqual(MyUShortEnum.Value1 | MyUShortEnum.Value2, (MyUShortEnum)result.Rows[1][3]); Assert.AreEqual(MyIntEnum.Value1 | MyIntEnum.Value2, (MyIntEnum)result.Rows[1][4]); Assert.AreEqual(MyUIntEnum.Value1 | MyUIntEnum.Value2, (MyUIntEnum)result.Rows[1][5]); Assert.AreEqual(MyLongEnum.Value1 | MyLongEnum.Value2, (MyLongEnum)result.Rows[1][6]); Assert.AreEqual(MyULongEnum.Value1 | MyULongEnum.Value2, (MyULongEnum)result.Rows[1][7]); Assert.AreEqual(MyByteEnum.Value1 | MyByteEnum.Value3, (MyByteEnum)result.Rows[2][0]); Assert.AreEqual(MySByteEnum.Value1 | MySByteEnum.Value3, (MySByteEnum)result.Rows[2][1]); Assert.AreEqual(MyShortEnum.Value1 | MyShortEnum.Value3, (MyShortEnum)result.Rows[2][2]); Assert.AreEqual(MyUShortEnum.Value1 | MyUShortEnum.Value3, (MyUShortEnum)result.Rows[2][3]); Assert.AreEqual(MyIntEnum.Value1 | MyIntEnum.Value3, (MyIntEnum)result.Rows[2][4]); Assert.AreEqual(MyUIntEnum.Value1 | MyUIntEnum.Value3, (MyUIntEnum)result.Rows[2][5]); Assert.AreEqual(MyLongEnum.Value1 | MyLongEnum.Value3, (MyLongEnum)result.Rows[2][6]); Assert.AreEqual(MyULongEnum.Value1 | MyULongEnum.Value3, (MyULongEnum)result.Rows[2][7]); // Check bitwise-OR query.Text = @" SELECT c.MyByteEnum | @MyByteEnum, c.MySByteEnum | @MySByteEnum, c.MyShortEnum | @MyShortEnum, c.MyUShortEnum | @MyUShortEnum, c.MyIntEnum | @MyIntEnum, c.MyUIntEnum | @MyUIntEnum, c.MyLongEnum | @MyLongEnum, c.MyULongEnum | @MyULongEnum FROM MyClasses c "; result = query.ExecuteDataTable(); Assert.AreEqual(8, result.Rows.Count); Assert.AreEqual(MyByteEnum.Value1, (MyByteEnum) result.Rows[0][0]); Assert.AreEqual(MyByteEnum.Value1, (MyByteEnum)result.Rows[1][0]); Assert.AreEqual(MyByteEnum.Value2 | MyByteEnum.Value1, (MyByteEnum)result.Rows[2][0]); Assert.AreEqual(MyByteEnum.Value3 | MyByteEnum.Value1, (MyByteEnum)result.Rows[3][0]); Assert.AreEqual(MyByteEnum.Value1 | MyByteEnum.Value2, (MyByteEnum)result.Rows[4][0]); Assert.AreEqual(MyByteEnum.Value3 | MyByteEnum.Value2 | MyByteEnum.Value1, (MyByteEnum)result.Rows[5][0]); Assert.AreEqual(MyByteEnum.Value1 | MyByteEnum.Value3, (MyByteEnum)result.Rows[6][0]); Assert.AreEqual(MyByteEnum.Value2 | MyByteEnum.Value3 | MyByteEnum.Value1, (MyByteEnum)result.Rows[7][0]); Assert.AreEqual(MySByteEnum.Value1, (MySByteEnum) result.Rows[0][1]); Assert.AreEqual(MySByteEnum.Value1, (MySByteEnum)result.Rows[1][1]); Assert.AreEqual(MySByteEnum.Value2 | MySByteEnum.Value1, (MySByteEnum)result.Rows[2][1]); Assert.AreEqual(MySByteEnum.Value3 | MySByteEnum.Value1, (MySByteEnum)result.Rows[3][1]); Assert.AreEqual(MySByteEnum.Value1 | MySByteEnum.Value2, (MySByteEnum)result.Rows[4][1]); Assert.AreEqual(MySByteEnum.Value3 | MySByteEnum.Value2 | MySByteEnum.Value1, (MySByteEnum)result.Rows[5][1]); Assert.AreEqual(MySByteEnum.Value1 | MySByteEnum.Value3, (MySByteEnum)result.Rows[6][1]); Assert.AreEqual(MySByteEnum.Value2 | MySByteEnum.Value3 | MySByteEnum.Value1, (MySByteEnum)result.Rows[7][1]); Assert.AreEqual(MyShortEnum.Value1, (MyShortEnum)result.Rows[0][2]); Assert.AreEqual(MyShortEnum.Value1, (MyShortEnum)result.Rows[1][2]); Assert.AreEqual(MyShortEnum.Value2 | MyShortEnum.Value1, (MyShortEnum)result.Rows[2][2]); Assert.AreEqual(MyShortEnum.Value3 | MyShortEnum.Value1, (MyShortEnum)result.Rows[3][2]); Assert.AreEqual(MyShortEnum.Value1 | MyShortEnum.Value2, (MyShortEnum)result.Rows[4][2]); Assert.AreEqual(MyShortEnum.Value3 | MyShortEnum.Value2 | MyShortEnum.Value1, (MyShortEnum)result.Rows[5][2]); Assert.AreEqual(MyShortEnum.Value1 | MyShortEnum.Value3, (MyShortEnum)result.Rows[6][2]); Assert.AreEqual(MyShortEnum.Value2 | MyShortEnum.Value3 | MyShortEnum.Value1, (MyShortEnum)result.Rows[7][2]); Assert.AreEqual(MyUShortEnum.Value1, (MyUShortEnum)result.Rows[0][3]); Assert.AreEqual(MyUShortEnum.Value1, (MyUShortEnum)result.Rows[1][3]); Assert.AreEqual(MyUShortEnum.Value2 | MyUShortEnum.Value1, (MyUShortEnum)result.Rows[2][3]); Assert.AreEqual(MyUShortEnum.Value3 | MyUShortEnum.Value1, (MyUShortEnum)result.Rows[3][3]); Assert.AreEqual(MyUShortEnum.Value1 | MyUShortEnum.Value2, (MyUShortEnum)result.Rows[4][3]); Assert.AreEqual(MyUShortEnum.Value3 | MyUShortEnum.Value2 | MyUShortEnum.Value1, (MyUShortEnum)result.Rows[5][3]); Assert.AreEqual(MyUShortEnum.Value1 | MyUShortEnum.Value3, (MyUShortEnum)result.Rows[6][3]); Assert.AreEqual(MyUShortEnum.Value2 | MyUShortEnum.Value3 | MyUShortEnum.Value1, (MyUShortEnum)result.Rows[7][3]); Assert.AreEqual(MyIntEnum.Value1, (MyIntEnum)result.Rows[0][4]); Assert.AreEqual(MyIntEnum.Value1, (MyIntEnum)result.Rows[1][4]); Assert.AreEqual(MyIntEnum.Value2 | MyIntEnum.Value1, (MyIntEnum)result.Rows[2][4]); Assert.AreEqual(MyIntEnum.Value3 | MyIntEnum.Value1, (MyIntEnum)result.Rows[3][4]); Assert.AreEqual(MyIntEnum.Value1 | MyIntEnum.Value2, (MyIntEnum)result.Rows[4][4]); Assert.AreEqual(MyIntEnum.Value3 | MyIntEnum.Value2 | MyIntEnum.Value1, (MyIntEnum)result.Rows[5][4]); Assert.AreEqual(MyIntEnum.Value1 | MyIntEnum.Value3, (MyIntEnum)result.Rows[6][4]); Assert.AreEqual(MyIntEnum.Value2 | MyIntEnum.Value3 | MyIntEnum.Value1, (MyIntEnum)result.Rows[7][4]); Assert.AreEqual(MyUIntEnum.Value1, (MyUIntEnum)result.Rows[0][5]); Assert.AreEqual(MyUIntEnum.Value1, (MyUIntEnum)result.Rows[1][5]); Assert.AreEqual(MyUIntEnum.Value2 | MyUIntEnum.Value1, (MyUIntEnum)result.Rows[2][5]); Assert.AreEqual(MyUIntEnum.Value3 | MyUIntEnum.Value1, (MyUIntEnum)result.Rows[3][5]); Assert.AreEqual(MyUIntEnum.Value1 | MyUIntEnum.Value2, (MyUIntEnum)result.Rows[4][5]); Assert.AreEqual(MyUIntEnum.Value3 | MyUIntEnum.Value2 | MyUIntEnum.Value1, (MyUIntEnum)result.Rows[5][5]); Assert.AreEqual(MyUIntEnum.Value1 | MyUIntEnum.Value3, (MyUIntEnum)result.Rows[6][5]); Assert.AreEqual(MyUIntEnum.Value2 | MyUIntEnum.Value3 | MyUIntEnum.Value1, (MyUIntEnum)result.Rows[7][5]); Assert.AreEqual(MyLongEnum.Value1, (MyLongEnum)result.Rows[0][6]); Assert.AreEqual(MyLongEnum.Value1, (MyLongEnum)result.Rows[1][6]); Assert.AreEqual(MyLongEnum.Value2 | MyLongEnum.Value1, (MyLongEnum)result.Rows[2][6]); Assert.AreEqual(MyLongEnum.Value3 | MyLongEnum.Value1, (MyLongEnum)result.Rows[3][6]); Assert.AreEqual(MyLongEnum.Value1 | MyLongEnum.Value2, (MyLongEnum)result.Rows[4][6]); Assert.AreEqual(MyLongEnum.Value3 | MyLongEnum.Value2 | MyLongEnum.Value1, (MyLongEnum)result.Rows[5][6]); Assert.AreEqual(MyLongEnum.Value1 | MyLongEnum.Value3, (MyLongEnum)result.Rows[6][6]); Assert.AreEqual(MyLongEnum.Value2 | MyLongEnum.Value3 | MyLongEnum.Value1, (MyLongEnum)result.Rows[7][6]); Assert.AreEqual(MyULongEnum.Value1, (MyULongEnum)result.Rows[0][7]); Assert.AreEqual(MyULongEnum.Value1, (MyULongEnum)result.Rows[1][7]); Assert.AreEqual(MyULongEnum.Value2 | MyULongEnum.Value1, (MyULongEnum)result.Rows[2][7]); Assert.AreEqual(MyULongEnum.Value3 | MyULongEnum.Value1, (MyULongEnum)result.Rows[3][7]); Assert.AreEqual(MyULongEnum.Value1 | MyULongEnum.Value2, (MyULongEnum)result.Rows[4][7]); Assert.AreEqual(MyULongEnum.Value3 | MyULongEnum.Value2 | MyULongEnum.Value1, (MyULongEnum)result.Rows[5][7]); Assert.AreEqual(MyULongEnum.Value1 | MyULongEnum.Value3, (MyULongEnum)result.Rows[6][7]); Assert.AreEqual(MyULongEnum.Value2 | MyULongEnum.Value3 | MyULongEnum.Value1, (MyULongEnum)result.Rows[7][7]); } [TestMethod] public void EnumBitTestingBetweenDifferentEnums() { Expression<bool> expression = new Expression<bool>(); expression.Parameters.Add("Left", typeof (MyIntEnum), MyIntEnum.Value1); expression.Parameters.Add("Right", typeof(MyUIntEnum), MyUIntEnum.Value1); try { expression.Text = "(Left | Right) != 0"; expression.Evaluate(); Assert.Fail("Bitwise-OR between different enum types should fail."); } catch (CompilationException ex) { Assert.AreEqual(1, ex.CompilationErrors.Count); Assert.AreEqual(ErrorId.CannotApplyBinaryOperator, ex.CompilationErrors[0].Id); } try { expression.Text = "(Left & Right) != 0"; expression.Evaluate(); Assert.Fail("Bitwise-AND between different enum types should fail."); } catch (CompilationException ex) { Assert.AreEqual(1, ex.CompilationErrors.Count); Assert.AreEqual(ErrorId.CannotApplyBinaryOperator, ex.CompilationErrors[0].Id); } } [TestMethod] public void EqualityCheckBetweenAbstractObjects() { object left = Environment.UserName; object right = Environment.UserName; bool result; Expression<bool> expression = new Expression<bool>(); expression.Parameters.Add("Left", typeof(object), left); expression.Parameters.Add("Right", typeof(object), right); expression.Text = "Left = Right"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "Left <> Right"; result = expression.Evaluate(); Assert.AreEqual(false, result); } [TestMethod] public void EqualityCheckBetweenAbstractEnums() { Enum left = MyIntEnum.Value1; Enum right = MyIntEnum.Value1; bool result; Expression<bool> expression = new Expression<bool>(); expression.Parameters.Add("Left", typeof(Enum), left); expression.Parameters.Add("Right", typeof(Enum), right); expression.Text = "Left = Right"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "Left <> Right"; result = expression.Evaluate(); Assert.AreEqual(false, result); } [TestMethod] public void EqualityCheckBetweenConcreteEnums() { MyIntEnum left = MyIntEnum.Value1; MyIntEnum right = MyIntEnum.Value1; bool result; Expression<bool> expression = new Expression<bool>(); expression.Parameters.Add("Left", typeof(MyIntEnum), left); expression.Parameters.Add("Right", typeof(MyIntEnum), right); expression.Text = "Left = Right"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "Left <> Right"; result = expression.Evaluate(); Assert.AreEqual(false, result); } [TestMethod] public void EqualityCheckBetweenAbstractStructs() { ValueType left = 42; ValueType right = 42; bool result; Expression<bool> expression = new Expression<bool>(); expression.Parameters.Add("Left", typeof(ValueType), left); expression.Parameters.Add("Right", typeof(ValueType), right); expression.Text = "Left = Right"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "Left <> Right"; result = expression.Evaluate(); Assert.AreEqual(false, result); } [TestMethod] public void EqualityCheckBetweenConcreteStructs() { MyStructWithoutEqualityOperators left = new MyStructWithoutEqualityOperators(42); MyStructWithoutEqualityOperators right = new MyStructWithoutEqualityOperators(42); bool result; Expression<bool> expression = new Expression<bool>(); expression.Parameters.Add("Left", typeof(MyStructWithoutEqualityOperators), left); expression.Parameters.Add("Right", typeof(MyStructWithoutEqualityOperators), right); expression.Text = "Left = Right"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "Left <> Right"; result = expression.Evaluate(); Assert.AreEqual(false, result); } [TestMethod] public void EqualityCheckBetweenCompatibleTypes() { BaseClass baseClass = new BaseClass(); Derived1Class derived1Class = new Derived1Class(); bool result; Expression<bool> expression = new Expression<bool>(); expression.Parameters.Add("baseClass", typeof(BaseClass), baseClass); expression.Parameters.Add("derived1Class", typeof(Derived1Class), derived1Class); expression.Parameters.Add("derived1ClassTypedAsBase", typeof(BaseClass), derived1Class); expression.Text = "baseClass = derived1Class"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived1Class = baseClass"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived1Class = derived1ClassTypedAsBase"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived1ClassTypedAsBase = derived1Class"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "baseClass <> derived1Class"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived1Class <> baseClass"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived1Class <> derived1ClassTypedAsBase"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived1ClassTypedAsBase <> derived1Class"; result = expression.Evaluate(); Assert.AreEqual(false, result); } [TestMethod] public void EqualityCheckBetweenCompatibleInterfaceTypes() { BaseClass baseClass = new BaseClass(); Derived1Class derived1Class = new Derived1Class(); Derived2Class derived2Class = new Derived2Class(); bool result; Expression<bool> expression = new Expression<bool>(); expression.Parameters.Add("baseClass", typeof(BaseClass), baseClass); expression.Parameters.Add("derived1Class", typeof(Derived1Class), derived1Class); expression.Parameters.Add("derived2Class", typeof(Derived2Class), derived2Class); expression.Parameters.Add("baseClassInterface0", typeof(Interface0), baseClass); expression.Parameters.Add("derived1ClassInterface0", typeof(Interface0), derived1Class); expression.Parameters.Add("derived1ClassInterface1", typeof(Interface1), derived1Class); expression.Parameters.Add("derived2ClassInterface0", typeof(Interface0), derived2Class); expression.Parameters.Add("derived2ClassInterface1", typeof(Interface1), derived2Class); expression.Parameters.Add("derived2ClassInterface2", typeof(Interface2), derived2Class); // Check Interface0 against baseClass, derived1Class, and derived2Class. expression.Text = "baseClass = baseClassInterface0"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "baseClassInterface0 = baseClass"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived1Class = derived1ClassInterface0"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived1ClassInterface0 = derived1Class"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived2Class = derived2ClassInterface0"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived2ClassInterface0 = derived2Class"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "baseClass = derived1ClassInterface0"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived1ClassInterface0 = baseClass"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "baseClass = derived2ClassInterface0"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived2ClassInterface0 = baseClass"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived1ClassInterface0 = derived2ClassInterface0"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived2ClassInterface0 = derived1ClassInterface0"; result = expression.Evaluate(); Assert.AreEqual(false, result); // Check Interface1 against derived1Class and derived2Class. expression.Text = "derived1ClassInterface1 = derived1Class"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived1Class = derived1ClassInterface1"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived2ClassInterface1 = derived2Class"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived2Class = derived2ClassInterface1"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived2Class = derived1ClassInterface1"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived1ClassInterface1 = derived2Class"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived1Class = derived2ClassInterface1"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived2ClassInterface1 = derived1Class"; result = expression.Evaluate(); Assert.AreEqual(false, result); // Check Interface2 against derived2Class expression.Text = "derived2ClassInterface2 = derived2Class"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived2Class = derived2ClassInterface2"; result = expression.Evaluate(); Assert.AreEqual(true, result); //------------------------------- // Now check with <> version. //------------------------------- // Check Interface0 against baseClass, derived1Class, and derived2Class. expression.Text = "baseClass <> baseClassInterface0"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "baseClassInterface0 <> baseClass"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived1Class <> derived1ClassInterface0"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived1ClassInterface0 <> derived1Class"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived2Class <> derived2ClassInterface0"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived2ClassInterface0 <> derived2Class"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "baseClass <> derived1ClassInterface0"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived1ClassInterface0 <> baseClass"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "baseClass <> derived2ClassInterface0"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived2ClassInterface0 <> baseClass"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived1ClassInterface0 <> derived2ClassInterface0"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived2ClassInterface0 <> derived1ClassInterface0"; result = expression.Evaluate(); Assert.AreEqual(true, result); // Check Interface1 against derived1Class and derived2Class. expression.Text = "derived1ClassInterface1 <> derived1Class"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived1Class <> derived1ClassInterface1"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived2ClassInterface1 <> derived2Class"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived2Class <> derived2ClassInterface1"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived2Class <> derived1ClassInterface1"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived1ClassInterface1 <> derived2Class"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived1Class <> derived2ClassInterface1"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived2ClassInterface1 <> derived1Class"; result = expression.Evaluate(); Assert.AreEqual(true, result); // Check Interface2 against derived2Class expression.Text = "derived2ClassInterface2 <> derived2Class"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived2Class <> derived2ClassInterface2"; result = expression.Evaluate(); Assert.AreEqual(false, result); } [TestMethod] public void EqualityCheckBetweenArbitraryInterfaceTypes() { BaseClass baseClass = new BaseClass(); Derived1Class derived1Class = new Derived1Class(); Derived2Class derived2Class = new Derived2Class(); bool result; Expression<bool> expression = new Expression<bool>(); expression.Parameters.Add("baseClass", typeof(BaseClass), baseClass); expression.Parameters.Add("baseClassInterface0", typeof(Interface0), baseClass); expression.Parameters.Add("derived1ClassInterface0", typeof(Interface0), derived1Class); expression.Parameters.Add("derived1ClassInterface1", typeof(Interface1), derived1Class); expression.Parameters.Add("derived2ClassInterface0", typeof(Interface0), derived2Class); expression.Parameters.Add("derived2ClassInterface1", typeof(Interface1), derived2Class); expression.Parameters.Add("derived2ClassInterface2", typeof(Interface2), derived2Class); expression.Text = "baseClass = baseClassInterface0"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "baseClassInterface0 = baseClass"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "baseClass = derived1ClassInterface0"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived1ClassInterface0 = baseClass"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "baseClass = derived1ClassInterface1"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived1ClassInterface1 = baseClass"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "baseClass = derived2ClassInterface0"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived2ClassInterface0 = baseClass"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "baseClass = derived2ClassInterface1"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived2ClassInterface1 = baseClass"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "baseClass = derived2ClassInterface2"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "derived2ClassInterface2 = baseClass"; result = expression.Evaluate(); Assert.AreEqual(false, result); //------------------------------- // Now check with <> version. //------------------------------- expression.Text = "baseClass <> baseClassInterface0"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "baseClassInterface0 <> baseClass"; result = expression.Evaluate(); Assert.AreEqual(false, result); expression.Text = "baseClass <> derived1ClassInterface0"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived1ClassInterface0 <> baseClass"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "baseClass <> derived1ClassInterface1"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived1ClassInterface1 <> baseClass"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "baseClass <> derived2ClassInterface0"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived2ClassInterface0 <> baseClass"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "baseClass <> derived2ClassInterface1"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived2ClassInterface1 <> baseClass"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "baseClass <> derived2ClassInterface2"; result = expression.Evaluate(); Assert.AreEqual(true, result); expression.Text = "derived2ClassInterface2 <> baseClass"; result = expression.Evaluate(); Assert.AreEqual(true, result); } [TestMethod] public void EqualityCheckBetweenIncompatibleTypesFails() { Derived1Class derived1Class = new Derived1Class(); Derived2Class derived2Class = new Derived2Class(); Expression<bool> expression = new Expression<bool>(); expression.Parameters.Add("derived1Class", typeof(Derived1Class), derived1Class); expression.Parameters.Add("derived2Class", typeof(Derived2Class), derived2Class); try { expression.Text = "derived1Class = derived2Class"; expression.Evaluate(); Assert.Fail("Equality check between incompatible types should fail."); } catch (CompilationException ex) { Assert.AreEqual(1, ex.CompilationErrors.Count); Assert.AreEqual(ErrorId.CannotApplyBinaryOperator, ex.CompilationErrors[0].Id); } try { expression.Text = "derived1Class <> derived2Class"; expression.Evaluate(); Assert.Fail("Inequality check between incompatible types should fail."); } catch (CompilationException ex) { Assert.AreEqual(1, ex.CompilationErrors.Count); Assert.AreEqual(ErrorId.CannotApplyBinaryOperator, ex.CompilationErrors[0].Id); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Runtime.Serialization; using System.Threading; #if Smartphone using TweetSharp.Core.Attributes; #endif #if SILVERLIGHT using System.Reflection; #endif namespace TweetSharp { #if !SILVERLIGHT /// <summary> /// Represents a normalized date from the Twitter API. /// </summary> [Serializable] #endif #if !Smartphone && !NET20 [DataContract] #endif public class TwitterDateTime : ITwitterModel { private static readonly IDictionary<string, string> _map = new Dictionary<string, string>(); /// <summary> /// Gets or sets the Twitter-based date format. /// </summary> /// <value>The format.</value> public virtual TwitterDateFormat Format { get; private set; } /// <summary> /// Gets or sets the actual date time. /// </summary> /// <value>The date time.</value> public virtual DateTime DateTime { get; private set; } #if !SILVERLIGHT && !Smartphone && !NET20 static readonly ReaderWriterLockSlim _readerWriterLock = new ReaderWriterLockSlim(); #else private static readonly object _lock = new object(); #endif /// <summary> /// Initializes a new instance of the <see cref="TwitterDateTime"/> class. /// </summary> /// <param name="dateTime">The date time.</param> /// <param name="format">The format.</param> public TwitterDateTime(DateTime dateTime, TwitterDateFormat format) { Format = format; DateTime = dateTime; } #if Smartphone || SILVERLIGHT private static readonly IList<string> _names = new List<string>(); #endif /// <summary> /// Converts from date time. /// </summary> /// <param name="input">The input.</param> /// <param name="format">The format.</param> /// <returns></returns> public static string ConvertFromDateTime(DateTime input, TwitterDateFormat format) { EnsureDateFormatsAreMapped(); #if !SILVERLIGHT && !Smartphone var name = Enum.GetName(typeof(TwitterDateFormat), format); #else EnsureEnumNamesAreMapped(typeof (TwitterDateFormat)); var name = _names[_names.IndexOf(format.ToString())]; #endif GetReadLockOnMap(); var value = _map[name]; ReleaseReadLockOnMap(); value = value.Replace(" zzzzz", " +0000"); var converted = input.ToString(value, CultureInfo.InvariantCulture); return converted; } /// <summary> /// Converts to date time. /// </summary> /// <param name="input">The input.</param> /// <returns></returns> public static DateTime ConvertToDateTime(string input) { EnsureDateFormatsAreMapped(); GetReadLockOnMap(); var formats = _map.Values; ReleaseReadLockOnMap(); foreach (var format in formats) { DateTime date; #if !Smartphone if (DateTime.TryParseExact(input, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out date)) #else if (TryParseDateTime(input, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out date)) #endif { return date; } } return default(DateTime); } /// <summary> /// Converts to twitter date time. /// </summary> /// <param name="input">The input.</param> /// <returns></returns> public static TwitterDateTime ConvertToTwitterDateTime(string input) { EnsureDateFormatsAreMapped(); GetReadLockOnMap(); try { foreach (var format in _map) { DateTime date; #if !Smartphone if (DateTime.TryParseExact(input, format.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out date)) #else if (TryParseDateTime(input, format.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out date)) #endif { var kind = Enum.Parse(typeof (TwitterDateFormat), format.Key, true); return new TwitterDateTime(date, (TwitterDateFormat) kind); } } return default(TwitterDateTime); } finally { ReleaseReadLockOnMap(); } } private static void EnsureDateFormatsAreMapped() { var type = typeof (TwitterDateFormat); #if !SILVERLIGHT && !Smartphone var names = Enum.GetNames(type); #else EnsureEnumNamesAreMapped(type); var names = _names; #endif GetReadLockOnMap(); try { foreach (var name in names) { if (_map.ContainsKey(name)) { continue; } GetWriteLockOnMap(); try { var fi = typeof (TwitterDateFormat).GetField(name); var attributes = fi.GetCustomAttributes(typeof (DescriptionAttribute), false); var format = (DescriptionAttribute) attributes[0]; _map.Add(name, format.Description); } finally { ReleaseWriteLockOnMap(); } } } finally { ReleaseReadLockOnMap(); } } private static void GetReadLockOnMap() { #if !SILVERLIGHT && !Smartphone && !NET20 _readerWriterLock.EnterUpgradeableReadLock(); #else Monitor.Enter(_lock); #endif } private static void ReleaseReadLockOnMap() { #if !SILVERLIGHT && !Smartphone && !NET20 _readerWriterLock.ExitUpgradeableReadLock(); #else Monitor.Exit(_lock); #endif } private static void GetWriteLockOnMap() { #if !SILVERLIGHT && !Smartphone && !NET20 _readerWriterLock.EnterWriteLock(); #else //already have exclusive access #endif } private static void ReleaseWriteLockOnMap() { #if !SILVERLIGHT && !Smartphone && !NET20 _readerWriterLock.ExitWriteLock(); #else //will exit when we give up read lock #endif } #if Smartphone || SILVERLIGHT private static bool TryParseDateTime(string input, string format, IFormatProvider provider, DateTimeStyles styles, out DateTime result) { try { result = DateTime.ParseExact(input, format, provider, styles); return true; } catch (Exception) { result = default(DateTime); return false; } } private static void EnsureEnumNamesAreMapped(Type type) { GetReadLockOnMap(); GetWriteLockOnMap(); try { var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static); foreach (var field in fields) { if (_names.Contains(field.Name)) { continue; } _names.Add(field.Name); } } finally { ReleaseWriteLockOnMap(); ReleaseReadLockOnMap(); } } #endif /// <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 ConvertFromDateTime(DateTime, Format); } #if !Smartphone && !NET20 [DataMember] #endif public virtual string RawSource { get; set; } } }
// // The Open Toolkit Library License // // Copyright (c) 2006 - 2010 the Open Toolkit library. // // 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; #if !MINIMAL using System.Drawing; #endif using System.Runtime.InteropServices; namespace OpenTK.Platform.X11 { internal sealed class X11DisplayDevice : DisplayDeviceBase { // Store a mapping between resolutions and their respective // size_index (needed for XRRSetScreenConfig). The size_index // is simply the sequence number of the resolution as returned by // XRRSizes. This is done per available screen. private readonly List<Dictionary<DisplayResolution, int>> screenResolutionToIndex = new List<Dictionary<DisplayResolution, int>>(); // Store a mapping between DisplayDevices and their default resolutions. private readonly Dictionary<DisplayDevice, int> deviceToDefaultResolution = new Dictionary<DisplayDevice, int>(); // Store a mapping between DisplayDevices and X11 screens. private readonly Dictionary<DisplayDevice, int> deviceToScreen = new Dictionary<DisplayDevice, int>(); // Keep the time when the config of each screen was last updated. private readonly List<IntPtr> lastConfigUpdate = new List<IntPtr>(); private bool xinerama_supported, xrandr_supported, xf86_supported; public X11DisplayDevice() { RefreshDisplayDevices(); } private void RefreshDisplayDevices() { using (new XLock(API.DefaultDisplay)) { List<DisplayDevice> devices = new List<DisplayDevice>(); xinerama_supported = false; try { xinerama_supported = QueryXinerama(devices); } catch { Debug.Print("Xinerama query failed."); } if (!xinerama_supported) { // We assume that devices are equivalent to the number of available screens. // Note: this won't work correctly in the case of distinct X servers. for (int i = 0; i < API.ScreenCount; i++) { DisplayDevice dev = new DisplayDevice(); dev.IsPrimary = i == Functions.XDefaultScreen(API.DefaultDisplay); devices.Add(dev); deviceToScreen.Add(dev, i); } } try { xrandr_supported = QueryXRandR(devices); } catch { } if (!xrandr_supported) { Debug.Print("XRandR query failed, falling back to XF86."); try { xf86_supported = QueryXF86(devices); } catch { } if (!xf86_supported) { Debug.Print("XF86 query failed, no DisplayDevice support available."); } } AvailableDevices.Clear(); AvailableDevices.AddRange(devices); Primary = FindDefaultDevice(devices); } } private static DisplayDevice FindDefaultDevice(IEnumerable<DisplayDevice> devices) { foreach (DisplayDevice dev in devices) { if (dev.IsPrimary) { return dev; } } throw new InvalidOperationException("No primary display found. Please file a bug at https://github.com/opentk/opentk/issues"); } private bool QueryXinerama(List<DisplayDevice> devices) { // Try to use Xinerama to obtain the geometry of all output devices. int event_base, error_base; if (NativeMethods.XineramaQueryExtension(API.DefaultDisplay, out event_base, out error_base) && NativeMethods.XineramaIsActive(API.DefaultDisplay)) { IList<XineramaScreenInfo> screens = NativeMethods.XineramaQueryScreens(API.DefaultDisplay); bool first = true; foreach (XineramaScreenInfo screen in screens) { DisplayDevice dev = new DisplayDevice(); dev.Bounds = new Rectangle(screen.X, screen.Y, screen.Width, screen.Height); if (first) { // We consider the first device returned by Xinerama as the primary one. // Makes sense conceptually, but is there a way to verify this? dev.IsPrimary = true; first = false; } devices.Add(dev); // It seems that all X screens are equal to 0 is Xinerama is enabled, at least on Nvidia (verify?) deviceToScreen.Add(dev, 0 /*screen.ScreenNumber*/); } } return (devices.Count > 0); } private bool QueryXRandR(List<DisplayDevice> devices) { // Get available resolutions. Then, for each resolution get all available rates. foreach (DisplayDevice dev in devices) { int screen = deviceToScreen[dev]; IntPtr timestamp_of_last_update; Functions.XRRTimes(API.DefaultDisplay, screen, out timestamp_of_last_update); lastConfigUpdate.Add(timestamp_of_last_update); List<DisplayResolution> available_res = new List<DisplayResolution>(); // Add info for a new screen. screenResolutionToIndex.Add(new Dictionary<DisplayResolution, int>()); int[] depths = FindAvailableDepths(screen); int resolution_count = 0; XRRScreenSize[] sizes = FindAvailableResolutions(screen); foreach (XRRScreenSize size in sizes) { if (size.Width == 0 || size.Height == 0) { Debug.Print("[Warning] XRandR returned an invalid resolution ({0}) for display device {1}", size, screen); continue; } short[] rates = null; rates = Functions.XRRRates(API.DefaultDisplay, screen, resolution_count); // It seems that XRRRates returns 0 for modes that are larger than the screen // can support, as well as for all supported modes. On Ubuntu 7.10 the tool // "Screens and Graphics" does report these modes, though. foreach (short rate in rates) { // Note: some X servers (like Xming on Windows) do not report any rates other than 0. // If we only have 1 rate, add it even if it is 0. if (rate != 0 || rates.Length == 1) { foreach (int depth in depths) { available_res.Add(new DisplayResolution(0, 0, size.Width, size.Height, depth, (float)rate)); } } } // Keep the index of this resolution - we will need it for resolution changes later. foreach (int depth in depths) { // Note that Xinerama may return multiple devices for a single screen. XRandR will // not distinguish between the two as far as resolutions are supported (since XRandR // operates on X screens, not display devices) - we need to be careful not to add the // same resolution twice! DisplayResolution res = new DisplayResolution(0, 0, size.Width, size.Height, depth, 0); if (!screenResolutionToIndex[screen].ContainsKey(res)) { screenResolutionToIndex[screen].Add(res, resolution_count); } } ++resolution_count; } // The resolution of the current DisplayDevice is discovered through XRRConfigCurrentConfiguration. // Its refresh rate is discovered by the FindCurrentRefreshRate call. // Its depth is discovered by the FindCurrentDepth call. float current_refresh_rate = FindCurrentRefreshRate(screen); int current_depth = FindCurrentDepth(screen); IntPtr screen_config = Functions.XRRGetScreenInfo(API.DefaultDisplay, Functions.XRootWindow(API.DefaultDisplay, screen)); ushort current_rotation; // Not needed. int current_sizes_index = Functions.XRRConfigCurrentConfiguration(screen_config, out current_rotation); if (dev.Bounds == Rectangle.Empty) { dev.Bounds = new Rectangle(0, 0, sizes[current_sizes_index].Width, sizes[current_sizes_index].Height); } dev.BitsPerPixel = current_depth; dev.RefreshRate = current_refresh_rate; dev.AvailableResolutions = available_res; deviceToDefaultResolution.Add(dev, current_sizes_index); } return true; } private bool QueryXF86(List<DisplayDevice> devices) { int major; int minor; try { if (!API.XF86VidModeQueryVersion(API.DefaultDisplay, out major, out minor)) { return false; } } catch (DllNotFoundException) { return false; } int currentScreen = 0; Debug.Print("Using XF86 v" + major.ToString() + "." + minor.ToString()); foreach (DisplayDevice dev in devices) { int count; IntPtr srcArray; API.XF86VidModeGetAllModeLines(API.DefaultDisplay, currentScreen, out count, out srcArray); Debug.Print(count.ToString() + " modes detected on screen " + currentScreen.ToString()); IntPtr[] array = new IntPtr[count]; Marshal.Copy(srcArray, array, 0, count); API.XF86VidModeModeInfo Mode = new API.XF86VidModeModeInfo(); int x; int y; API.XF86VidModeGetViewPort(API.DefaultDisplay, currentScreen, out x, out y); List<DisplayResolution> resolutions = new List<DisplayResolution>(); for (int i = 0; i < count; i++) { Mode = (API.XF86VidModeModeInfo)Marshal.PtrToStructure(array[i], typeof(API.XF86VidModeModeInfo)); resolutions.Add(new DisplayResolution(x, y, Mode.hdisplay, Mode.vdisplay, 24, (Mode.dotclock * 1000F) / (Mode.vtotal * Mode.htotal))); } dev.AvailableResolutions = resolutions; int pixelClock; API.XF86VidModeModeLine currentMode; API.XF86VidModeGetModeLine(API.DefaultDisplay, currentScreen, out pixelClock, out currentMode); dev.Bounds = new Rectangle(x, y, currentMode.hdisplay, (currentMode.vdisplay == 0) ? currentMode.vsyncstart : currentMode.vdisplay); dev.BitsPerPixel = FindCurrentDepth(currentScreen); dev.RefreshRate = (pixelClock * 1000F) / (currentMode.vtotal * currentMode.htotal); currentScreen++; } return true; } private static int[] FindAvailableDepths(int screen) { return Functions.XListDepths(API.DefaultDisplay, screen); } private static XRRScreenSize[] FindAvailableResolutions(int screen) { XRRScreenSize[] resolutions = null; resolutions = Functions.XRRSizes(API.DefaultDisplay, screen); if (resolutions == null) { throw new NotSupportedException("XRandR extensions not available."); } return resolutions; } private static float FindCurrentRefreshRate(int screen) { short rate = 0; IntPtr screen_config = Functions.XRRGetScreenInfo(API.DefaultDisplay, Functions.XRootWindow(API.DefaultDisplay, screen)); rate = Functions.XRRConfigCurrentRate(screen_config); Functions.XRRFreeScreenConfigInfo(screen_config); return (float)rate; } private static int FindCurrentDepth(int screen) { return (int)Functions.XDefaultDepth(API.DefaultDisplay, screen); } private bool ChangeResolutionXRandR(DisplayDevice device, DisplayResolution resolution) { using (new XLock(API.DefaultDisplay)) { int screen = deviceToScreen[device]; IntPtr root = Functions.XRootWindow(API.DefaultDisplay, screen); IntPtr screen_config = Functions.XRRGetScreenInfo(API.DefaultDisplay, root); ushort current_rotation; int current_resolution_index = Functions.XRRConfigCurrentConfiguration(screen_config, out current_rotation); int new_resolution_index; if (resolution != null) { new_resolution_index = screenResolutionToIndex[screen] [new DisplayResolution(0, 0, resolution.Width, resolution.Height, resolution.BitsPerPixel, 0)]; } else { new_resolution_index = deviceToDefaultResolution[device]; } Debug.Print("Changing size of screen {0} from {1} to {2}", screen, current_resolution_index, new_resolution_index); int ret = 0; short refresh_rate = (short)(resolution != null ? resolution.RefreshRate : 0); if (refresh_rate > 0) { ret = Functions.XRRSetScreenConfigAndRate(API.DefaultDisplay, screen_config, root, new_resolution_index, current_rotation, refresh_rate, IntPtr.Zero); } else { ret = Functions.XRRSetScreenConfig(API.DefaultDisplay, screen_config, root, new_resolution_index, current_rotation, IntPtr.Zero); } if (ret != 0) { Debug.Print("[Error] Change to resolution {0} failed with error {1}.", resolution, (ErrorCode)ret); } return ret == 0; } } private static bool ChangeResolutionXF86(DisplayDevice device, DisplayResolution resolution) { return false; } public sealed override bool TryChangeResolution(DisplayDevice device, DisplayResolution resolution) { // If resolution is null, restore the default resolution (new_resolution_index = 0). if (xrandr_supported) { return ChangeResolutionXRandR(device, resolution); } else if (xf86_supported) { return ChangeResolutionXF86(device, resolution); } else { return false; } } public sealed override bool TryRestoreResolution(DisplayDevice device) { return TryChangeResolution(device, null); } private static class NativeMethods { private const string Xinerama = "libXinerama"; [DllImport(Xinerama)] public static extern bool XineramaQueryExtension(IntPtr dpy, out int event_basep, out int error_basep); [DllImport(Xinerama)] public static extern int XineramaQueryVersion (IntPtr dpy, out int major_versionp, out int minor_versionp); [DllImport(Xinerama)] public static extern bool XineramaIsActive(IntPtr dpy); [DllImport(Xinerama)] private static extern IntPtr XineramaQueryScreens(IntPtr dpy, out int number); public static IList<XineramaScreenInfo> XineramaQueryScreens(IntPtr dpy) { int number; IntPtr screen_ptr = XineramaQueryScreens(dpy, out number); List<XineramaScreenInfo> screens = new List<XineramaScreenInfo>(number); unsafe { XineramaScreenInfo* ptr = (XineramaScreenInfo*)screen_ptr; while (--number >= 0) { screens.Add(*ptr); ptr++; } } return screens; } } [StructLayout(LayoutKind.Sequential, Pack = 1)] private struct XineramaScreenInfo { public int ScreenNumber; public short X; public short Y; public short Width; public short Height; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Factory.cs" company="Naos"> // Copyright (c) Naos 2017. All Rights Reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Naos.MessageBus.Test { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FakeItEasy; using Naos.Compression.Domain; using Naos.MessageBus.Domain; using Naos.Serialization.Factory; using OBeautifulCode.TypeRepresentation; internal class Factory { public static Func<IPostOffice> GetInMemorySender(List<Parcel> trackingSends) { Func<Parcel, TrackingCode> send = parcel => { trackingSends.Add(parcel); return null; }; var ret = A.Fake<IPostOffice>(); A.CallTo(ret) .Where(call => call.Method.Name == nameof(IPostOffice.Send)) .WithReturnType<TrackingCode>() .Invokes(call => send(call.Arguments.FirstOrDefault() as Parcel)); return () => ret; } public static Func<ICourier> GetInMemoryCourier(List<Crate> trackingSends) { Action<Crate> send = trackingSends.Add; var ret = A.Fake<ICourier>(); A.CallTo(ret) .Where(call => call.Method.Name == nameof(ICourier.Send)) .Invokes(call => send(call.Arguments.FirstOrDefault() as Crate)); return () => ret; } public static Func<IParcelTrackingSystem> GetInMemoryParcelTrackingSystem(List<string> trackingCalls, List<Parcel> trackingParcelsFromSent) { Action<string> track = trackingCalls.Add; var ret = A.Fake<IParcelTrackingSystem>(); A.CallTo(ret).WithReturnType<Task>().Invokes( call => { if (call.Method.Name == nameof(IParcelTrackingSystem.UpdateSentAsync)) { trackingParcelsFromSent.Add(call.Arguments.Skip(1).First() as Parcel); } track(call.Method.Name); }).Returns(Task.Run(() => { })); return () => ret; } public static IGetTrackingReports GetSeededTrackerForGetLatestNoticeAsync(Dictionary<ITopic, TopicStatusReport> data) { var tracker = A.Fake<IGetTrackingReports>(); foreach (var item in data) { A.CallTo(() => tracker.GetLatestTopicStatusReportAsync(item.Key, TopicStatus.None)).Returns(Task.FromResult(item.Value)); A.CallTo(() => tracker.GetLatestTopicStatusReportAsync(item.Key, TopicStatus.WasAffected)).Returns(Task.FromResult(item.Value)); } return tracker; } public static IGetTrackingReports GetRoundRobinStatusImplOfGetTrackingReportAsync(TrackingCode trackingCode, ParcelStatus[] parcelStatusesToRoundRobin, IList<string> trackingCalls = null) { return new RoundRobinStatusTracker(trackingCode, parcelStatusesToRoundRobin, trackingCalls ?? new List<string>()); } public static IGetTrackingReports GetSeededTrackerForGetTrackingReportAsync(IReadOnlyCollection<Tuple<TrackingCode[], List<ParcelTrackingReport>>> data) { var ret = new SeededTracker(data); return ret; /* * Totally does not work because it can't match on the array in the CallTo signature and tries to create a fake IReadOnlyCollection * this is why I just use a mock where i can match the inputs to the seed data map. var tracker = A.Dummy<IGetTrackingReports>(); foreach (var item in data) { A.CallTo(() => tracker.GetTrackingReportAsync(item.Item1)).Returns(Task.FromResult((IReadOnlyCollection<ParcelTrackingReport>)item.Item2)); } return tracker; */ } public static IStuffAndOpenEnvelopes GetEnvelopeMachine() { return new EnvelopeMachine( PostOffice.MessageSerializationDescription, SerializerFactory.Instance, CompressorFactory.Instance, TypeMatchStrategy.NamespaceAndName); } public static IManageShares GetShareManager() { return new ShareManager(SerializerFactory.Instance, CompressorFactory.Instance, TypeMatchStrategy.NamespaceAndName); } public static IPostOffice GetInMemoryParcelTrackingSystemBackedPostOffice(List<string> trackingCalls, List<Parcel> trackingSends) { var parcelTrackingSystemBuilder = Factory.GetInMemoryParcelTrackingSystem(trackingCalls, trackingSends); var envelopeMachine = Factory.GetEnvelopeMachine(); var ret = new PostOffice( parcelTrackingSystemBuilder(), new ChannelRouter(new NullChannel()), envelopeMachine); return ret; } public class SeededTracker : IGetTrackingReports { private readonly IReadOnlyCollection<Tuple<TrackingCode[], List<ParcelTrackingReport>>> seedData; public SeededTracker(IReadOnlyCollection<Tuple<TrackingCode[], List<ParcelTrackingReport>>> seedData) { this.seedData = seedData; } /// <inheritdoc /> public async Task<IReadOnlyCollection<ParcelTrackingReport>> GetTrackingReportAsync(IReadOnlyCollection<TrackingCode> trackingCodes) { var ret = this.seedData.SingleOrDefault(_ => _.Item1.Length == trackingCodes.Count && _.Item1.All(trackingCodes.Contains))?.Item2; return await Task.FromResult(ret ?? new List<ParcelTrackingReport>()); } /// <inheritdoc /> public Task<TopicStatusReport> GetLatestTopicStatusReportAsync(ITopic topic, TopicStatus statusFilter = TopicStatus.None) { throw new NotImplementedException(); } } public class RoundRobinStatusTracker : IGetTrackingReports { private readonly TrackingCode trackingCode; private readonly ParcelStatus[] parcelStatusesToRoundRobin; private readonly IList<string> trackingCalls; private int index; public RoundRobinStatusTracker() { } public RoundRobinStatusTracker(TrackingCode trackingCode, ParcelStatus[] parcelStatusesToRoundRobin, IList<string> trackingCalls) { this.trackingCode = trackingCode; this.parcelStatusesToRoundRobin = parcelStatusesToRoundRobin; this.trackingCalls = trackingCalls; this.index = 0; } /// <inheritdoc /> public async Task<IReadOnlyCollection<ParcelTrackingReport>> GetTrackingReportAsync(IReadOnlyCollection<TrackingCode> trackingCodes) { this.trackingCalls.Add(nameof(IGetTrackingReports.GetTrackingReportAsync)); var status = this.parcelStatusesToRoundRobin[this.index]; this.index = this.index + 1; var ret = new ParcelTrackingReport { CurrentTrackingCode = this.trackingCode, ParcelId = this.trackingCode.ParcelId, Status = status, LastUpdatedUtc = DateTime.UtcNow }; return await Task.FromResult(new[] { ret }); } /// <inheritdoc /> public Task<TopicStatusReport> GetLatestTopicStatusReportAsync(ITopic topic, TopicStatus statusFilter = TopicStatus.None) { throw new NotImplementedException(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using Newtonsoft.Json; using System.Collections.Concurrent; using System.Threading; using System.Diagnostics; namespace SimpleDB { public static class SimpleDB { private static ConcurrentQueue<Task> _queue = new ConcurrentQueue<Task>(); private static string _idPropertyName = "_Id"; private static List<string> _openDocuments = new List<string>(); private static bool _initialized = false; public static string Database { get; set; } public static string BaseUrl { get; set; } public static string IdPropertyName { get { return _idPropertyName; } set { _idPropertyName = value; } } public static bool Initialized { get { return _initialized; } } public static void Initialize() { _initialized = true; // Process queue /* new Thread(() => { Thread.CurrentThread.IsBackground = true; while (true) { while (!_queue.IsEmpty) { Task task; _queue.TryDequeue(out task); if (task != null) { task.RunSynchronously(); } } } }).Start();*/ } public static void Store<T>(T item) { string id = GetId<T>(item); if (String.IsNullOrEmpty(id)) return; _queue.Enqueue(new Task(() => { List<T> data = OpenDocument<T>(); if (data.Where(i => GetId<T>(i) == id).Count() > 0) return; data.Add(item); SaveDocument<T>(data); })); RunQueue(); } public static T Get<T>(string id) { List<T> data = OpenDocument<T>(); return data.Where(i => GetId<T>(i) == id).SingleOrDefault(); } public static void Update<T>(T item) { string id = GetId<T>(item); if (String.IsNullOrEmpty(id)) return; _queue.Enqueue(new Task(() => { List<T> data = OpenDocument<T>(); T oldItem = data.Where(i => GetId<T>(i) == id).SingleOrDefault(); if (oldItem == null) return; int index = data.IndexOf(oldItem); data[index] = item; SaveDocument<T>(data); })); RunQueue(); } public static void Delete<T>(T item) { string id = GetId<T>(item); if (String.IsNullOrEmpty(id)) return; _queue.Enqueue(new Task(() => { List<T> data = OpenDocument<T>(); T oldItem = data.Where(i => GetId<T>(i) == id).SingleOrDefault(); if (oldItem == null) return; data.Remove(oldItem); SaveDocument<T>(data); })); RunQueue(); } public static IQueryable<T> Query<T>() { return OpenDocument<T>().AsQueryable<T>(); } private static List<T> OpenDocument<T>() { string name = GetName<T>(); if (!DocumentExists<T>()) CreateDocument<T>(); while (true) { try { using (var streamReader = new StreamReader(BaseUrl + "\\" + Database + "\\" + name + ".json")) { return JsonConvert.DeserializeObject<List<T>>(streamReader.ReadToEnd()); } } catch (Exception e) { // File is locked ... Debug.WriteLine("File locked ..."); } } } private static void SaveDocument<T>(List<T> data) { string name = GetName<T>(); if (!DocumentExists<T>()) CreateDocument<T>(); while (true) { try { using (var fileStream = File.Create(BaseUrl + "\\" + Database + "\\" + name + ".json")) { using (var streamWriter = new StreamWriter(fileStream)) { streamWriter.Write(JsonConvert.SerializeObject(data)); break; } } } catch (Exception e) { // File is locked ... Debug.WriteLine("File locked ..."); } } } private static bool DocumentExists<T>() { return File.Exists(BaseUrl + "\\" + Database + "\\" + GetName<T>() + ".json"); } private static void CreateDocument<T>() { List<T> emptyList = new List<T>(); using (var fileStream = File.Create(BaseUrl + "\\" + Database + "\\" + GetName<T>() + ".json")) { using (var streamWriter = new StreamWriter(fileStream)) { streamWriter.Write(JsonConvert.SerializeObject(emptyList)); } } } private static string GetName<T>() { return typeof(T).Name; } private static string GetId<T>(T item) { Type type = typeof(T); var propertyInfo = type.GetProperty(IdPropertyName); return propertyInfo.GetValue(item) as String; } private static void RunQueue() { while (!_queue.IsEmpty) { Task task; _queue.TryDequeue(out task); if (task != null) { task.RunSynchronously(); } } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.Providers.Streams.AzureQueue; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.TestingHost; using Orleans.TestingHost.Utils; using Tester; using TestExtensions; using UnitTests.GrainInterfaces; using UnitTests.StreamingTests; using Xunit; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Orleans.Hosting; using Microsoft.Extensions.Options; using Orleans.Configuration; using Tester.AzureUtils.Streaming; namespace UnitTests.HaloTests.Streaming { [TestCategory("Streaming"), TestCategory("Halo")] public class HaloStreamSubscribeTests : OrleansTestingBase, IClassFixture<HaloStreamSubscribeTests.Fixture>, IDisposable { private readonly Fixture fixture; private const int queueCount = 8; public class Fixture : BaseAzureTestClusterFixture { public const string AzureQueueStreamProviderName = StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME; public const string SmsStreamProviderName = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME; protected override void ConfigureTestCluster(TestClusterBuilder builder) { builder.AddSiloBuilderConfigurator<SiloBuilderConfigurator>(); } private class SiloBuilderConfigurator : ISiloBuilderConfigurator { public void Configure(ISiloHostBuilder hostBuilder) { hostBuilder .AddMemoryGrainStorage("MemoryStore", options => options.NumStorageGrains = 1) .AddAzureTableGrainStorage("AzureStore", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) => { options.ConnectionString = TestDefaultConfiguration.DataConnectionString; options.DeleteStateOnClear = true; })) .AddSimpleMessageStreamProvider(SmsStreamProviderName) .AddSimpleMessageStreamProvider("SMSProviderDoNotOptimizeForImmutableData", options => options.OptimizeForImmutableData = false) .AddAzureTableGrainStorage("PubSubStore", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) => { options.DeleteStateOnClear = true; options.ConnectionString = TestDefaultConfiguration.DataConnectionString; })) .AddAzureQueueStreams(AzureQueueStreamProviderName, b=>b .ConfigureAzureQueue(ob => ob.Configure<IOptions<ClusterOptions>>( (options, dep) => { options.ConnectionString = TestDefaultConfiguration.DataConnectionString; options.QueueNames = AzureQueueUtilities.GenerateQueueNames(dep.Value.ClusterId, queueCount); }))); hostBuilder .AddAzureQueueStreams("AzureQueueProvider2", b=>b .ConfigureAzureQueue(ob => ob.Configure<IOptions<ClusterOptions>>( (options, dep) => { options.ConnectionString = TestDefaultConfiguration.DataConnectionString; options.QueueNames = AzureQueueUtilities.GenerateQueueNames($"{dep.Value.ClusterId}2", queueCount); }))); } } public override void Dispose() { base.Dispose(); AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(NullLoggerFactory.Instance, AzureQueueUtilities.GenerateQueueNames(this.HostedCluster.Options.ClusterId, queueCount), TestDefaultConfiguration.DataConnectionString).Wait(); AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(NullLoggerFactory.Instance, AzureQueueUtilities.GenerateQueueNames($"{this.HostedCluster.Options.ClusterId}2", queueCount), TestDefaultConfiguration.DataConnectionString).Wait(); } } protected TestCluster HostedCluster { get; } private const string SmsStreamProviderName = Fixture.SmsStreamProviderName; private const string AzureQueueStreamProviderName = Fixture.AzureQueueStreamProviderName; private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); private Guid _streamId; private string _streamProvider; private readonly ILoggerFactory loggerFactory; public HaloStreamSubscribeTests(Fixture fixture) { this.fixture = fixture; HostedCluster = fixture.HostedCluster; fixture.EnsurePreconditionsMet(); this.loggerFactory = fixture.HostedCluster.ServiceProvider.GetService<ILoggerFactory>(); } public void Dispose() { AzureQueueStreamProviderUtils.ClearAllUsedAzureQueues(NullLoggerFactory.Instance, AzureQueueUtilities.GenerateQueueNames(this.HostedCluster.Options.ClusterId, queueCount), TestDefaultConfiguration.DataConnectionString).Wait(); AzureQueueStreamProviderUtils.ClearAllUsedAzureQueues(NullLoggerFactory.Instance, AzureQueueUtilities.GenerateQueueNames($"{this.HostedCluster.Options.ClusterId}2", queueCount), TestDefaultConfiguration.DataConnectionString).Wait(); } [SkippableFact, TestCategory("Functional")] public async Task Halo_SMS_ResubscribeTest_ConsumerProducer() { this.fixture.Logger.Info("\n\n************************ Halo_SMS_ResubscribeTest_ConsumerProducer ********************************* \n\n"); _streamId = Guid.NewGuid(); _streamProvider = SmsStreamProviderName; Guid consumerGuid = Guid.NewGuid(); Guid producerGuid = Guid.NewGuid(); await ConsumerProducerTest(consumerGuid, producerGuid); await ConsumerProducerTest(consumerGuid, producerGuid); } [SkippableFact, TestCategory("Functional")] public async Task Halo_SMS_ResubscribeTest_ProducerConsumer() { this.fixture.Logger.Info("\n\n************************ Halo_SMS_ResubscribeTest_ProducerConsumer ********************************* \n\n"); _streamId = Guid.NewGuid(); _streamProvider = SmsStreamProviderName; Guid producerGuid = Guid.NewGuid(); Guid consumerGuid = Guid.NewGuid(); await ProducerConsumerTest(producerGuid, consumerGuid); await ProducerConsumerTest(producerGuid, consumerGuid); } [SkippableFact, TestCategory("Functional")] public async Task Halo_AzureQueue_ResubscribeTest_ConsumerProducer() { this.fixture.Logger.Info("\n\n************************ Halo_AzureQueue_ResubscribeTest_ConsumerProducer ********************************* \n\n"); _streamId = Guid.NewGuid(); _streamProvider = AzureQueueStreamProviderName; Guid consumerGuid = Guid.NewGuid(); Guid producerGuid = Guid.NewGuid(); await ConsumerProducerTest(consumerGuid, producerGuid); await ConsumerProducerTest(consumerGuid, producerGuid); } [SkippableFact, TestCategory("Functional")] public async Task Halo_AzureQueue_ResubscribeTest_ProducerConsumer() { this.fixture.Logger.Info("\n\n************************ Halo_AzureQueue_ResubscribeTest_ProducerConsumer ********************************* \n\n"); _streamId = Guid.NewGuid(); _streamProvider = AzureQueueStreamProviderName; Guid producerGuid = Guid.NewGuid(); Guid consumerGuid = Guid.NewGuid(); await ProducerConsumerTest(producerGuid, consumerGuid); await ProducerConsumerTest(producerGuid, consumerGuid); } private async Task ConsumerProducerTest(Guid consumerGuid, Guid producerGuid) { // consumer joins first, producer later IConsumerEventCountingGrain consumer = this.fixture.GrainFactory.GetGrain<IConsumerEventCountingGrain>(consumerGuid); await consumer.BecomeConsumer(_streamId, _streamProvider); IProducerEventCountingGrain producer = this.fixture.GrainFactory.GetGrain<IProducerEventCountingGrain>(producerGuid); await producer.BecomeProducer(_streamId, _streamProvider); await producer.SendEvent(); await Task.Delay(1000); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer), Timeout); await consumer.StopConsuming(); } private async Task ProducerConsumerTest(Guid producerGuid, Guid consumerGuid) { // producer joins first, consumer later IProducerEventCountingGrain producer = this.fixture.GrainFactory.GetGrain<IProducerEventCountingGrain>(producerGuid); await producer.BecomeProducer(_streamId, _streamProvider); IConsumerEventCountingGrain consumer = this.fixture.GrainFactory.GetGrain<IConsumerEventCountingGrain>(consumerGuid); await consumer.BecomeConsumer(_streamId, _streamProvider); await producer.SendEvent(); await Task.Delay(1000); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer), Timeout); await consumer.StopConsuming(); } private async Task<bool> CheckCounters(IProducerEventCountingGrain producer, IConsumerEventCountingGrain consumer) { var numProduced = await producer.GetNumberProduced(); var numConsumed = await consumer.GetNumberConsumed(); this.fixture.Logger.Info("CheckCounters: numProduced = {0}, numConsumed = {1}", numProduced, numConsumed); return numProduced == numConsumed; } } }
using System; using UnityEngine; using System.Collections; using System.Collections.Generic; public class FAtlasManager { static private int _nextAtlasIndex; private List<FAtlas> _atlases = new List<FAtlas>(); private Dictionary<string, FAtlasElement> _allElementsByName = new Dictionary<string, FAtlasElement>(); private List<FFont> _fonts = new List<FFont>(); private Dictionary<string,FFont> _fontsByName = new Dictionary<string, FFont>(); public FAtlasManager () //new DAtlasManager() called by Futile { } public FAtlas GetAtlasWithName(string name) { int atlasCount = _atlases.Count; for(int a = 0; a<atlasCount; ++a) { if(_atlases[a].name == name) return _atlases[a]; } return null; } public bool DoesContainAtlas(string name) { int atlasCount = _atlases.Count; for(int a = 0; a<atlasCount; ++a) { if(_atlases[a].name == name) return true; } return false; } public void LoadAtlasFromTexture (string name, Texture texture) { if(DoesContainAtlas(name)) return; //we already have it, don't load it again FAtlas atlas = new FAtlas(name, texture, _nextAtlasIndex++); AddAtlas(atlas); } public void LoadAtlasFromTexture (string name, string dataPath, Texture texture) { if(DoesContainAtlas(name)) return; //we already have it, don't load it again FAtlas atlas = new FAtlas(name, dataPath, texture, _nextAtlasIndex++); AddAtlas(atlas); } public void ActuallyLoadAtlasOrImage(string name, string imagePath, string dataPath) { if(DoesContainAtlas(name)) return; //we already have it, don't load it again //if dataPath is empty, load it as a single image bool isSingleImage = (dataPath == ""); FAtlas atlas = new FAtlas(name, imagePath, dataPath, _nextAtlasIndex++, isSingleImage); AddAtlas(atlas); } private void AddAtlas(FAtlas atlas) { int elementCount = atlas.elements.Count; for(int e = 0; e<elementCount; ++e) { FAtlasElement element = atlas.elements[e]; element.atlas = atlas; element.atlasIndex = atlas.index; if(_allElementsByName.ContainsKey(element.name)) { throw new FutileException("Duplicate element name '" + element.name +"' found! All element names must be unique!"); } else { _allElementsByName.Add (element.name, element); } } _atlases.Add(atlas); } public void LoadAtlas(string atlasPath) { if(DoesContainAtlas(atlasPath)) return; //we already have it, don't load it again string filePath = atlasPath+Futile.resourceSuffix+"_png"; TextAsset imageBytes = Resources.Load (filePath, typeof(TextAsset)) as TextAsset; if(imageBytes != null) //do we have png bytes? { Texture2D texture = new Texture2D(0,0,TextureFormat.ARGB32,false); texture.LoadImage(imageBytes.bytes); Resources.UnloadAsset(imageBytes); LoadAtlasFromTexture(atlasPath,atlasPath+Futile.resourceSuffix, texture); } else //load it as a normal Unity image asset { ActuallyLoadAtlasOrImage(atlasPath, atlasPath+Futile.resourceSuffix, atlasPath+Futile.resourceSuffix); } } public void LoadImage(string imagePath) { if(DoesContainAtlas(imagePath)) return; //we already have it string filePath = imagePath+Futile.resourceSuffix+"_png"; TextAsset imageBytes = Resources.Load (filePath, typeof(TextAsset)) as TextAsset; if(imageBytes != null) //do we have png bytes? { Texture2D texture = new Texture2D(0,0,TextureFormat.ARGB32,false); texture.LoadImage(imageBytes.bytes); Resources.UnloadAsset(imageBytes); LoadAtlasFromTexture(imagePath, texture); } else //load it as a normal Unity image asset { ActuallyLoadAtlasOrImage(imagePath, imagePath+Futile.resourceSuffix,""); } } public void ActuallyUnloadAtlasOrImage(string name) { bool wasAtlasRemoved = false; int atlasCount = _atlases.Count; for(int a = atlasCount-1; a>=0; a--) //reverse order so deletions ain't no thang { FAtlas atlas = _atlases[a]; if(atlas.name == name) { int elementCount = atlas.elements.Count; for(int e = 0; e<elementCount; e++) { _allElementsByName.Remove(atlas.elements[e].name); } atlas.Unload(); _atlases.RemoveAt(a); wasAtlasRemoved = true; } } if(wasAtlasRemoved) { Futile.stage.renderer.Clear(); Resources.UnloadUnusedAssets(); } } public void UnloadAtlas(string atlasPath) { ActuallyUnloadAtlasOrImage(atlasPath); } public void UnloadImage(string imagePath) { ActuallyUnloadAtlasOrImage(imagePath); } public FAtlasElement GetElementWithName (string elementName) { if (_allElementsByName.ContainsKey(elementName)) { return _allElementsByName [elementName]; } else { //Try to make an educated guess about what they were trying to load //First we get the last part of the path (the file name) and then we remove the extension //Then we check to see if that string is in any of our element names //(perhaps they have the path wrong or are mistakenly using a .png extension) String lastChunk = null; if(elementName.Contains("\\")) { String[] chunks = elementName.Split('\\'); lastChunk = chunks[chunks.Length-1]; } else { String[] chunks = elementName.Split('/'); lastChunk = chunks[chunks.Length-1]; } String replacementName = null; if(lastChunk != null) { lastChunk = lastChunk.Split('.')[0]; //remove the extension foreach(KeyValuePair<String, FAtlasElement> pair in _allElementsByName) { if(pair.Value.name.Contains(lastChunk)) { replacementName = pair.Value.name; } } } if(replacementName == null) { throw new FutileException("Couldn't find element named '" + elementName + "'. \nUse Futile.atlasManager.LogAllElementNames() to see a list of all loaded elements names"); } else { throw new FutileException("Couldn't find element named '" + elementName + "'. Did you mean '" + replacementName + "'? \nUse Futile.atlasManager.LogAllElementNames() to see a list of all loaded element names."); } } } public FFont GetFontWithName(string fontName) { if(_fontsByName.ContainsKey(fontName)) { return _fontsByName[fontName]; } else { throw new FutileException("Couldn't find font named '"+fontName+"'"); } } public void LoadFont (string name, string elementName, string configPath, float offsetX, float offsetY) { LoadFont (name,elementName,configPath, offsetX, offsetY, new FTextParams()); } public void LoadFont (string name, string elementName, string configPath, float offsetX, float offsetY, FTextParams textParams) { FAtlasElement element = GetElementWithName(elementName); FFont font = new FFont(name,element,configPath, offsetX, offsetY, textParams); _fonts.Add(font); _fontsByName.Add (name, font); } public void LogAllElementNames() { Debug.Log("Logging all element names:"); foreach(KeyValuePair<String,FAtlasElement> pair in _allElementsByName) { Debug.Log("'"+pair.Value.name+"'"); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsPaging { using Fixtures.Azure; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// PagingOperations operations. /// </summary> public partial interface IPagingOperations { /// <summary> /// A paging operation that finishes on the first call without a /// nextlink /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetSinglePagesWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetMultiplePagesOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesWithHttpMessagesAsync(string clientRequestId = default(string), PagingGetMultiplePagesOptionsInner pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptionsInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that includes a nextLink in odata format that /// has 10 pages /// </summary> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetOdataMultiplePagesOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetOdataMultiplePagesWithHttpMessagesAsync(string clientRequestId = default(string), PagingGetOdataMultiplePagesOptionsInner pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptionsInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='pagingGetMultiplePagesWithOffsetOptions'> /// Additional parameters for the operation /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesWithOffsetWithHttpMessagesAsync(PagingGetMultiplePagesWithOffsetOptionsInner pagingGetMultiplePagesWithOffsetOptions, string clientRequestId = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that fails on the first call with 500 and then /// retries and then get a response including a nextLink that has 10 /// pages /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesRetryFirstWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of /// which the 2nd call fails first with 500. The client should retry /// and finish all 10 pages eventually. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesRetrySecondWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that receives a 400 on the first call /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetSinglePagesFailureWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that receives a 400 on the second call /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFailureWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that receives an invalid nextLink /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFailureUriWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that doesn't return a full URL, just a fragment /// </summary> /// <param name='apiVersion'> /// Sets the api version to use. /// </param> /// <param name='tenant'> /// Sets the tenant to use. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFragmentNextLinkWithHttpMessagesAsync(string apiVersion, string tenant, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that doesn't return a full URL, just a fragment /// with parameters grouped /// </summary> /// <param name='customParameterGroup'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFragmentWithGroupingNextLinkWithHttpMessagesAsync(CustomParameterGroupInner customParameterGroup, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that doesn't return a full URL, just a fragment /// </summary> /// <param name='apiVersion'> /// Sets the api version to use. /// </param> /// <param name='tenant'> /// Sets the tenant to use. /// </param> /// <param name='nextLink'> /// Next link for list operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> NextFragmentWithHttpMessagesAsync(string apiVersion, string tenant, string nextLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that doesn't return a full URL, just a fragment /// </summary> /// <param name='nextLink'> /// Next link for list operation. /// </param> /// <param name='customParameterGroup'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> NextFragmentWithGroupingWithHttpMessagesAsync(string nextLink, CustomParameterGroupInner customParameterGroup, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that finishes on the first call without a /// nextlink /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetSinglePagesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetMultiplePagesOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesNextWithHttpMessagesAsync(string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesOptionsInner pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptionsInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that includes a nextLink in odata format that /// has 10 pages /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetOdataMultiplePagesOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetOdataMultiplePagesNextWithHttpMessagesAsync(string nextPageLink, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptionsInner pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptionsInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetMultiplePagesWithOffsetNextOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesWithOffsetNextWithHttpMessagesAsync(string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesWithOffsetNextOptionsInner pagingGetMultiplePagesWithOffsetNextOptions = default(PagingGetMultiplePagesWithOffsetNextOptionsInner), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that fails on the first call with 500 and then /// retries and then get a response including a nextLink that has 10 /// pages /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesRetryFirstNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of /// which the 2nd call fails first with 500. The client should retry /// and finish all 10 pages eventually. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesRetrySecondNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that receives a 400 on the first call /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetSinglePagesFailureNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that receives a 400 on the second call /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFailureNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A paging operation that receives an invalid nextLink /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFailureUriNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Text; using Hydra.Framework; namespace Hydra.SharedCache.Common { // // ********************************************************************** /// <summary> /// <b>Manage Data which expires in cache based on provided DateTime</b> /// </summary> // ********************************************************************** // public class CacheExpire { #region Member Variables // // ********************************************************************** /// <summary> /// Defines a dic object with a <see cref="string"/> and <see cref="DateTime"/>. /// </summary> // ********************************************************************** // private static Dictionary<string, DateTime> expireTable = null; // // ********************************************************************** /// <summary> /// defines a bulk <see cref="object"/> to manage concurrency. /// </summary> // ********************************************************************** // private static object bulkObject = new object(); private bool enable = false; // // ********************************************************************** /// <summary> /// Gets/sets the Enable /// </summary> // ********************************************************************** // public bool Enable { [System.Diagnostics.DebuggerStepThrough] get { return this.enable; } [System.Diagnostics.DebuggerStepThrough] set { this.enable = value; } } #endregion // // ********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="CacheExpire"/> class. /// </summary> /// <param name="enable">if set to <c>true</c> [enable].</param> // ********************************************************************** // public CacheExpire(bool enable) { this.enable = enable; expireTable = new Dictionary<string, DateTime>(); } // // ********************************************************************** /// <summary> /// Dumps the cache item at. /// If key is already available, it will update the expire date and time. /// </summary> /// <param name="key">The key. A <see cref="T:System.String"/> Object.</param> /// <param name="expire">The expire. A <see cref="T:System.DateTime"/> Object.</param> // ********************************************************************** // public void DumpCacheItemAt(string key, DateTime expire) { // // check to extend the expire date // if (expireTable.ContainsKey(key)) { lock (bulkObject) { expireTable[key] = expire; } } else { // // first time // lock (bulkObject) { expireTable.Add(key, expire); } } } // // ********************************************************************** /// <summary> /// Clear all items within the expiry table. /// </summary> // ********************************************************************** // public void Clear() { lock (bulkObject) { expireTable.Clear(); } GC.Collect(); } // // ********************************************************************** /// <summary> /// Removes the specified key. /// </summary> /// <param name="key">The key. A <see cref="T:System.String"/> Object.</param> // ********************************************************************** // public void Remove(string key) { if (expireTable.ContainsKey(key)) { lock (bulkObject) { expireTable.Remove(key); } GC.WaitForPendingFinalizers(); } } // // ********************************************************************** /// <summary> /// Check if an Item within cache is already expired upon Get Request /// </summary> /// <param name="key"></param> /// <returns></returns> // ********************************************************************** // public bool CheckExpired(string key) { if (expireTable.ContainsKey(key)) { DateTime dt = DateTime.MinValue; lock (bulkObject) { dt = expireTable[key]; } if (DateTime.Now > dt) { return true; } } return false; } // // ********************************************************************** /// <summary> /// Check if an Item within cache is already expired upon Get Request /// </summary> /// <param name="key"></param> /// <returns></returns> // ********************************************************************** // public DateTime GetExpireDateTime(string key) { if (expireTable.ContainsKey(key)) { DateTime dt = DateTime.MinValue; lock (bulkObject) { dt = expireTable[key]; } return dt; } return DateTime.MinValue; } // // ********************************************************************** /// <summary> /// Returns a list of <see cref="string"/> with key's to clean up from /// the cache. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.List&lt;System.String&gt;"/> Object. /// </returns> // ********************************************************************** // public List<string> CleanUp() { Dictionary<string, DateTime> dict = null; List<string> result = new List<string>(); // // create a copy of current status. // lock (bulkObject) { dict = new Dictionary<string, DateTime>(expireTable); } if (dict != null) { foreach (KeyValuePair<string, DateTime> kpv in dict) { // // QuickFix // if (kpv.Value != DateTime.MaxValue) { // // kpv.Value contains the datetime when this item // needs to expire // if (DateTime.Now > kpv.Value) { result.Add(kpv.Key); } } } } return result; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using gView.Framework.UI; using gView.Framework.Data; using gView.Explorer.UI; using gView.Framework.FDB; using gView.Framework.system; using gView.Framework.system.UI; using System.Threading; using gView.Framework.UI.Dialogs; using gView.Framework.Geometry; using gView.Framework.Carto; using gView.Framework.Globalisation; using gView.DataSources.Fdb.UI; using gView.Framework.UI.Controls.Filter; using gView.DataSources.Fdb.MSAccess; namespace gView.Plugins.DbTools.Export { public partial class ExportFeatureClassDialog : Form { private IFeatureClass _sourceFeatureClass = null; private int _panelIndex = 0; private FeatureClassListViewItem _listViewItem; public ExportFeatureClassDialog(IDisplay display, IFeatureLayer sourceFeatureLayer) { InitializeComponent(); _sourceFeatureClass = sourceFeatureLayer.Class as IFeatureClass; #region Filter //All Features //Selected Features //Features in actual extent cmbExport.Items.Add(new ExportMethodItem("All Features", null)); if (sourceFeatureLayer is IFeatureSelection && ((IFeatureSelection)sourceFeatureLayer).SelectionSet != null && ((IFeatureSelection)sourceFeatureLayer).SelectionSet.Count > 0) { ISelectionSet selectionSet = ((IFeatureSelection)sourceFeatureLayer).SelectionSet; IQueryFilter selFilter = null; if (selectionSet is IIDSelectionSet) { selFilter = new RowIDFilter(_sourceFeatureClass.IDFieldName, ((IIDSelectionSet)selectionSet).IDs); } else if (selectionSet is IGlobalIDSelectionSet) { selFilter = new GlobalRowIDFilter(_sourceFeatureClass.IDFieldName, ((IGlobalIDSelectionSet)selectionSet).IDs); } else if (selectionSet is IQueryFilteredSelectionSet) { selFilter = ((IQueryFilteredSelectionSet)selectionSet).QueryFilter.Clone() as IQueryFilter; } if (selFilter != null) { selFilter.SubFields = "*"; ExportMethodItem item = new ExportMethodItem("Selected Features", selFilter); cmbExport.Items.Add(item); cmbExport.SelectedItem = item; } } if (display != null && display.Envelope != null) { SpatialFilter dispFilter = new SpatialFilter(); dispFilter.SubFields = "*"; dispFilter.FilterSpatialReference = display.SpatialReference; dispFilter.Geometry = display.Envelope; dispFilter.SpatialRelation = spatialRelation.SpatialRelationIntersects; cmbExport.Items.Add(new ExportMethodItem("Features in actual extent", dispFilter)); } if (cmbExport.SelectedIndex == -1) cmbExport.SelectedIndex = 0; #endregion _listViewItem = new FeatureClassListViewItem(_sourceFeatureClass, 255); gvFields.DataSource = _listViewItem.Fields; panelStep1.Dock = panelStep2.Dock = DockStyle.Fill; SetPanelVisibity(); } private void btnSelect_Click(object sender, EventArgs e) { List<ExplorerDialogFilter> filters = new List<ExplorerDialogFilter>(); filters.Add(new OpenFeatureDatasetFilter()); ExplorerDialog exDlg = new ExplorerDialog("New Target Featureclass", SaveFeatureClassFilters.AllFilters, false); if (exDlg.ShowDialog() == DialogResult.OK && exDlg.ExplorerObjects.Count == 1) { IExplorerObject parentObject = exDlg.ExplorerObjects[0]; if (parentObject.Object is IFeatureDataset && ((IDataset)parentObject.Object).Database is IFeatureUpdater) { _dataset = (IFeatureDataset)parentObject.Object; } else if (exDlg.SelectedExplorerDialogFilter.FilterObject is IFeatureDataset && ((IDataset)exDlg.SelectedExplorerDialogFilter.FilterObject).Database is IFileFeatureDatabase) { IFileFeatureDatabase fileDB = (IFileFeatureDatabase)((IFeatureDataset)exDlg.SelectedExplorerDialogFilter.FilterObject).Database; _dataset = fileDB[parentObject.FullName]; } else { MessageBox.Show("Can't determine target featureclass!"); return; } txtDatasetName.Text = _dataset.Database.ToString(); txtDatasetLocation.Text = parentObject.FullName; txtTargetClass.Text = _listViewItem.TargetName = exDlg.TargetName; } btnNext.Enabled = exDlg.TargetName != String.Empty; } private void btnNext_Click(object sender, EventArgs e) { if (btnNext.Text == LocalizedResources.GetResString("String.Export", "Export")) { if (_listViewItem != null) { ExportDatasetObject(_listViewItem); _destDatasetElement = _dataset[_listViewItem.TargetName]; this.DialogResult = DialogResult.OK; this.Close(); } } else { _panelIndex++; SetPanelVisibity(); } } private void btnBack_Click(object sender, EventArgs e) { _panelIndex--; SetPanelVisibity(); } private void cmbExport_SelectedIndexChanged(object sender, EventArgs e) { if (cmbExport.SelectedItem is ExportMethodItem) { _filter = ((ExportMethodItem)cmbExport.SelectedItem).QueryFilter; } } private void SetPanelVisibity() { switch (_panelIndex) { case 0: panelStep2.Visible = false; panelStep1.Visible = true; btnBack.Visible = false; btnNext.Enabled = (txtTargetClass.Text != String.Empty); btnNext.Text = LocalizedResources.GetResString("String.Next", "Next") + " >"; break; case 1: panelStep1.Visible = false; panelStep2.Visible = true; btnBack.Visible = true; btnNext.Text = LocalizedResources.GetResString("String.Export", "Export"); if (_listViewItem.MaxFieldLength > MaximumFieldLength(_dataset)) { _listViewItem = new FeatureClassListViewItem(_sourceFeatureClass, MaximumFieldLength(_dataset)); gvFields.DataSource = _listViewItem.Fields; } break; } } private IDatasetElement _destDatasetElement = null; public IDatasetElement DestinationDatasetElement { get { return _destDatasetElement; } } #region Helper private int MaximumFieldLength(IDataset dataset) { MaximumFieldnameLength maxLength = Attribute.GetCustomAttribute(dataset.GetType(), typeof(MaximumFieldnameLength)) as MaximumFieldnameLength; if (maxLength != null) return maxLength.Value; return 255; } private class ExportMethodItem { private string _text; private IQueryFilter _filter; public ExportMethodItem(string text, IQueryFilter filter) { _text = text; _filter = filter; } public IQueryFilter QueryFilter { get { return _filter; } } public override string ToString() { return _text; } } #endregion #region Export private FeatureImport _export = null; private FDBImport _fdbExport = null; private IFeatureDataset _dataset = null; private IQueryFilter _filter = null; private void ExportDatasetObject(object datasetObject) { if (_dataset.Database is AccessFDB) { ExportDatasetObject_fdb(datasetObject); } else { ExportDatasetObject_db(datasetObject); } } #region FDB private void ExportDatasetObject_fdb(object datasetObject) { if (datasetObject is IFeatureDataset) { IFeatureDataset dataset = (IFeatureDataset)datasetObject; foreach (IDatasetElement element in dataset.Elements) { if (element is IFeatureLayer) { ExportDatasetObject(((IFeatureLayer)element).FeatureClass); } } } if (datasetObject is IFeatureClass) { Thread thread = new Thread(new ParameterizedThreadStart(ExportAsync_fdb)); if (_fdbExport == null) _fdbExport = new FDBImport(); else { MessageBox.Show("ERROR: Import already runnung"); return; } FeatureClassImportProgressReporter reporter = new FeatureClassImportProgressReporter(_fdbExport, (IFeatureClass)datasetObject); FormProgress progress = new FormProgress(reporter, thread, datasetObject); progress.Text = "Export Features: " + ((IFeatureClass)datasetObject).Name; progress.ShowDialog(); _fdbExport = null; } if (datasetObject is FeatureClassListViewItem) { Thread thread = new Thread(new ParameterizedThreadStart(ExportAsync_fdb)); if (_fdbExport == null) _fdbExport = new FDBImport(); else { MessageBox.Show("ERROR: Import already runnung"); return; } FeatureClassImportProgressReporter reporter = new FeatureClassImportProgressReporter(_fdbExport, ((FeatureClassListViewItem)datasetObject).FeatureClass); FormProgress progress = new FormProgress(reporter, thread, datasetObject); progress.Text = "Export Features: " + ((FeatureClassListViewItem)datasetObject).TargetName; progress.ShowDialog(); _fdbExport = null; } } private void ExportAsync_fdb(object element) { if (_fdbExport == null) return; List<IQueryFilter> filters = null; if (_filter != null) { filters = new List<IQueryFilter>(); filters.Add(_filter); } if (element is IFeatureClass) { if (!_fdbExport.ImportToNewFeatureclass( _dataset.Database as IFeatureDatabase, _dataset.DatasetName, _listViewItem.TargetName, (IFeatureClass)element, null, true, filters)) { MessageBox.Show(_export.lastErrorMsg); } } else if (element is FeatureClassListViewItem) { FeatureClassListViewItem item = element as FeatureClassListViewItem; if (item.FeatureClass == null) return; if (!_fdbExport.ImportToNewFeatureclass( _dataset.Database as IFeatureDatabase, _dataset.DatasetName, item.TargetName, item.FeatureClass, item.ImportFieldTranslation, true, filters)) { MessageBox.Show(_fdbExport.lastErrorMsg); } } } #endregion #region All other DBs private void ExportDatasetObject_db(object datasetObject) { if (datasetObject is IFeatureDataset) { IFeatureDataset dataset = (IFeatureDataset)datasetObject; foreach (IDatasetElement element in dataset.Elements) { if (element is IFeatureLayer) { ExportDatasetObject(((IFeatureLayer)element).FeatureClass); } } } if (datasetObject is IFeatureClass) { Thread thread = new Thread(new ParameterizedThreadStart(ExportAsync_db)); if (_export == null) _export = new FeatureImport(); else { MessageBox.Show("ERROR: Import already runnung"); return; } FeatureClassImportProgressReporter reporter = new FeatureClassImportProgressReporter(_export, (IFeatureClass)datasetObject); FormProgress progress = new FormProgress(reporter, thread, datasetObject); progress.Text = "Export Features: " + ((IFeatureClass)datasetObject).Name; progress.ShowDialog(); _export = null; } if (datasetObject is FeatureClassListViewItem) { Thread thread = new Thread(new ParameterizedThreadStart(ExportAsync_db)); if (_export == null) _export = new FeatureImport(); else { MessageBox.Show("ERROR: Import already runnung"); return; } FeatureClassImportProgressReporter reporter = new FeatureClassImportProgressReporter(_export, ((FeatureClassListViewItem)datasetObject).FeatureClass); FormProgress progress = new FormProgress(reporter, thread, datasetObject); progress.Text = "Export Features: " + ((FeatureClassListViewItem)datasetObject).TargetName; progress.ShowDialog(); _export = null; } } private void ExportAsync_db(object element) { if (_export == null) return; List<IQueryFilter> filters = null; if (_filter != null) { filters = new List<IQueryFilter>(); filters.Add(_filter); } if (element is IFeatureClass) { if (!_export.ImportToNewFeatureclass( _dataset, ((IFeatureClass)element).Name, (IFeatureClass)element, null, true, filters)) { MessageBox.Show(_export.lastErrorMsg); } } else if (element is FeatureClassListViewItem) { FeatureClassListViewItem item = element as FeatureClassListViewItem; if (item.FeatureClass == null) return; if (!_export.ImportToNewFeatureclass( _dataset, item.TargetName, item.FeatureClass, item.ImportFieldTranslation, true, filters)) { MessageBox.Show(_export.lastErrorMsg); } } } #endregion class FeatureClassImportProgressReporter : IProgressReporter { private ProgressReport _report = new ProgressReport(); private ICancelTracker _cancelTracker = null; public FeatureClassImportProgressReporter(object import, IFeatureClass source) { if (import == null) return; if (import is FDBImport) { _cancelTracker = ((FDBImport)import).CancelTracker; if (source != null) _report.featureMax = source.CountFeatures; ((FDBImport)import).ReportAction += new FDBImport.ReportActionEvent(FeatureClassImportProgressReporter_ReportAction); ((FDBImport)import).ReportProgress += new FDBImport.ReportProgressEvent(FeatureClassImportProgressReporter_ReportProgress); ((FDBImport)import).ReportRequest += new FDBImport.ReportRequestEvent(FeatureClassImportProgressReporter_ReportRequest); } if (import is FeatureImport) { _cancelTracker = ((FeatureImport)import).CancelTracker; if (source != null) _report.featureMax = source.CountFeatures; ((FeatureImport)import).ReportAction += new FeatureImport.ReportActionEvent(import_ReportAction); ((FeatureImport)import).ReportProgress += new FeatureImport.ReportProgressEvent(import_ReportProgress); ((FeatureImport)import).ReportRequest += new FeatureImport.ReportRequestEvent(import_ReportRequest); } } #region FDB void FeatureClassImportProgressReporter_ReportRequest(FDBImport sender, gView.DataSources.Fdb.UI.RequestArgs args) { args.Result = MessageBox.Show( args.Request, "Warning", args.Buttons, MessageBoxIcon.Warning); } void FeatureClassImportProgressReporter_ReportProgress(FDBImport sender, int progress) { if (ReportProgress == null) return; _report.featureMax = Math.Max(_report.featureMax, progress); _report.featurePos = progress; ReportProgress(_report); } void FeatureClassImportProgressReporter_ReportAction(FDBImport sender, string action) { if (ReportProgress == null) return; _report.featurePos = 0; _report.Message = action; ReportProgress(_report); } #endregion void import_ReportRequest(FeatureImport sender, gView.Framework.system.UI.RequestArgs args) { args.Result = MessageBox.Show( args.Request, "Warning", args.Buttons, MessageBoxIcon.Warning); } void import_ReportProgress(FeatureImport sender, int progress) { if (ReportProgress == null) return; _report.featureMax = Math.Max(_report.featureMax, progress); _report.featurePos = progress; ReportProgress(_report); } void import_ReportAction(FeatureImport sender, string action) { if (ReportProgress == null) return; _report.featurePos = 0; _report.Message = action; ReportProgress(_report); } #region IProgressReporter Member public event ProgressReporterEvent ReportProgress; public ICancelTracker CancelTracker { get { return _cancelTracker; } } #endregion } #endregion } }
/* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, 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 name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Antlr.Runtime.Tree { using System.Collections.Generic; using Exception = System.Exception; using IDictionary = System.Collections.IDictionary; using NotSupportedException = System.NotSupportedException; /** <summary>A TreeAdaptor that works with any Tree implementation.</summary> */ public abstract class BaseTreeAdaptor : ITreeAdaptor { /** <summary> * System.identityHashCode() is not always unique; we have to * track ourselves. That's ok, it's only for debugging, though it's * expensive: we have to create a hashtable with all tree nodes in it. * </summary> */ protected IDictionary<object, int> treeToUniqueIDMap; protected int uniqueNodeID = 1; public virtual object Nil() { return Create(null); } /** <summary> * Create tree node that holds the start and stop tokens associated * with an error. * </summary> * * <remarks> * If you specify your own kind of tree nodes, you will likely have to * override this method. CommonTree returns Token.INVALID_TOKEN_TYPE * if no token payload but you might have to set token type for diff * node type. * * You don't have to subclass CommonErrorNode; you will likely need to * subclass your own tree node class to avoid class cast exception. * </remarks> */ public virtual object ErrorNode(ITokenStream input, IToken start, IToken stop, RecognitionException e) { CommonErrorNode t = new CommonErrorNode(input, start, stop, e); //System.out.println("returning error node '"+t+"' @index="+input.index()); return t; } public virtual bool IsNil(object tree) { return ((ITree)tree).IsNil; } public virtual object DupTree(object tree) { return DupTree(tree, null); } /** <summary> * This is generic in the sense that it will work with any kind of * tree (not just ITree interface). It invokes the adaptor routines * not the tree node routines to do the construction. * </summary> */ public virtual object DupTree(object t, object parent) { if (t == null) { return null; } object newTree = DupNode(t); // ensure new subtree root has parent/child index set SetChildIndex(newTree, GetChildIndex(t)); // same index in new tree SetParent(newTree, parent); int n = GetChildCount(t); for (int i = 0; i < n; i++) { object child = GetChild(t, i); object newSubTree = DupTree(child, t); AddChild(newTree, newSubTree); } return newTree; } /** <summary> * Add a child to the tree t. If child is a flat tree (a list), make all * in list children of t. Warning: if t has no children, but child does * and child isNil then you can decide it is ok to move children to t via * t.children = child.children; i.e., without copying the array. Just * make sure that this is consistent with have the user will build * ASTs. * </summary> */ public virtual void AddChild(object t, object child) { if (t != null && child != null) { ((ITree)t).AddChild((ITree)child); } } /** <summary> * If oldRoot is a nil root, just copy or move the children to newRoot. * If not a nil root, make oldRoot a child of newRoot. * </summary> * * <remarks> * old=^(nil a b c), new=r yields ^(r a b c) * old=^(a b c), new=r yields ^(r ^(a b c)) * * If newRoot is a nil-rooted single child tree, use the single * child as the new root node. * * old=^(nil a b c), new=^(nil r) yields ^(r a b c) * old=^(a b c), new=^(nil r) yields ^(r ^(a b c)) * * If oldRoot was null, it's ok, just return newRoot (even if isNil). * * old=null, new=r yields r * old=null, new=^(nil r) yields ^(nil r) * * Return newRoot. Throw an exception if newRoot is not a * simple node or nil root with a single child node--it must be a root * node. If newRoot is ^(nil x) return x as newRoot. * * Be advised that it's ok for newRoot to point at oldRoot's * children; i.e., you don't have to copy the list. We are * constructing these nodes so we should have this control for * efficiency. * </remarks> */ public virtual object BecomeRoot(object newRoot, object oldRoot) { //System.out.println("becomeroot new "+newRoot.toString()+" old "+oldRoot); ITree newRootTree = (ITree)newRoot; ITree oldRootTree = (ITree)oldRoot; if (oldRoot == null) { return newRoot; } // handle ^(nil real-node) if (newRootTree.IsNil) { int nc = newRootTree.ChildCount; if (nc == 1) newRootTree = (ITree)newRootTree.GetChild(0); else if (nc > 1) { // TODO: make tree run time exceptions hierarchy throw new Exception("more than one node as root (TODO: make exception hierarchy)"); } } // add oldRoot to newRoot; addChild takes care of case where oldRoot // is a flat list (i.e., nil-rooted tree). All children of oldRoot // are added to newRoot. newRootTree.AddChild(oldRootTree); return newRootTree; } /** <summary>Transform ^(nil x) to x and nil to null</summary> */ public virtual object RulePostProcessing(object root) { //System.out.println("rulePostProcessing: "+((Tree)root).toStringTree()); ITree r = (ITree)root; if (r != null && r.IsNil) { if (r.ChildCount == 0) { r = null; } else if (r.ChildCount == 1) { r = (ITree)r.GetChild(0); // whoever invokes rule will set parent and child index r.Parent = null; r.ChildIndex = -1; } } return r; } public virtual object BecomeRoot(IToken newRoot, object oldRoot) { return BecomeRoot(Create(newRoot), oldRoot); } public virtual object Create(int tokenType, IToken fromToken) { fromToken = CreateToken(fromToken); //((ClassicToken)fromToken).setType(tokenType); fromToken.Type = tokenType; ITree t = (ITree)Create(fromToken); return t; } public virtual object Create(int tokenType, IToken fromToken, string text) { if (fromToken == null) return Create(tokenType, text); fromToken = CreateToken(fromToken); fromToken.Type = tokenType; fromToken.Text = text; ITree t = (ITree)Create(fromToken); return t; } public virtual object Create(int tokenType, string text) { IToken fromToken = CreateToken(tokenType, text); ITree t = (ITree)Create(fromToken); return t; } public virtual int GetType(object t) { return ((ITree)t).Type; } public virtual void SetType(object t, int type) { throw new NotSupportedException("don't know enough about Tree node"); } public virtual string GetText(object t) { return ((ITree)t).Text; } public virtual void SetText(object t, string text) { throw new NotSupportedException("don't know enough about Tree node"); } public virtual object GetChild(object t, int i) { return ((ITree)t).GetChild(i); } public virtual void SetChild(object t, int i, object child) { ((ITree)t).SetChild(i, (ITree)child); } public virtual object DeleteChild(object t, int i) { return ((ITree)t).DeleteChild(i); } public virtual int GetChildCount(object t) { return ((ITree)t).ChildCount; } public virtual int GetUniqueID(object node) { if (treeToUniqueIDMap == null) { treeToUniqueIDMap = new Dictionary<object, int>(); } int id; if (treeToUniqueIDMap.TryGetValue(node, out id)) return id; id = uniqueNodeID; treeToUniqueIDMap[node] = id; uniqueNodeID++; return id; // GC makes these nonunique: // return System.identityHashCode(node); } /** <summary> * Tell me how to create a token for use with imaginary token nodes. * For example, there is probably no input symbol associated with imaginary * token DECL, but you need to create it as a payload or whatever for * the DECL node as in ^(DECL type ID). * </summary> * * <remarks> * If you care what the token payload objects' type is, you should * override this method and any other createToken variant. * </remarks> */ public abstract IToken CreateToken(int tokenType, string text); /** <summary> * Tell me how to create a token for use with imaginary token nodes. * For example, there is probably no input symbol associated with imaginary * token DECL, but you need to create it as a payload or whatever for * the DECL node as in ^(DECL type ID). * </summary> * * <remarks> * This is a variant of createToken where the new token is derived from * an actual real input token. Typically this is for converting '{' * tokens to BLOCK etc... You'll see * * r : lc='{' ID+ '}' -> ^(BLOCK[$lc] ID+) ; * * If you care what the token payload objects' type is, you should * override this method and any other createToken variant. * </remarks> */ public abstract IToken CreateToken(IToken fromToken); public abstract object Create(IToken payload); public abstract object DupNode(object treeNode); public abstract IToken GetToken(object t); public abstract void SetTokenBoundaries(object t, IToken startToken, IToken stopToken); public abstract int GetTokenStartIndex(object t); public abstract int GetTokenStopIndex(object t); public abstract object GetParent(object t); public abstract void SetParent(object t, object parent); public abstract int GetChildIndex(object t); public abstract void SetChildIndex(object t, int index); public abstract void ReplaceChildren(object parent, int startChildIndex, int stopChildIndex, object t); } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.InteractiveWindow; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Repl; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.PythonTools.Intellisense { internal class NormalCompletionAnalysis : CompletionAnalysis { private readonly ITextSnapshot _snapshot; private readonly VsProjectAnalyzer _analyzer; private readonly IServiceProvider _serviceProvider; internal NormalCompletionAnalysis(VsProjectAnalyzer analyzer, ICompletionSession session, ITextView view, ITextSnapshot snapshot, ITrackingSpan span, ITextBuffer textBuffer, CompletionOptions options, IServiceProvider serviceProvider) : base(analyzer._serviceProvider, session, view, span, textBuffer, options) { _snapshot = snapshot; _analyzer = analyzer; _serviceProvider = serviceProvider; } internal bool GetPrecedingExpression(out string text, out SnapshotSpan expressionExtent) { text = string.Empty; expressionExtent = default(SnapshotSpan); var startSpan = _snapshot.CreateTrackingSpan(Span.GetSpan(_snapshot).Start.Position, 0, SpanTrackingMode.EdgeInclusive); var parser = new ReverseExpressionParser(_snapshot, _snapshot.TextBuffer, startSpan); using (var e = parser.GetEnumerator()) { if (e.MoveNext() && e.Current != null && e.Current.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Number)) { return false; } } var sourceSpan = parser.GetExpressionRange(); if (sourceSpan.HasValue && sourceSpan.Value.Length > 0) { text = sourceSpan.Value.GetText(); if (text.EndsWith(".")) { text = text.Substring(0, text.Length - 1); if (text.Length == 0) { // don't return all available members on empty dot. return false; } } else { int cut = text.LastIndexOfAny(new[] { '.', ']', ')' }); if (cut != -1) { text = text.Substring(0, cut); } else { text = String.Empty; } } } expressionExtent = sourceSpan ?? new SnapshotSpan(Span.GetStartPoint(_snapshot), 0); return true; } public override CompletionSet GetCompletions(IGlyphService glyphService) { var start1 = _stopwatch.ElapsedMilliseconds; IEnumerable<CompletionResult> members = null; IEnumerable<CompletionResult> replMembers = null; var interactiveWindow = _snapshot.TextBuffer.GetInteractiveWindow(); var pyReplEval = interactiveWindow?.Evaluator as IPythonInteractiveIntellisense; var analysis = GetAnalysisEntry(); string text; SnapshotSpan statementRange; if (!GetPrecedingExpression(out text, out statementRange)) { return null; } else if (string.IsNullOrEmpty(text)) { if (analysis != null) { lock (_analyzer) { var location = VsProjectAnalyzer.TranslateIndex( statementRange.Start.Position, statementRange.Snapshot, analysis ); var parameters = Enumerable.Empty<CompletionResult>(); var sigs = VsProjectAnalyzer.GetSignaturesAsync(_serviceProvider, View, _snapshot, Span).WaitOrDefault(1000); if (sigs != null && sigs.Signatures.Any()) { parameters = sigs.Signatures .SelectMany(s => s.Parameters) .Select(p => p.Name) .Distinct() .Select(n => new CompletionResult(n, PythonMemberType.Field)); } members = (analysis.Analyzer.GetAllAvailableMembersAsync(analysis, location, _options.MemberOptions).WaitOrDefault(1000) ?? new CompletionResult[0]) .Union(parameters, CompletionComparer.MemberEquality); } } if (pyReplEval == null) { var expansions = _serviceProvider.GetPythonToolsService().GetExpansionCompletions(100); if (expansions != null) { // Expansions should come first, so that they replace our keyword // completions with the more detailed snippets. if (members != null) { members = expansions.Union(members, CompletionComparer.MemberEquality); } else { members = expansions; } } } if (pyReplEval != null) { replMembers = pyReplEval.GetMemberNames(string.Empty); } } else { if (analysis != null && (pyReplEval == null || !pyReplEval.LiveCompletionsOnly)) { lock (_analyzer) { var location = VsProjectAnalyzer.TranslateIndex( statementRange.Start.Position, statementRange.Snapshot, analysis ); members = analysis.Analyzer.GetMembersAsync(analysis, text, location, _options.MemberOptions).WaitOrDefault(1000); } } if (pyReplEval != null && _analyzer.ShouldEvaluateForCompletion(text)) { Debug.Assert(pyReplEval.Analyzer == _analyzer); replMembers = pyReplEval.GetMemberNames(text); } } if (replMembers != null) { if (members != null) { members = members.Union(replMembers, CompletionComparer.MemberEquality); } else { members = replMembers; } } var end = _stopwatch.ElapsedMilliseconds; if (/*Logging &&*/ (end - start1) > TooMuchTime) { if (members != null) { var memberArray = members.ToArray(); members = memberArray; Trace.WriteLine(String.Format("{0} lookup time {1} for {2} members", this, end - start1, members.Count())); } else { Trace.WriteLine(String.Format("{0} lookup time {1} for zero members", this, end - start1)); } } if (members == null) { // The expression is invalid so we shouldn't provide // a completion set at all. return null; } var start = _stopwatch.ElapsedMilliseconds; var result = new FuzzyCompletionSet( "Python", "Python", Span, members.Select(m => PythonCompletion(glyphService, m)), _options, CompletionComparer.UnderscoresLast, matchInsertionText: true ); end = _stopwatch.ElapsedMilliseconds; if (/*Logging &&*/ (end - start1) > TooMuchTime) { Trace.WriteLine(String.Format("{0} completion set time {1} total time {2}", this, end - start, end - start1)); } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Xsl.XsltOld { using System; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl.Runtime; using MS.Internal.Xml.XPath; using System.Security; internal class Key { private XmlQualifiedName _name; private int _matchKey; private int _useKey; private ArrayList _keyNodes; public Key(XmlQualifiedName name, int matchkey, int usekey) { _name = name; _matchKey = matchkey; _useKey = usekey; _keyNodes = null; } public XmlQualifiedName Name { get { return _name; } } public int MatchKey { get { return _matchKey; } } public int UseKey { get { return _useKey; } } public void AddKey(XPathNavigator root, Hashtable table) { if (_keyNodes == null) { _keyNodes = new ArrayList(); } _keyNodes.Add(new DocumentKeyList(root, table)); } public Hashtable GetKeys(XPathNavigator root) { if (_keyNodes != null) { for (int i = 0; i < _keyNodes.Count; i++) { if (((DocumentKeyList)_keyNodes[i]).RootNav.IsSamePosition(root)) { return ((DocumentKeyList)_keyNodes[i]).KeyTable; } } } return null; } public Key Clone() { return new Key(_name, _matchKey, _useKey); } } internal struct DocumentKeyList { private XPathNavigator _rootNav; private Hashtable _keyTable; public DocumentKeyList(XPathNavigator rootNav, Hashtable keyTable) { _rootNav = rootNav; _keyTable = keyTable; } public XPathNavigator RootNav { get { return _rootNav; } } public Hashtable KeyTable { get { return _keyTable; } } } internal class RootAction : TemplateBaseAction { private const int QueryInitialized = 2; private const int RootProcessed = 3; private Hashtable _attributeSetTable = new Hashtable(); private Hashtable _decimalFormatTable = new Hashtable(); private List<Key> _keyList; private XsltOutput _output; public Stylesheet builtInSheet; internal XsltOutput Output { get { if (_output == null) { _output = new XsltOutput(); } return _output; } } /* * Compile */ internal override void Compile(Compiler compiler) { CompileDocument(compiler, /*inInclude*/ false); } internal void InsertKey(XmlQualifiedName name, int MatchKey, int UseKey) { if (_keyList == null) { _keyList = new List<Key>(); } _keyList.Add(new Key(name, MatchKey, UseKey)); } internal AttributeSetAction GetAttributeSet(XmlQualifiedName name) { AttributeSetAction action = (AttributeSetAction)_attributeSetTable[name]; if (action == null) { throw XsltException.Create(SR.Xslt_NoAttributeSet, name.ToString()); } return action; } public void PorcessAttributeSets(Stylesheet rootStylesheet) { MirgeAttributeSets(rootStylesheet); // As we mentioned we need to invert all lists. foreach (AttributeSetAction attSet in _attributeSetTable.Values) { if (attSet.containedActions != null) { attSet.containedActions.Reverse(); } } // ensures there are no cycles in the attribute-sets use dfs marking method CheckAttributeSets_RecurceInList(new Hashtable(), _attributeSetTable.Keys); } private void MirgeAttributeSets(Stylesheet stylesheet) { // mirge stylesheet.AttributeSetTable to this.AttributeSetTable if (stylesheet.AttributeSetTable != null) { foreach (AttributeSetAction srcAttSet in stylesheet.AttributeSetTable.Values) { ArrayList srcAttList = srcAttSet.containedActions; AttributeSetAction dstAttSet = (AttributeSetAction)_attributeSetTable[srcAttSet.Name]; if (dstAttSet == null) { dstAttSet = new AttributeSetAction(); { dstAttSet.name = srcAttSet.Name; dstAttSet.containedActions = new ArrayList(); } _attributeSetTable[srcAttSet.Name] = dstAttSet; } ArrayList dstAttList = dstAttSet.containedActions; // We adding attributes in reverse order for purpuse. In the mirged list most importent attset shoud go last one // so we'll need to invert dstAttList finaly. if (srcAttList != null) { for (int src = srcAttList.Count - 1; 0 <= src; src--) { // We can ignore duplicate attibutes here. dstAttList.Add(srcAttList[src]); } } } } foreach (Stylesheet importedStylesheet in stylesheet.Imports) { MirgeAttributeSets(importedStylesheet); } } private void CheckAttributeSets_RecurceInList(Hashtable markTable, ICollection setQNames) { const string PROCESSING = "P"; const string DONE = "D"; foreach (XmlQualifiedName qname in setQNames) { object mark = markTable[qname]; if (mark == (object)PROCESSING) { throw XsltException.Create(SR.Xslt_CircularAttributeSet, qname.ToString()); } else if (mark == (object)DONE) { continue; // optimization: we already investigated this attribute-set. } else { Debug.Assert(mark == null); markTable[qname] = (object)PROCESSING; CheckAttributeSets_RecurceInContainer(markTable, GetAttributeSet(qname)); markTable[qname] = (object)DONE; } } } private void CheckAttributeSets_RecurceInContainer(Hashtable markTable, ContainerAction container) { if (container.containedActions == null) { return; } foreach (Action action in container.containedActions) { if (action is UseAttributeSetsAction) { CheckAttributeSets_RecurceInList(markTable, ((UseAttributeSetsAction)action).UsedSets); } else if (action is ContainerAction) { CheckAttributeSets_RecurceInContainer(markTable, (ContainerAction)action); } } } internal void AddDecimalFormat(XmlQualifiedName name, DecimalFormat formatinfo) { DecimalFormat exist = (DecimalFormat)_decimalFormatTable[name]; if (exist != null) { NumberFormatInfo info = exist.info; NumberFormatInfo newinfo = formatinfo.info; if (info.NumberDecimalSeparator != newinfo.NumberDecimalSeparator || info.NumberGroupSeparator != newinfo.NumberGroupSeparator || info.PositiveInfinitySymbol != newinfo.PositiveInfinitySymbol || info.NegativeSign != newinfo.NegativeSign || info.NaNSymbol != newinfo.NaNSymbol || info.PercentSymbol != newinfo.PercentSymbol || info.PerMilleSymbol != newinfo.PerMilleSymbol || exist.zeroDigit != formatinfo.zeroDigit || exist.digit != formatinfo.digit || exist.patternSeparator != formatinfo.patternSeparator ) { throw XsltException.Create(SR.Xslt_DupDecimalFormat, name.ToString()); } } _decimalFormatTable[name] = formatinfo; } internal DecimalFormat GetDecimalFormat(XmlQualifiedName name) { return _decimalFormatTable[name] as DecimalFormat; } internal List<Key> KeyList { get { return _keyList; } } internal override void Execute(Processor processor, ActionFrame frame) { Debug.Assert(processor != null && frame != null); switch (frame.State) { case Initialized: frame.AllocateVariables(variableCount); XPathNavigator root = processor.Document.Clone(); root.MoveToRoot(); frame.InitNodeSet(new XPathSingletonIterator(root)); if (this.containedActions != null && this.containedActions.Count > 0) { processor.PushActionFrame(frame); } frame.State = QueryInitialized; break; case QueryInitialized: Debug.Assert(frame.State == QueryInitialized); frame.NextNode(processor); Debug.Assert(Processor.IsRoot(frame.Node)); if (processor.Debugger != null) { // this is like apply-templates, but we don't have it on stack. // Pop the stack, otherwise last instruction will be on it. processor.PopDebuggerStack(); } processor.PushTemplateLookup(frame.NodeSet, /*mode:*/null, /*importsOf:*/null); frame.State = RootProcessed; break; case RootProcessed: Debug.Assert(frame.State == RootProcessed); frame.Finished(); break; default: Debug.Fail("Invalid RootAction execution state"); break; } } } }
/* * Copyright 2013 ThirdMotion, 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. */ /** * @class strange.extensions.injector.impl.Injector * * Supplies injection for all mapped dependencies. * * Extension satisfies injection dependencies. Works in conjuntion with * (and therefore relies on) the Reflector. * * Dependencies may be Constructor injections (all parameters will be satisfied), * or setter injections. * * Classes utilizing this injector must be marked with the following metatags: * <ul> * <li>[Inject] - Use this metatag on any setter you wish to have supplied by injection.</li> * <li>[Construct] - Use this metatag on the specific Constructor you wish to inject into when using Constructor injection. If you omit this tag, the Constructor with the shortest list of dependencies will be selected automatically.</li> * <li>[PostConstruct] - Use this metatag on any method(s) you wish to fire directly after dependencies are supplied</li> * </ul> * * The Injection system is quite loud and specific where dependencies are unmapped, * throwing Exceptions to warn you. This is exceptionally useful in ensuring that * your app is well structured. */ using System; using System.Collections.Generic; using System.Reflection; using strange.extensions.injector.api; using strange.extensions.reflector.api; namespace strange.extensions.injector.impl { public class Injector : IInjector { private Dictionary<IInjectionBinding, int> infinityLock; private const int INFINITY_LIMIT = 10; public Injector () { factory = new InjectorFactory(); } public IInjectorFactory factory{ get; set;} public IInjectionBinder binder{ get; set;} public IReflectionBinder reflector{ get; set;} public object Instantiate(IInjectionBinding binding) { failIf(binder == null, "Attempt to instantiate from Injector without a Binder", InjectionExceptionType.NO_BINDER); failIf(factory == null, "Attempt to inject into Injector without a Factory", InjectionExceptionType.NO_FACTORY); armorAgainstInfiniteLoops (binding); object retv = null; Type reflectionType = null; if (binding.value is Type) { reflectionType = binding.value as Type; } else if (binding.value == null) { object[] tl = binding.key as object[]; reflectionType = tl [0] as Type; if (reflectionType.IsPrimitive || reflectionType == typeof(Decimal) || reflectionType == typeof(string)) { retv = binding.value; } } else { retv = binding.value; } if (retv == null) //If we don't have an existing value, go ahead and create one. { IReflectedClass reflection = reflector.Get (reflectionType); Type[] parameterTypes = reflection.constructorParameters; object[] parameterNames = reflection.ConstructorParameterNames; int aa = parameterTypes.Length; object[] args = new object [aa]; for (int a = 0; a < aa; a++) { args [a] = getValueInjection (parameterTypes[a] as Type, parameterNames[a], null); } retv = factory.Get (binding, args); //If the InjectorFactory returns null, just return it. Otherwise inject the retv if it needs it //This could happen if Activator.CreateInstance returns null if (retv != null) { if (binding.toInject) { retv = Inject (retv, false); } if (binding.type == InjectionBindingType.SINGLETON || binding.type == InjectionBindingType.VALUE) { //prevent double-injection binding.ToInject(false); } } } infinityLock = null; //Clear our infinity lock so the next time we instantiate we don't consider this a circular dependency return retv; } public object Inject(object target) { return Inject (target, true); } public object Inject(object target, bool attemptConstructorInjection) { failIf(binder == null, "Attempt to inject into Injector without a Binder", InjectionExceptionType.NO_BINDER); failIf(reflector == null, "Attempt to inject without a reflector", InjectionExceptionType.NO_REFLECTOR); failIf(target == null, "Attempt to inject into null instance", InjectionExceptionType.NULL_TARGET); //Some things can't be injected into. Bail out. Type t = target.GetType (); if (t.IsPrimitive || t == typeof(Decimal) || t == typeof(string)) { return target; } IReflectedClass reflection = reflector.Get (t); if (attemptConstructorInjection) { target = performConstructorInjection(target, reflection); } performSetterInjection(target, reflection); postInject(target, reflection); return target; } public void Uninject(object target) { failIf(binder == null, "Attempt to inject into Injector without a Binder", InjectionExceptionType.NO_BINDER); failIf(reflector == null, "Attempt to inject without a reflector", InjectionExceptionType.NO_REFLECTOR); failIf(target == null, "Attempt to inject into null instance", InjectionExceptionType.NULL_TARGET); Type t = target.GetType (); if (t.IsPrimitive || t == typeof(Decimal) || t == typeof(string)) { return; } IReflectedClass reflection = reflector.Get (t); performUninjection (target, reflection); } private object performConstructorInjection(object target, IReflectedClass reflection) { failIf(target == null, "Attempt to perform constructor injection into a null object", InjectionExceptionType.NULL_TARGET); failIf(reflection == null, "Attempt to perform constructor injection without a reflection", InjectionExceptionType.NULL_REFLECTION); ConstructorInfo constructor = reflection.constructor; failIf(constructor == null, "Attempt to construction inject a null constructor", InjectionExceptionType.NULL_CONSTRUCTOR); Type[] parameterTypes = reflection.constructorParameters; object[] parameterNames = reflection.ConstructorParameterNames; object[] values = new object[parameterTypes.Length]; int i = 0; foreach (Type type in parameterTypes) { values[i] = getValueInjection(type, parameterNames[i], target); i++; } if (values.Length == 0) { return target; } object constructedObj = constructor.Invoke (values); return (constructedObj == null) ? target : constructedObj; } private void performSetterInjection(object target, IReflectedClass reflection) { failIf(target == null, "Attempt to inject into a null object", InjectionExceptionType.NULL_TARGET); failIf(reflection == null, "Attempt to inject without a reflection", InjectionExceptionType.NULL_REFLECTION); failIf(reflection.setters.Length != reflection.setterNames.Length, "Attempt to perform setter injection with mismatched names.\nThere must be exactly as many names as setters.", InjectionExceptionType.SETTER_NAME_MISMATCH); int aa = reflection.setters.Length; for(int a = 0; a < aa; a++) { KeyValuePair<Type, PropertyInfo> pair = reflection.setters [a]; object value = getValueInjection(pair.Key, reflection.setterNames[a], target); injectValueIntoPoint (value, target, pair.Value); } } private object getValueInjection(Type t, object name, object target) { IInjectionBinding binding = binder.GetBinding (t, name); failIf(binding == null, "Attempt to Instantiate a null binding.", InjectionExceptionType.NULL_BINDING, t, name, target); if (binding.type == InjectionBindingType.VALUE) { if (!binding.toInject) { return binding.value; } else { object retv = Inject (binding.value, false); binding.ToInject (false); return retv; } } else if (binding.type == InjectionBindingType.SINGLETON) { if (binding.value is Type || binding.value == null) Instantiate (binding); return binding.value; } else { return Instantiate (binding); } } //Inject the value into the target at the specified injection point private void injectValueIntoPoint(object value, object target, PropertyInfo point) { failIf(target == null, "Attempt to inject into a null target", InjectionExceptionType.NULL_TARGET); failIf(point == null, "Attempt to inject into a null point", InjectionExceptionType.NULL_INJECTION_POINT); failIf(value == null, "Attempt to inject null into a target object", InjectionExceptionType.NULL_VALUE_INJECTION); point.SetValue (target, value, null); } //After injection, call any methods labelled with the [PostConstruct] tag private void postInject(object target, IReflectedClass reflection) { failIf(target == null, "Attempt to PostConstruct a null target", InjectionExceptionType.NULL_TARGET); failIf(reflection == null, "Attempt to PostConstruct without a reflection", InjectionExceptionType.NULL_REFLECTION); MethodInfo[] postConstructors = reflection.postConstructors; if (postConstructors != null) { foreach(MethodInfo method in postConstructors) { method.Invoke (target, null); } } } //Note that uninjection can only clean publicly settable points private void performUninjection(object target, IReflectedClass reflection) { int aa = reflection.setters.Length; for(int a = 0; a < aa; a++) { KeyValuePair<Type, PropertyInfo> pair = reflection.setters [a]; pair.Value.SetValue (target, null, null); } } private void failIf(bool condition, string message, InjectionExceptionType type) { failIf (condition, message, type, null, null, null); } private void failIf(bool condition, string message, InjectionExceptionType type, Type t, object name) { failIf(condition, message, type, t, name, null); } private void failIf(bool condition, string message, InjectionExceptionType type, Type t, object name, object target) { if (condition) { message += "\n\t\ttarget: " + target; message += "\n\t\ttype: " + t; message += "\n\t\tname: " + name; throw new InjectionException(message, type); } } private void armorAgainstInfiniteLoops(IInjectionBinding binding) { if (binding == null) { return; } if (infinityLock == null) { infinityLock = new Dictionary<IInjectionBinding, int> (); } if(infinityLock.ContainsKey(binding) == false) { infinityLock.Add (binding, 0); } infinityLock [binding] = infinityLock [binding] + 1; if (infinityLock [binding] > INFINITY_LIMIT) { throw new InjectionException ("There appears to be a circular dependency. Terminating loop.", InjectionExceptionType.CIRCULAR_DEPENDENCY); } } } }
using System; using System.Web; using umbraco.presentation.LiveEditing; using umbraco.BasePages; using umbraco.cms.businesslogic.web; namespace umbraco.presentation { /// <summary> /// A custom HttpRequestBase object which exposes some additional methods /// </summary> /// <remarks> /// The only reason this class exists is because somebody decided that it would be a good idea to piggy /// back the IsDebug method on top of the HttpRequest object. Unforunately when this was created it /// inherited from HttpRequestWrapper intead of HttpRequestBase which meant that this is not unit testable /// and still has a dependency on a real HttpRequest. So now it inherits from HttpRequestBase which /// means we need to override all of the methods and just wrap them with the _request object passed in. /// /// This now needs to exist only because of backwards compatibility /// </remarks> [Obsolete("This class is no longer used, for the IsDebug method use Umbraco.Web.UmbracoContext.IsDebug")] public class UmbracoRequest : HttpRequestBase { private readonly HttpRequestBase _request; #region Constructor public UmbracoRequest(HttpRequestBase request) { _request = request; } [Obsolete("Use the alternative contructor that accepts a HttpRequestBase object instead")] public UmbracoRequest(HttpRequest request) { _request = new HttpRequestWrapper(request); } #endregion #region Wrapped Methods public override string[] AcceptTypes { get { return _request.AcceptTypes; } } public override string AnonymousID { get { return _request.AnonymousID; } } public override string ApplicationPath { get { return _request.ApplicationPath; } } public override string AppRelativeCurrentExecutionFilePath { get { return _request.AppRelativeCurrentExecutionFilePath; } } public override byte[] BinaryRead(int count) { return _request.BinaryRead(count); } public override HttpBrowserCapabilitiesBase Browser { get { return _request.Browser; } } public override HttpClientCertificate ClientCertificate { get { return _request.ClientCertificate; } } public override System.Text.Encoding ContentEncoding { get { return _request.ContentEncoding; } set { _request.ContentEncoding = value; } } public override int ContentLength { get { return _request.ContentLength; } } public override string ContentType { get { return _request.ContentType; } set { _request.ContentType = value; } } public override HttpCookieCollection Cookies { get { return _request.Cookies; } } public override string CurrentExecutionFilePath { get { return _request.CurrentExecutionFilePath; } } public override bool Equals(object obj) { return _request.Equals(obj); } public override string FilePath { get { return _request.FilePath; } } public override HttpFileCollectionBase Files { get { return _request.Files; } } public override System.IO.Stream Filter { get { return _request.Filter; } set { _request.Filter = value; } } public override System.Collections.Specialized.NameValueCollection Form { get { return _request.Form; } } public override int GetHashCode() { return _request.GetHashCode(); } public override System.Collections.Specialized.NameValueCollection Headers { get { return _request.Headers; } } public override System.Security.Authentication.ExtendedProtection.ChannelBinding HttpChannelBinding { get { return _request.HttpChannelBinding; } } public override string HttpMethod { get { return _request.HttpMethod; } } public override System.IO.Stream InputStream { get { return _request.InputStream; } } public override bool IsAuthenticated { get { return _request.IsAuthenticated; } } public override bool IsLocal { get { return _request.IsLocal; } } public override bool IsSecureConnection { get { return _request.IsSecureConnection; } } public override System.Security.Principal.WindowsIdentity LogonUserIdentity { get { return _request.LogonUserIdentity; } } public override int[] MapImageCoordinates(string imageFieldName) { return _request.MapImageCoordinates(imageFieldName); } public override string MapPath(string virtualPath) { return _request.MapPath(virtualPath); } public override string MapPath(string virtualPath, string baseVirtualDir, bool allowCrossAppMapping) { return _request.MapPath(virtualPath, baseVirtualDir, allowCrossAppMapping); } public override System.Collections.Specialized.NameValueCollection Params { get { return _request.Params; } } public override string Path { get { return _request.Path; } } public override string PathInfo { get { return _request.PathInfo; } } public override string PhysicalApplicationPath { get { return _request.PhysicalApplicationPath; } } public override string PhysicalPath { get { return _request.PhysicalPath; } } public override System.Collections.Specialized.NameValueCollection QueryString { get { return _request.QueryString; } } public override string RawUrl { get { return _request.RawUrl; } } public override System.Web.Routing.RequestContext RequestContext { get { return _request.RequestContext; } } public override string RequestType { get { return _request.RequestType; } set { _request.RequestType = value; } } public override void SaveAs(string filename, bool includeHeaders) { _request.SaveAs(filename, includeHeaders); } public override System.Collections.Specialized.NameValueCollection ServerVariables { get { return _request.ServerVariables; } } public override string this[string key] { get { return _request[key]; } } public override string ToString() { return _request.ToString(); } public override int TotalBytes { get { return _request.TotalBytes; } } public override Uri Url { get { return _request.Url; } } public override Uri UrlReferrer { get { return _request.UrlReferrer; } } public override string UserAgent { get { return _request.UserAgent; } } public override string UserHostAddress { get { return _request.UserHostAddress; } } public override string UserHostName { get { return _request.UserHostName; } } public override string[] UserLanguages { get { return _request.UserLanguages; } } public override void ValidateInput() { _request.ValidateInput(); } #endregion /// <summary> /// Gets a value indicating whether the request has debugging enabled /// </summary> /// <value><c>true</c> if this instance is debug; otherwise, <c>false</c>.</value> public bool IsDebug { get { return GlobalSettings.DebugMode && (!string.IsNullOrEmpty(this["umbdebugshowtrace"]) || !string.IsNullOrEmpty(this["umbdebug"])); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Diagnostics.Contracts; using System.Collections.Generic; namespace System.Globalization { internal partial class CalendarData { private bool LoadCalendarDataFromSystem(String localeName, CalendarId calendarId) { bool ret = true; uint useOverrides = this.bUseUserOverrides ? 0 : CAL_NOUSEROVERRIDE; // // Windows doesn't support some calendars right now, so remap those. // switch (calendarId) { case CalendarId.JAPANESELUNISOLAR: // Data looks like Japanese calendarId = CalendarId.JAPAN; break; case CalendarId.JULIAN: // Data looks like gregorian US case CalendarId.CHINESELUNISOLAR: // Algorithmic, so actual data is irrelevent case CalendarId.SAKA: // reserved to match Office but not implemented in our code, so data is irrelevent case CalendarId.LUNAR_ETO_CHN: // reserved to match Office but not implemented in our code, so data is irrelevent case CalendarId.LUNAR_ETO_KOR: // reserved to match Office but not implemented in our code, so data is irrelevent case CalendarId.LUNAR_ETO_ROKUYOU: // reserved to match Office but not implemented in our code, so data is irrelevent case CalendarId.KOREANLUNISOLAR: // Algorithmic, so actual data is irrelevent case CalendarId.TAIWANLUNISOLAR: // Algorithmic, so actual data is irrelevent calendarId = CalendarId.GREGORIAN_US; break; } // // Special handling for some special calendar due to OS limitation. // This includes calendar like Taiwan calendar, UmAlQura calendar, etc. // CheckSpecialCalendar(ref calendarId, ref localeName); // Numbers ret &= CallGetCalendarInfoEx(localeName, calendarId, CAL_ITWODIGITYEARMAX | useOverrides, out this.iTwoDigitYearMax); // Strings ret &= CallGetCalendarInfoEx(localeName, calendarId, CAL_SCALNAME, out this.sNativeName); ret &= CallGetCalendarInfoEx(localeName, calendarId, CAL_SMONTHDAY | useOverrides, out this.sMonthDay); // String Arrays // Formats ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SSHORTDATE, LOCALE_SSHORTDATE | useOverrides, out this.saShortDates); ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SLONGDATE, LOCALE_SLONGDATE | useOverrides, out this.saLongDates); // Get the YearMonth pattern. ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SYEARMONTH, LOCALE_SYEARMONTH, out this.saYearMonths); // Day & Month Names // These are all single calType entries, 1 per day, so we have to make 7 or 13 calls to collect all the names // Day // Note that we're off-by-one since managed starts on sunday and windows starts on monday ret &= GetCalendarDayInfo(localeName, calendarId, CAL_SDAYNAME7, out this.saDayNames); ret &= GetCalendarDayInfo(localeName, calendarId, CAL_SABBREVDAYNAME7, out this.saAbbrevDayNames); // Month names ret &= GetCalendarMonthInfo(localeName, calendarId, CAL_SMONTHNAME1, out this.saMonthNames); ret &= GetCalendarMonthInfo(localeName, calendarId, CAL_SABBREVMONTHNAME1, out this.saAbbrevMonthNames); // // The following LCTYPE are not supported in some platforms. If the call fails, // don't return a failure. // GetCalendarDayInfo(localeName, calendarId, CAL_SSHORTESTDAYNAME7, out this.saSuperShortDayNames); // Gregorian may have genitive month names if (calendarId == CalendarId.GREGORIAN) { GetCalendarMonthInfo(localeName, calendarId, CAL_SMONTHNAME1 | CAL_RETURN_GENITIVE_NAMES, out this.saMonthGenitiveNames); GetCalendarMonthInfo(localeName, calendarId, CAL_SABBREVMONTHNAME1 | CAL_RETURN_GENITIVE_NAMES, out this.saAbbrevMonthGenitiveNames); } // Calendar Parts Names // This doesn't get always get localized names for gregorian (not available in windows < 7) // so: eg: coreclr on win < 7 won't get these CallEnumCalendarInfo(localeName, calendarId, CAL_SERASTRING, 0, out this.saEraNames); CallEnumCalendarInfo(localeName, calendarId, CAL_SABBREVERASTRING, 0, out this.saAbbrevEraNames); // // Calendar Era Info // Note that calendar era data (offsets, etc) is hard coded for each calendar since this // data is implementation specific and not dynamic (except perhaps Japanese) // // Clean up the escaping of the formats this.saShortDates = CultureData.ReescapeWin32Strings(this.saShortDates); this.saLongDates = CultureData.ReescapeWin32Strings(this.saLongDates); this.saYearMonths = CultureData.ReescapeWin32Strings(this.saYearMonths); this.sMonthDay = CultureData.ReescapeWin32String(this.sMonthDay); return ret; } // Get native two digit year max internal static int GetTwoDigitYearMax(CalendarId calendarId) { int twoDigitYearMax = -1; if (!CallGetCalendarInfoEx(null, calendarId, (uint)CAL_ITWODIGITYEARMAX, out twoDigitYearMax)) { twoDigitYearMax = -1; } return twoDigitYearMax; } internal static CalendarData GetCalendarData(CalendarId calendarId) { // // Get a calendar. // Unfortunately we depend on the locale in the OS, so we need a locale // no matter what. So just get the appropriate calendar from the // appropriate locale here // // Get a culture name // TODO: Note that this doesn't handle the new calendars (lunisolar, etc) String culture = CalendarIdToCultureName(calendarId); // Return our calendar return CultureInfo.GetCultureInfo(culture).m_cultureData.GetCalendar(calendarId); } // Call native side to figure out which calendars are allowed internal static int GetCalendars(String localeName, bool useUserOverride, CalendarId[] calendars) { EnumCalendarsData data = new EnumCalendarsData(); data.userOverride = 0; data.calendars = new LowLevelList<int>(); // First call GetLocaleInfo if necessary if (useUserOverride) { // They want user overrides, see if the user calendar matches the input calendar int userCalendar = Interop.mincore.GetLocaleInfoExInt(localeName, LOCALE_ICALENDARTYPE); // If we got a default, then use it as the first calendar if (userCalendar != 0) { data.userOverride = userCalendar; data.calendars.Add(userCalendar); } } GCHandle contextHandle = GCHandle.Alloc(data); try { // Now call the enumeration API. Work is done by our callback function IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, uint, IntPtr, IntPtr, Interop.BOOL>>(EnumCalendarsCallback); Interop.mincore.EnumCalendarInfoExEx(callback, localeName, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, (IntPtr)contextHandle); } finally { contextHandle.Free(); } // Copy to the output array for (int i = 0; i < Math.Min(calendars.Length, data.calendars.Count); i++) calendars[i] = (CalendarId)data.calendars[i]; // Now we have a list of data, return the count return data.calendars.Count; } private static bool SystemSupportsTaiwaneseCalendar() { string data; // Taiwanese calendar get listed as one of the optional zh-TW calendars only when having zh-TW UI return CallGetCalendarInfoEx("zh-TW", CalendarId.TAIWAN, CAL_SCALNAME, out data); } // PAL Layer ends here private const uint CAL_RETURN_NUMBER = 0x20000000; private const uint CAL_RETURN_GENITIVE_NAMES = 0x10000000; private const uint CAL_NOUSEROVERRIDE = 0x80000000; private const uint CAL_SCALNAME = 0x00000002; private const uint CAL_SMONTHDAY = 0x00000038; private const uint CAL_SSHORTDATE = 0x00000005; private const uint CAL_SLONGDATE = 0x00000006; private const uint CAL_SYEARMONTH = 0x0000002f; private const uint CAL_SDAYNAME7 = 0x0000000d; private const uint CAL_SABBREVDAYNAME7 = 0x00000014; private const uint CAL_SMONTHNAME1 = 0x00000015; private const uint CAL_SABBREVMONTHNAME1 = 0x00000022; private const uint CAL_SSHORTESTDAYNAME7 = 0x00000037; private const uint CAL_SERASTRING = 0x00000004; private const uint CAL_SABBREVERASTRING = 0x00000039; private const uint CAL_ICALINTVALUE = 0x00000001; private const uint CAL_ITWODIGITYEARMAX = 0x00000030; private const uint ENUM_ALL_CALENDARS = 0xffffffff; private const uint LOCALE_SSHORTDATE = 0x0000001F; private const uint LOCALE_SLONGDATE = 0x00000020; private const uint LOCALE_SYEARMONTH = 0x00001006; private const uint LOCALE_ICALENDARTYPE = 0x00001009; private static String CalendarIdToCultureName(CalendarId calendarId) { switch (calendarId) { case CalendarId.GREGORIAN_US: return "fa-IR"; // "fa-IR" Iran case CalendarId.JAPAN: return "ja-JP"; // "ja-JP" Japan case CalendarId.TAIWAN: return "zh-TW"; // zh-TW Taiwan case CalendarId.KOREA: return "ko-KR"; // "ko-KR" Korea case CalendarId.HIJRI: case CalendarId.GREGORIAN_ARABIC: case CalendarId.UMALQURA: return "ar-SA"; // "ar-SA" Saudi Arabia case CalendarId.THAI: return "th-TH"; // "th-TH" Thailand case CalendarId.HEBREW: return "he-IL"; // "he-IL" Israel case CalendarId.GREGORIAN_ME_FRENCH: return "ar-DZ"; // "ar-DZ" Algeria case CalendarId.GREGORIAN_XLIT_ENGLISH: case CalendarId.GREGORIAN_XLIT_FRENCH: return "ar-IQ"; // "ar-IQ"; Iraq default: // Default to gregorian en-US break; } return "en-US"; } //////////////////////////////////////////////////////////////////////// // // For calendars like Gregorain US/Taiwan/UmAlQura, they are not available // in all OS or all localized versions of OS. // If OS does not support these calendars, we will fallback by using the // appropriate fallback calendar and locale combination to retrieve data from OS. // // Parameters: // __deref_inout pCalendarInt: // Pointer to the calendar ID. This will be updated to new fallback calendar ID if needed. // __in_out pLocaleNameStackBuffer // Pointer to the StackSString object which holds the locale name to be checked. // This will be updated to new fallback locale name if needed. // //////////////////////////////////////////////////////////////////////// private static void CheckSpecialCalendar(ref CalendarId calendar, ref string localeName) { string data; // Gregorian-US isn't always available in the OS, however it is the same for all locales switch (calendar) { case CalendarId.GREGORIAN_US: // See if this works if (!CallGetCalendarInfoEx(localeName, calendar, CAL_SCALNAME, out data)) { // Failed, set it to a locale (fa-IR) that's alway has Gregorian US available in the OS localeName = "fa-IR"; } // See if that works if (!CallGetCalendarInfoEx(localeName, calendar, CAL_SCALNAME, out data)) { // Failed again, just use en-US with the gregorian calendar localeName = "en-US"; calendar = CalendarId.GREGORIAN; } break; case CalendarId.TAIWAN: // Taiwan calendar data is not always in all language version of OS due to Geopolical reasons. // It is only available in zh-TW localized versions of Windows. // Let's check if OS supports it. If not, fallback to Greogrian localized for Taiwan calendar. if (!SystemSupportsTaiwaneseCalendar()) { calendar = CalendarId.GREGORIAN; } break; } } private static bool CallGetCalendarInfoEx(string localeName, CalendarId calendar, uint calType, out int data) { return (Interop.mincore.GetCalendarInfoEx(localeName, (uint)calendar, IntPtr.Zero, calType | CAL_RETURN_NUMBER, IntPtr.Zero, 0, out data) != 0); } private static unsafe bool CallGetCalendarInfoEx(string localeName, CalendarId calendar, uint calType, out string data) { const int BUFFER_LENGTH = 80; // The maximum size for values returned from GetCalendarInfoEx is 80 characters. char* buffer = stackalloc char[BUFFER_LENGTH]; int ret = Interop.mincore.GetCalendarInfoEx(localeName, (uint)calendar, IntPtr.Zero, calType, (IntPtr)buffer, BUFFER_LENGTH, IntPtr.Zero); if (ret > 0) { if (buffer[ret - 1] == '\0') { ret--; // don't include the null termination in the string } data = new string(buffer, 0, ret); return true; } data = ""; return false; } // Context for EnumCalendarInfoExEx callback. private class EnumData { public string userOverride; public LowLevelList<string> strings; } // EnumCalendarInfoExEx callback itself. [NativeCallable(CallingConvention = CallingConvention.StdCall)] private static unsafe Interop.BOOL EnumCalendarInfoCallback(IntPtr lpCalendarInfoString, uint calendar, IntPtr pReserved, IntPtr lParam) { EnumData context = (EnumData)((GCHandle)lParam).Target; try { string calendarInfo = new string((char*)lpCalendarInfoString); // If we had a user override, check to make sure this differs if (context.userOverride != calendarInfo) context.strings.Add(calendarInfo); return Interop.BOOL.TRUE; } catch (Exception) { return Interop.BOOL.FALSE; } } private static unsafe bool CallEnumCalendarInfo(string localeName, CalendarId calendar, uint calType, uint lcType, out string[] data) { EnumData context = new EnumData(); context.userOverride = null; context.strings = new LowLevelList<string>(); // First call GetLocaleInfo if necessary if (((lcType != 0) && ((lcType & CAL_NOUSEROVERRIDE) == 0)) && // Get user locale, see if it matches localeName. // Note that they should match exactly, including letter case GetUserDefaultLocaleName() == localeName) { // They want user overrides, see if the user calendar matches the input calendar CalendarId userCalendar = (CalendarId)Interop.mincore.GetLocaleInfoExInt(localeName, LOCALE_ICALENDARTYPE); // If the calendars were the same, see if the locales were the same if (userCalendar == calendar) { // They matched, get the user override since locale & calendar match string res = Interop.mincore.GetLocaleInfoEx(localeName, lcType); // if it succeeded remember the override for the later callers if (res != "") { // Remember this was the override (so we can look for duplicates later in the enum function) context.userOverride = res; // Add to the result strings. context.strings.Add(res); } } } GCHandle contextHandle = GCHandle.Alloc(context); try { // Now call the enumeration API. Work is done by our callback function IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, uint, IntPtr, IntPtr, Interop.BOOL>>(EnumCalendarInfoCallback); Interop.mincore.EnumCalendarInfoExEx(callback, localeName, (uint)calendar, null, calType, (IntPtr)contextHandle); } finally { contextHandle.Free(); } // Now we have a list of data, fail if we didn't find anything. if (context.strings.Count == 0) { data = null; return false; } string[] output = context.strings.ToArray(); if (calType == CAL_SABBREVERASTRING || calType == CAL_SERASTRING) { // Eras are enumerated backwards. (oldest era name first, but // Japanese calendar has newest era first in array, and is only // calendar with multiple eras) Array.Reverse(output, 0, output.Length); } data = output; return true; } //////////////////////////////////////////////////////////////////////// // // Get the native day names // // NOTE: There's a disparity between .Net & windows day orders, the input day should // start with Sunday // // Parameters: // OUT pOutputStrings The output string[] value. // //////////////////////////////////////////////////////////////////////// private static bool GetCalendarDayInfo(string localeName, CalendarId calendar, uint calType, out string[] outputStrings) { bool result = true; // // We'll need a new array of 7 items // string[] results = new string[7]; // Get each one of them for (int i = 0; i < 7; i++, calType++) { result &= CallGetCalendarInfoEx(localeName, calendar, calType, out results[i]); // On the first iteration we need to go from CAL_SDAYNAME7 to CAL_SDAYNAME1, so subtract 7 before the ++ happens // This is because the framework starts on sunday and windows starts on monday when counting days if (i == 0) calType -= 7; } outputStrings = results; return result; } //////////////////////////////////////////////////////////////////////// // // Get the native month names // // Parameters: // OUT pOutputStrings The output string[] value. // //////////////////////////////////////////////////////////////////////// private static bool GetCalendarMonthInfo(string localeName, CalendarId calendar, uint calType, out string[] outputStrings) { // // We'll need a new array of 13 items // string[] results = new string[13]; // Get each one of them for (int i = 0; i < 13; i++, calType++) { if (!CallGetCalendarInfoEx(localeName, calendar, calType, out results[i])) results[i] = ""; } outputStrings = results; return true; } // // struct to help our calendar data enumaration callback // private class EnumCalendarsData { public int userOverride; // user override value (if found) public LowLevelList<int> calendars; // list of calendars found so far } [NativeCallable(CallingConvention = CallingConvention.StdCall)] private static Interop.BOOL EnumCalendarsCallback(IntPtr lpCalendarInfoString, uint calendar, IntPtr reserved, IntPtr lParam) { EnumCalendarsData context = (EnumCalendarsData)((GCHandle)lParam).Target; try { // If we had a user override, check to make sure this differs if (context.userOverride != calendar) context.calendars.Add((int)calendar); return Interop.BOOL.TRUE; } catch (Exception) { return Interop.BOOL.FALSE; } } private static unsafe String GetUserDefaultLocaleName() { const int LOCALE_NAME_MAX_LENGTH = 85; const uint LOCALE_SNAME = 0x0000005c; const string LOCALE_NAME_USER_DEFAULT = null; int result; char* localeName = stackalloc char[LOCALE_NAME_MAX_LENGTH]; result = Interop.mincore.GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SNAME, localeName, LOCALE_NAME_MAX_LENGTH); return result <= 0 ? "" : new String(localeName, 0, result - 1); // exclude the null termination } } }
// The MIT License (MIT) // // CoreTweet - A .NET Twitter Library supporting Twitter API 1.1 // Copyright (c) 2013-2015 CoreTweet Development Team // // 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.Net; using System.Text; using CoreTweet.Core; using Newtonsoft.Json.Linq; namespace CoreTweet { /// <summary> /// Provides a set of static (Shared in Visual Basic) methods for OAuth authentication. /// </summary> public static partial class OAuth { /// <summary> /// Represents an OAuth session. /// </summary> public class OAuthSession { /// <summary> /// Gets or sets the consumer key. /// </summary> public string ConsumerKey { get; set; } /// <summary> /// Gets or sets the consumer secret. /// </summary> public string ConsumerSecret { get; set; } /// <summary> /// Gets or sets the request token. /// </summary> public string RequestToken { get; set; } /// <summary> /// Gets or sets the request token secret. /// </summary> public string RequestTokenSecret { get; set; } /// <summary> /// Gets or sets the options of the connection. /// </summary> public ConnectionOptions ConnectionOptions { get; set; } /// <summary> /// Gets the authorize URL. /// </summary> public Uri AuthorizeUri { get { var options = this.ConnectionOptions ?? new ConnectionOptions(); return new Uri(InternalUtils.GetUrl(options, options.ApiUrl, false, "oauth/authorize") + "?oauth_token=" + RequestToken); } } } private static Uri GetRequestTokenUrl(ConnectionOptions options) { if (options == null) options = new ConnectionOptions(); return new Uri(InternalUtils.GetUrl(options, options.ApiUrl, false, "oauth/request_token")); } private static Uri GetAccessTokenUrl(ConnectionOptions options) { if (options == null) options = new ConnectionOptions(); return new Uri(InternalUtils.GetUrl(options, options.ApiUrl, false, "oauth/access_token")); } #if !(PCL || WIN_RT || WP) /// <summary> /// <para>Generates the authorize URI.</para> /// <para>Then call <see cref="GetTokens"/> after get the pin code.</para> /// </summary> /// <param name="consumerKey">The Consumer key.</param> /// <param name="consumerSecret">The Consumer secret.</param> /// <param name="oauthCallback"> /// <para>For OAuth 1.0a compliance this parameter is required.</para> /// <para>The value you specify here will be used as the URL a user is redirected to should they approve your application's access to their account.</para> /// <para>Set this to oob for out-of-band pin mode.</para> /// <para>This is also how you specify custom callbacks for use in desktop/mobile applications.</para> /// <para>Always send an oauth_callback on this step, regardless of a pre-registered callback.</para> /// </param> /// <param name="options">The connection options for the request.</param> /// <returns>The authorize URI.</returns> public static OAuthSession Authorize(string consumerKey, string consumerSecret, string oauthCallback = "oob", ConnectionOptions options = null) { var reqUrl = GetRequestTokenUrl(options); // Note: Twitter says, // "If you're using HTTP-header based OAuth, you shouldn't include oauth_* parameters in the POST body or querystring." var prm = new Dictionary<string,object>(); if(!string.IsNullOrEmpty(oauthCallback)) prm.Add("oauth_callback", oauthCallback); var header = Tokens.Create(consumerKey, consumerSecret, null, null) .CreateAuthorizationHeader(MethodType.Post, reqUrl, prm); try { var dic = from x in Request.HttpPost(reqUrl, prm, header, options).Use() from y in new StreamReader(x.GetResponseStream()).Use() select y.ReadToEnd() .Split('&') .Where(z => z.Contains('=')) .Select(z => z.Split('=')) .ToDictionary(z => z[0], z => z[1]); return new OAuthSession() { RequestToken = dic["oauth_token"], RequestTokenSecret = dic["oauth_token_secret"], ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, ConnectionOptions = options }; } catch(WebException ex) { var tex = TwitterException.Create(ex); if(tex != null) throw tex; throw; } } /// <summary> /// <para>Gets the OAuth tokens.</para> /// <para>Be sure to call <see cref="Authorize"/> before call this method.</para> /// </summary> /// <param name="session">The OAuth session.</param> /// <param name="pin">The pin code.</param> /// <returns>The tokens.</returns> public static Tokens GetTokens(this OAuthSession session, string pin) { var reqUrl = GetAccessTokenUrl(session.ConnectionOptions); var prm = new Dictionary<string,object>() { { "oauth_verifier", pin } }; var header = Tokens.Create(session.ConsumerKey, session.ConsumerSecret, session.RequestToken, session.RequestTokenSecret) .CreateAuthorizationHeader(MethodType.Post, reqUrl, prm); try { var dic = from x in Request.HttpPost(reqUrl, prm, header, session.ConnectionOptions).Use() from y in new StreamReader(x.GetResponseStream()).Use() select y.ReadToEnd() .Split('&') .Where(z => z.Contains('=')) .Select(z => z.Split('=')) .ToDictionary(z => z[0], z => z[1]); var t = Tokens.Create(session.ConsumerKey, session.ConsumerSecret, dic["oauth_token"], dic["oauth_token_secret"], long.Parse(dic["user_id"]), dic["screen_name"]); t.ConnectionOptions = session.ConnectionOptions; return t; } catch(WebException ex) { var tex = TwitterException.Create(ex); if(tex != null) throw tex; throw; } } #endif } /// <summary> /// Provides a set of static (Shared in Visual Basic) methods for OAuth 2 Authentication. /// </summary> public static partial class OAuth2 { private static Uri GetAccessTokenUrl(ConnectionOptions options) { if (options == null) options = new ConnectionOptions(); return new Uri(InternalUtils.GetUrl(options, options.ApiUrl, false, "oauth2/token")); } private static Uri GetInvalidateTokenUrl(ConnectionOptions options) { if (options == null) options = new ConnectionOptions(); return new Uri(InternalUtils.GetUrl(options, options.ApiUrl, false, "oauth2/invalidate_token")); } private static string CreateCredentials(string consumerKey, string consumerSecret) { return "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(consumerKey + ":" + consumerSecret)); } #if !(PCL || WIN_RT || WP) /// <summary> /// Gets the OAuth 2 Bearer Token. /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="options">The connection options for the request.</param> /// <returns>The tokens.</returns> public static OAuth2Token GetToken(string consumerKey, string consumerSecret, ConnectionOptions options = null) { try { var token = from x in Request.HttpPost( GetAccessTokenUrl(options), new Dictionary<string, object>() { { "grant_type", "client_credentials" } }, // At this time, only client_credentials is allowed. CreateCredentials(consumerKey, consumerSecret), options).Use() from y in new StreamReader(x.GetResponseStream()).Use() select (string)JObject.Parse(y.ReadToEnd())["access_token"]; var t = OAuth2Token.Create(consumerKey, consumerSecret, token); t.ConnectionOptions = options; return t; } catch(WebException ex) { var tex = TwitterException.Create(ex); if(tex != null) throw tex; throw; } } /// <summary> /// Invalidates the OAuth 2 Bearer Token. /// </summary> /// <param name="tokens">An instance of <see cref="OAuth2Token"/>.</param> /// <returns>The invalidated token.</returns> public static string InvalidateToken(this OAuth2Token tokens) { try { return from x in Request.HttpPost( GetInvalidateTokenUrl(tokens.ConnectionOptions), new Dictionary<string, object>() { { "access_token", Uri.UnescapeDataString(tokens.BearerToken) } }, CreateCredentials(tokens.ConsumerKey, tokens.ConsumerSecret), tokens.ConnectionOptions).Use() from y in new StreamReader(x.GetResponseStream()).Use() select (string)JObject.Parse(y.ReadToEnd())["access_token"]; } catch(WebException ex) { var tex = TwitterException.Create(ex); if(tex != null) throw tex; throw; } } #endif } }
using System; using Org.BouncyCastle.Crypto.Parameters; namespace Org.BouncyCastle.Crypto.Engines { /** * A class that provides a basic International Data Encryption Algorithm (IDEA) engine. * <p> * This implementation is based on the "HOWTO: INTERNATIONAL DATA ENCRYPTION ALGORITHM" * implementation summary by Fauzan Mirza (F.U.Mirza@sheffield.ac.uk). (baring 1 typo at the * end of the mulinv function!). * </p> * <p> * It can be found at ftp://ftp.funet.fi/pub/crypt/cryptography/symmetric/idea/ * </p> * <p> * Note 1: This algorithm is patented in the USA, Japan, and Europe including * at least Austria, France, Germany, Italy, Netherlands, Spain, Sweden, Switzerland * and the United Kingdom. Non-commercial use is free, however any commercial * products are liable for royalties. Please see * <a href="http://www.mediacrypt.com">www.mediacrypt.com</a> for * further details. This announcement has been included at the request of * the patent holders. * </p> * <p> * Note 2: Due to the requests concerning the above, this algorithm is now only * included in the extended assembly. It is not included in the default distributions. * </p> */ public class IdeaEngine : IBlockCipher { private const int BLOCK_SIZE = 8; private int[] workingKey; /** * standard constructor. */ public IdeaEngine() { } /** * initialise an IDEA cipher. * * @param forEncryption whether or not we are for encryption. * @param parameters the parameters required to set up the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public virtual void Init( bool forEncryption, ICipherParameters parameters) { if (!(parameters is KeyParameter)) throw new ArgumentException("invalid parameter passed to IDEA init - " + parameters.GetType().ToString()); workingKey = GenerateWorkingKey(forEncryption, ((KeyParameter)parameters).GetKey()); } public virtual string AlgorithmName { get { return "IDEA"; } } public virtual bool IsPartialBlockOkay { get { return false; } } public virtual int GetBlockSize() { return BLOCK_SIZE; } public virtual int ProcessBlock( byte[] input, int inOff, byte[] output, int outOff) { if (workingKey == null) throw new InvalidOperationException("IDEA engine not initialised"); Check.DataLength(input, inOff, BLOCK_SIZE, "input buffer too short"); Check.OutputLength(output, outOff, BLOCK_SIZE, "output buffer too short"); IdeaFunc(workingKey, input, inOff, output, outOff); return BLOCK_SIZE; } public virtual void Reset() { } private static readonly int MASK = 0xffff; private static readonly int BASE = 0x10001; private int BytesToWord( byte[] input, int inOff) { return ((input[inOff] << 8) & 0xff00) + (input[inOff + 1] & 0xff); } private void WordToBytes( int word, byte[] outBytes, int outOff) { outBytes[outOff] = (byte)((uint) word >> 8); outBytes[outOff + 1] = (byte)word; } /** * return x = x * y where the multiplication is done modulo * 65537 (0x10001) (as defined in the IDEA specification) and * a zero input is taken to be 65536 (0x10000). * * @param x the x value * @param y the y value * @return x = x * y */ private int Mul( int x, int y) { if (x == 0) { x = (BASE - y); } else if (y == 0) { x = (BASE - x); } else { int p = x * y; y = p & MASK; x = (int) ((uint) p >> 16); x = y - x + ((y < x) ? 1 : 0); } return x & MASK; } private void IdeaFunc( int[] workingKey, byte[] input, int inOff, byte[] outBytes, int outOff) { int x0, x1, x2, x3, t0, t1; int keyOff = 0; x0 = BytesToWord(input, inOff); x1 = BytesToWord(input, inOff + 2); x2 = BytesToWord(input, inOff + 4); x3 = BytesToWord(input, inOff + 6); for (int round = 0; round < 8; round++) { x0 = Mul(x0, workingKey[keyOff++]); x1 += workingKey[keyOff++]; x1 &= MASK; x2 += workingKey[keyOff++]; x2 &= MASK; x3 = Mul(x3, workingKey[keyOff++]); t0 = x1; t1 = x2; x2 ^= x0; x1 ^= x3; x2 = Mul(x2, workingKey[keyOff++]); x1 += x2; x1 &= MASK; x1 = Mul(x1, workingKey[keyOff++]); x2 += x1; x2 &= MASK; x0 ^= x1; x3 ^= x2; x1 ^= t1; x2 ^= t0; } WordToBytes(Mul(x0, workingKey[keyOff++]), outBytes, outOff); WordToBytes(x2 + workingKey[keyOff++], outBytes, outOff + 2); /* NB: Order */ WordToBytes(x1 + workingKey[keyOff++], outBytes, outOff + 4); WordToBytes(Mul(x3, workingKey[keyOff]), outBytes, outOff + 6); } /** * The following function is used to expand the user key to the encryption * subkey. The first 16 bytes are the user key, and the rest of the subkey * is calculated by rotating the previous 16 bytes by 25 bits to the left, * and so on until the subkey is completed. */ private int[] ExpandKey( byte[] uKey) { int[] key = new int[52]; if (uKey.Length < 16) { byte[] tmp = new byte[16]; Array.Copy(uKey, 0, tmp, tmp.Length - uKey.Length, uKey.Length); uKey = tmp; } for (int i = 0; i < 8; i++) { key[i] = BytesToWord(uKey, i * 2); } for (int i = 8; i < 52; i++) { if ((i & 7) < 6) { key[i] = ((key[i - 7] & 127) << 9 | key[i - 6] >> 7) & MASK; } else if ((i & 7) == 6) { key[i] = ((key[i - 7] & 127) << 9 | key[i - 14] >> 7) & MASK; } else { key[i] = ((key[i - 15] & 127) << 9 | key[i - 14] >> 7) & MASK; } } return key; } /** * This function computes multiplicative inverse using Euclid's Greatest * Common Divisor algorithm. Zero and one are self inverse. * <p> * i.e. x * MulInv(x) == 1 (modulo BASE) * </p> */ private int MulInv( int x) { int t0, t1, q, y; if (x < 2) { return x; } t0 = 1; t1 = BASE / x; y = BASE % x; while (y != 1) { q = x / y; x = x % y; t0 = (t0 + (t1 * q)) & MASK; if (x == 1) { return t0; } q = y / x; y = y % x; t1 = (t1 + (t0 * q)) & MASK; } return (1 - t1) & MASK; } /** * Return the additive inverse of x. * <p> * i.e. x + AddInv(x) == 0 * </p> */ int AddInv( int x) { return (0 - x) & MASK; } /** * The function to invert the encryption subkey to the decryption subkey. * It also involves the multiplicative inverse and the additive inverse functions. */ private int[] InvertKey( int[] inKey) { int t1, t2, t3, t4; int p = 52; /* We work backwards */ int[] key = new int[52]; int inOff = 0; t1 = MulInv(inKey[inOff++]); t2 = AddInv(inKey[inOff++]); t3 = AddInv(inKey[inOff++]); t4 = MulInv(inKey[inOff++]); key[--p] = t4; key[--p] = t3; key[--p] = t2; key[--p] = t1; for (int round = 1; round < 8; round++) { t1 = inKey[inOff++]; t2 = inKey[inOff++]; key[--p] = t2; key[--p] = t1; t1 = MulInv(inKey[inOff++]); t2 = AddInv(inKey[inOff++]); t3 = AddInv(inKey[inOff++]); t4 = MulInv(inKey[inOff++]); key[--p] = t4; key[--p] = t2; /* NB: Order */ key[--p] = t3; key[--p] = t1; } t1 = inKey[inOff++]; t2 = inKey[inOff++]; key[--p] = t2; key[--p] = t1; t1 = MulInv(inKey[inOff++]); t2 = AddInv(inKey[inOff++]); t3 = AddInv(inKey[inOff++]); t4 = MulInv(inKey[inOff]); key[--p] = t4; key[--p] = t3; key[--p] = t2; key[--p] = t1; return key; } private int[] GenerateWorkingKey( bool forEncryption, byte[] userKey) { if (forEncryption) { return ExpandKey(userKey); } else { return InvertKey(ExpandKey(userKey)); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using NUnit.Framework; namespace ExcelDataReader.Tests { public class ExcelOpenXmlReaderTest : ExcelOpenXmlReaderBase { protected override IExcelDataReader OpenReader(Stream stream, ExcelReaderConfiguration configuration = null) { return ExcelReaderFactory.CreateOpenXmlReader(stream, configuration); } protected override Stream OpenStream(string name) { return Configuration.GetTestWorkbook(name + ".xlsx"); } /// <inheritdoc /> protected override DateTime GitIssue82TodayDate => new DateTime(2013, 4, 19); [Test] public void FailTest() { var expectedException = typeof(Exceptions.HeaderException); var exception = Assert.Throws(expectedException, () => { using (ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("TestFail_Binary.xls"))) { } }); Assert.AreEqual("Invalid file signature.", exception.Message); } [Test] public void Issue4145() { using (IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("Test_Issue_4145.xlsx"))) { Assert.DoesNotThrow(() => excelReader.AsDataSet(Configuration.FirstRowColumnNamesConfiguration)); while (excelReader.Read()) { } } } [Test] public void IssueFileLock5161() { using (IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("TestMultiSheet.xlsx"))) { // read something from the 3rd sheet int i = 0; do { if (i == 0) { excelReader.Read(); } } while (excelReader.NextResult()); // bug was exposed here } } [Test] public void Issue11522OpenXml() { using (IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("Test_Issue_11522_OpenXml.xlsx"))) { DataSet result = excelReader.AsDataSet(Configuration.FirstRowColumnNamesConfiguration); Assert.AreEqual(11, result.Tables[0].Columns.Count); Assert.AreEqual(1, result.Tables[0].Rows.Count); Assert.AreEqual("TestNewButton", result.Tables[0].Rows[0][0]); Assert.AreEqual("677", result.Tables[0].Rows[0][1]); Assert.AreEqual("u77", result.Tables[0].Rows[0][2]); Assert.AreEqual("u766", result.Tables[0].Rows[0][3]); Assert.AreEqual("y66", result.Tables[0].Rows[0][4]); Assert.AreEqual("F", result.Tables[0].Rows[0][5]); Assert.AreEqual(DBNull.Value, result.Tables[0].Rows[0][6]); Assert.AreEqual(DBNull.Value, result.Tables[0].Rows[0][7]); Assert.AreEqual(DBNull.Value, result.Tables[0].Rows[0][8]); Assert.AreEqual(DBNull.Value, result.Tables[0].Rows[0][9]); Assert.AreEqual(DBNull.Value, result.Tables[0].Rows[0][10]); } } /* #if !LEGACY [Test] public void ZipWorker_Extract_Test() { var zipper = new ZipWorker(FileSystem.Current, new FileConfiguration.)); //this first one isn't a valid xlsx so we are expecting no side effects in the directory tree zipper.Extract(Configuration.GetTestWorkbook("TestChess")); Assert.AreEqual(false, Directory.Exists(zipper.TempPath)); Assert.AreEqual(false, zipper.IsValid); //this one is valid so we expect to find the files zipper.Extract(Configuration.GetTestWorkbook("TestOpenXml")); Assert.AreEqual(true, Directory.Exists(zipper.TempPath)); Assert.AreEqual(true, zipper.IsValid); string tPath = zipper.TempPath; //make sure that dispose gets rid of the files zipper.Dispose(); Assert.AreEqual(false, Directory.Exists(tPath)); } private class FileConfiguration.: IFileConfiguration. { public string GetTempPath() { return System.IO.Path.GetTempPath(); } } #endif */ [Test] public void TestGoogleSourced() { using (IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("Test_googlesourced.xlsx"))) { var dataSet = excelReader.AsDataSet(Configuration.FirstRowColumnNamesConfiguration); Assert.AreEqual("9583638582", dataSet.Tables[0].Rows[0][0].ToString()); Assert.AreEqual(4, dataSet.Tables[0].Rows.Count); Assert.AreEqual(6, dataSet.Tables[0].Columns.Count); } } [Test] public void TestIssue12667GoogleExportMissingColumns() { using (IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("Test_Issue_12667_GoogleExport_MissingColumns.xlsx"))) { var dataSet = excelReader.AsDataSet(Configuration.FirstRowColumnNamesConfiguration); Assert.AreEqual(7, dataSet.Tables[0].Columns.Count); // 6 with data + 1 that is present but no data in it Assert.AreEqual(0, dataSet.Tables[0].Rows.Count); } } [Test] public void IssueGit142() { using (IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("Test_git_Issue_142.xlsx"))) { var dataSet = excelReader.AsDataSet(); Assert.AreEqual(4, dataSet.Tables[0].Columns.Count); } } /// <summary> /// Sheet has no [dimension] and/or no [cols]. /// Sheet has no [styles]. /// Each row [row] has no "r" attribute. /// Each cell [c] has no "r" attribute. /// </summary> [Test] public void IssueNoStylesNoRAttribute() { using (IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("Test_Issue_NoStyles_NoRAttribute.xlsx"))) { DataSet result = excelReader.AsDataSet(); Assert.IsTrue(result.Tables.Count > 0); Assert.AreEqual(39, result.Tables[0].Rows.Count); Assert.AreEqual(18, result.Tables[0].Columns.Count); Assert.AreEqual("ROW NUMBER 5", result.Tables[0].Rows[4][4].ToString()); excelReader.Close(); } } [Test] public void NoDimensionOrCellReferenceAttribute() { // 20170306_Daily Package GPR 250 Index EUR Overview.xlsx using (IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("NoDimensionOrCellReferenceAttribute.xlsx"))) { DataSet result = excelReader.AsDataSet(); Assert.AreEqual(2, result.Tables.Count); Assert.AreEqual(8, result.Tables[0].Columns.Count, "Sheet0 Columns"); Assert.AreEqual(7, result.Tables[0].Rows.Count, "Sheet0 Rows"); Assert.AreEqual(8, result.Tables[1].Columns.Count, "Sheet1 Columns"); Assert.AreEqual(20, result.Tables[1].Rows.Count, "Sheet1 Rows"); } } [Test] public void CellValueIso8601Date() { using (IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("Test_git_issue_221.xlsx"))) { DataSet result = excelReader.AsDataSet(); Assert.AreEqual(new DateTime(2017, 3, 16), result.Tables[0].Rows[0][0]); } } [Test] public void CellFormat49() { using (IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("Format49_@.xlsx"))) { DataSet result = excelReader.AsDataSet(); // ExcelDataReader used to convert numbers formatted with NumFmtId=49/@ to culture-specific strings. // This behaviour changed in v3 to return the original value: // Assert.That(result.Tables[0].Rows[0].ItemArray, Is.EqualTo(new[] { "2010-05-05", "1.1", "2,2", "123", "2,2" })); Assert.That(result.Tables[0].Rows[0].ItemArray, Is.EqualTo(new object[] { "2010-05-05", "1.1", 2.2000000000000002D, 123.0D, "2,2" })); } } [Test] public void GitIssue97() { using (IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("fillreport.xlsx"))) { // fillreport.xlsx was generated by a third party and uses badly formatted cell references with only numerals. DataSet result = excelReader.AsDataSet(); Assert.AreEqual(1, result.Tables.Count); Assert.AreEqual(20, result.Tables[0].Rows.Count); Assert.AreEqual(10, result.Tables[0].Columns.Count); Assert.AreEqual("Account Number", result.Tables[0].Rows[1][0]); Assert.AreEqual("Trader", result.Tables[0].Rows[1][1]); } } [Test] public void GitIssue68NullSheetPath() { using (var excelReader = ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("Test_git_issue_68_NullSheetPath.xlsm"))) { DataSet result = excelReader.AsDataSet(); Assert.AreEqual(2, result.Tables[0].Columns.Count); Assert.AreEqual(1, result.Tables[0].Rows.Count); } } [Test] public void GitIssue53CachedFormulaStringType() { using (var excelReader = ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("Test_git_issue_53_Cached_Formula_String_Type.xlsx"))) { var dataSet = excelReader.AsDataSet(Configuration.FirstRowColumnNamesConfiguration); // Ensure that parseable, numeric cached formula values are read as a double Assert.IsInstanceOf<double>(dataSet.Tables[0].Rows[0][2]); Assert.AreEqual(3D, dataSet.Tables[0].Rows[0][2]); // Ensure that non-parseable, non-numeric cached formula values are read as a string Assert.IsInstanceOf<string>(dataSet.Tables[0].Rows[1][2]); Assert.AreEqual("AB", dataSet.Tables[0].Rows[1][2]); // Ensure that parseable, non-numeric cached formula values are read as a string Assert.IsInstanceOf<string>(dataSet.Tables[0].Rows[2][2]); Assert.AreEqual("1,", dataSet.Tables[0].Rows[2][2]); } } [Test] public void GitIssue271InvalidDimension() { using (var excelReader = ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("Test_git_issue_271_InvalidDimension.xlsx"))) { var dataSet = excelReader.AsDataSet(); Assert.AreEqual(3, dataSet.Tables[0].Columns.Count); Assert.AreEqual(9, dataSet.Tables[0].Rows.Count); } } [Test] public void GitIssue289CompoundDocumentEncryptedWithDefaultPassword() { using (var reader = ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("Test_git_issue289.xlsx"))) { reader.Read(); Assert.AreEqual("aaaaaaa", reader.GetValue(0)); } } [Test] public void GitIssue301IgnoreCase() { using (var reader = ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("Test_git_issue_301_IgnoreCase.xlsx"))) { DataTable result = reader.AsDataSet().Tables[0]; Assert.AreEqual(10, result.Rows.Count); Assert.AreEqual(10, result.Columns.Count); Assert.AreEqual("10x10", result.Rows[1][0]); Assert.AreEqual("10x27", result.Rows[9][9]); } } [Test] public void GitIssue319InlineRichText() { using (var reader = ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("Test_git_issue319.xlsx"))) { var result = reader.AsDataSet().Tables[0]; Assert.AreEqual("Text1", result.Rows[0][0]); } } [Test] public void GitIssue324MultipleRowElementsPerRow() { using (var reader = ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("Test_git_issue_324.xlsx"))) { var result = reader.AsDataSet().Tables[0]; Assert.AreEqual(20, result.Rows.Count); Assert.AreEqual(13, result.Columns.Count); Assert.That(result.Rows[10].ItemArray, Is.EqualTo(new object[] { DBNull.Value, DBNull.Value, "Other", 191036.15, 194489.45, 66106.32, 37167.88, 102589.54, 57467.94, 130721.93, 150752.67, 76300.69, 67024.6 })); } } [Test] public void GitIssue354() { using (var reader = ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("test_git_issue_354.xlsx"))) { var result = reader.AsDataSet().Tables[0]; Assert.AreEqual(1, result.Rows.Count); Assert.AreEqual("cell data", result.Rows[0][0]); } } [Test] public void GitIssue385Backslash() { using (var reader = ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("Test_git_issue_385_backslash.xlsx"))) { var result = reader.AsDataSet().Tables[0]; Assert.AreEqual(10, result.Rows.Count); Assert.AreEqual(10, result.Columns.Count); Assert.AreEqual("10x10", result.Rows[1][0]); Assert.AreEqual("10x27", result.Rows[9][9]); } } /// <summary> /// This test is to ensure that we get the same results from an xls saved in excel vs open office /// </summary> [Test] public void TestOpenOfficeSavedInExcel() { using (IExcelDataReader excelReader = OpenReader("Test_Excel_OpenOffice")) { AssertUtilities.DoOpenOfficeTest(excelReader); } } [Test] public void GitIssue454HandleDuplicateNumberFormats() { using var reader = ExcelReaderFactory.CreateOpenXmlReader(Configuration.GetTestWorkbook("Test_git_issue454.xlsx")); reader.Read(); } [Test] public void GitIssue486TransformValue() { using (var reader = OpenReader("Test_git_issue_486")) { var dataSet = reader.AsDataSet(new ExcelDataSetConfiguration() { ConfigureDataTable = _ => new ExcelDataTableConfiguration() { UseHeaderRow = true, TransformValue = (transformReader, n, value) => { var error = transformReader.GetCellError(n); if (error != null) { return error; } return value; } } }); Assert.AreEqual("REF", dataSet.Tables[0].Rows[0][0].ToString()); Assert.AreEqual("REF", dataSet.Tables[0].Rows[0][1].ToString()); Assert.AreEqual("NAME", dataSet.Tables[0].Rows[1][0].ToString()); Assert.AreEqual("NAME", dataSet.Tables[0].Rows[1][1].ToString()); } } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace DotSpatial.Symbology.Forms { /// <summary> /// TabColorControl. /// </summary> [DefaultEvent("ColorChanged")] [ToolboxItem(false)] public partial class TabColorControl : UserControl { #region Fields private Color _endColor; private int _endHue; private float _endLight; private float _endSat; private bool _hsl; private bool _ignoreUpdates; private Color _startColor; private int _startHue; private float _startLight; private float _startSat; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="TabColorControl"/> class. /// </summary> public TabColorControl() { InitializeComponent(); Configure(); } #endregion #region Events /// <summary> /// Occurs when the color is changed. /// </summary> public event EventHandler<ColorRangeEventArgs> ColorChanged; #endregion #region Properties /// <summary> /// Gets or sets the end color, which controls the RGB end color and the right HSL ranges. /// </summary> [Category("Colors")] [Description("Gets or sets the end color, which controls the RGB end color and the right HSL ranges")] public Color EndColor { get { return _endColor; } set { _endColor = value; SetEndHsl(); cbEndColor.Color = value; } } /// <summary> /// Gets or sets the integer hue shift marking how much the hue slider should be shifted. /// </summary> [Category("Behavior")] [Description("Gets or sets the integer hue shift marking how much the hue slider should be shifted")] public int HueShift { get; set; } /// <summary> /// Gets or sets the start color, which controls the RGB start colors and the HSL left ranges. /// </summary> [Category("Colors")] [Description("Gets or sets the start color, which controls the RGB colors and the HSL range")] public Color StartColor { get { return _startColor; } set { _startColor = value; SetStartHsl(); cbStartColor.Color = value; } } /// <summary> /// Gets or sets a value indicating whether or not the hue range is to be used. /// </summary> [Category("Behavior")] [Description("Gets or sets a boolean indicating whether or not the hue range is to be used.")] public bool UseRangeChecked { get { return chkUseColorRange.Checked; } set { chkUseColorRange.Checked = value; } } #endregion #region Methods /// <summary> /// Initializes a new instance of this control using the specified values. /// </summary> /// <param name="args">The ColorRangeEventArgs that stores the initial values.</param> public void Initialize(ColorRangeEventArgs args) { _endColor = args.EndColor; _hsl = args.Hsl; HueShift = args.HueShift; _startColor = args.StartColor; chkUseColorRange.Checked = args.UseColorRange; SetStartHsl(); SetEndHsl(); UpdateControls(); } /// <summary> /// Fires the ColorChanged event. /// </summary> protected virtual void OnColorChanged() { ColorChanged?.Invoke(this, new ColorRangeEventArgs(_startColor, _endColor, HueShift, _hsl, chkUseColorRange.Checked)); } private void BtnHueShiftMouseDown(object sender, MouseEventArgs e) { tmrHueShift.Start(); } private void BtnHueShiftMouseUp(object sender, MouseEventArgs e) { tmrHueShift.Stop(); } private void BtnReverseHueClick(object sender, EventArgs e) { sldHue.Inverted = !sldHue.Inverted; SetHsl(); } private void BtnReverseLightClick(object sender, EventArgs e) { sldLightness.Inverted = !sldLightness.Inverted; SetHsl(); } private void BtnReverseSatClick(object sender, EventArgs e) { sldSaturation.Inverted = !sldSaturation.Inverted; SetHsl(); } private void CbEndColorColorChanged(object sender, EventArgs e) { SetRgb(); } private void CbStartColorColorChanged(object sender, EventArgs e) { SetRgb(); } private void ChkUseColorRangeCheckedChanged(object sender, EventArgs e) { OnColorChanged(); } private void Configure() { tmrHueShift = new Timer { Interval = 100 }; tmrHueShift.Tick += TmrHueShiftTick; btnHueShift.MouseDown += BtnHueShiftMouseDown; btnHueShift.MouseUp += BtnHueShiftMouseUp; } private void SetEndHsl() { _endHue = (int)_endColor.GetHue(); _endSat = _endColor.GetSaturation(); _endLight = _endColor.GetBrightness(); } // Reads the current control settings to the cached values. private void SetHsl() { if (_ignoreUpdates) return; HueShift = sldHue.HueShift; int h = (int)(sldHue.LeftValue + (HueShift % 360)); float s = sldSaturation.LeftValue; float l = sldLightness.LeftValue; float a = _startColor.A / 255f; _startColor = SymbologyGlobal.ColorFromHsl(h, s, l).ToTransparent(a); _startHue = h; _startSat = s; _startLight = l; h = (int)(sldHue.RightValue + HueShift) % 360; s = sldSaturation.RightValue; l = sldLightness.RightValue; a = _endColor.A / 255f; _endHue = h; _endSat = s; _endLight = l; _endColor = SymbologyGlobal.ColorFromHsl(h, s, l).ToTransparent(a); _hsl = true; chkUseColorRange.Checked = true; _ignoreUpdates = true; cbStartColor.Color = _startColor; cbEndColor.Color = _endColor; _ignoreUpdates = false; UpdateControls(); } // Updates private void SetRgb() { if (_ignoreUpdates) return; _startColor = cbStartColor.Color; _endColor = cbEndColor.Color; SetStartHsl(); SetEndHsl(); chkUseColorRange.Checked = true; _hsl = false; UpdateControls(); } private void SetStartHsl() { _startHue = (int)_startColor.GetHue(); _startSat = _startColor.GetSaturation(); _startLight = _startColor.GetBrightness(); } private void SldHuePositionChanging(object sender, EventArgs e) { SetHsl(); } private void SldLightnessPositionChanging(object sender, EventArgs e) { SetHsl(); } private void SldSaturationPositionChanging(object sender, EventArgs e) { SetHsl(); } private void TmrHueShiftTick(object sender, EventArgs e) { int shift = sldHue.Inverted ? 36 : -36; _ignoreUpdates = true; sldHue.HueShift = (sldHue.HueShift + shift) % 360; // sldHue.LeftValue = sldHue.LeftValue; // sldHue.RightValue = sldHue.RightValue; SetHsl(); } private void UpdateControls() { // Prevent infinite loops if (_ignoreUpdates) return; _ignoreUpdates = true; if (_hsl) { // Don't use the colors directly, here mainly because saturation // loses information when going back and forth from a color. if (_startHue != _endHue) sldHue.Inverted = _startHue > _endHue; sldHue.LeftValue = _startHue; sldHue.RightValue = _endHue; if (_startSat != _endSat) sldSaturation.Inverted = _startSat > _endSat; sldSaturation.LeftValue = _startSat; sldSaturation.RightValue = _endSat; if (_startLight != _endLight) sldLightness.Inverted = _startLight > _endLight; sldLightness.LeftValue = _startLight; sldLightness.RightValue = _endLight; } else { sldHue.SetRange(_startColor, _endColor); sldSaturation.SetSaturation(_startColor, _endColor); sldLightness.SetLightness(_startColor, _endColor); sldHue.HueShift = HueShift; cbStartColor.Color = _startColor; cbEndColor.Color = _endColor; } tabColorRange.SelectedTab = _hsl ? tabHSL : tabRGB; _ignoreUpdates = false; OnColorChanged(); } #endregion } }
using System; using System.IO; using System.Runtime.InteropServices; using System.Security; namespace SFML { namespace Audio { //////////////////////////////////////////////////////////// /// <summary> /// SoundBuffer is the low-level class for loading and manipulating /// sound buffers. A sound buffer holds audio data (samples) /// which can then be played by a Sound or saved to a file. /// </summary> //////////////////////////////////////////////////////////// public class SoundBuffer : ObjectBase { //////////////////////////////////////////////////////////// /// <summary> /// Construct the sound buffer from a file /// </summary> /// <param name="filename">Path of the sound file to load</param> /// <exception cref="LoadingFailedException" /> //////////////////////////////////////////////////////////// public SoundBuffer(string filename) : base(sfSoundBuffer_CreateFromFile(filename)) { if (This == IntPtr.Zero) throw new LoadingFailedException("sound buffer", filename); } //////////////////////////////////////////////////////////// /// <summary> /// Construct the sound buffer from a file in a stream /// </summary> /// <param name="stream">Stream containing the file contents</param> //////////////////////////////////////////////////////////// public SoundBuffer(Stream stream) : base(IntPtr.Zero) { stream.Position = 0; byte[] StreamData = new byte[stream.Length]; uint Read = (uint)stream.Read(StreamData, 0, StreamData.Length); unsafe { fixed (byte* dataPtr = StreamData) { SetThis(sfSoundBuffer_CreateFromMemory((char*)dataPtr, Read)); } } if (This == IntPtr.Zero) throw new LoadingFailedException("sound buffer"); } //////////////////////////////////////////////////////////// /// <summary> /// Construct the sound buffer from an array of samples /// </summary> /// <param name="samples">Array of samples</param> /// <param name="channelsCount">Channels count</param> /// <param name="sampleRate">Sample rate</param> /// <exception cref="LoadingFailedException" /> //////////////////////////////////////////////////////////// public SoundBuffer(short[] samples, uint channelsCount, uint sampleRate) : base(IntPtr.Zero) { unsafe { fixed (short* SamplesPtr = samples) { SetThis(sfSoundBuffer_CreateFromSamples(SamplesPtr, (uint)samples.Length, channelsCount, sampleRate)); } } if (This == IntPtr.Zero) throw new LoadingFailedException("sound buffer"); } //////////////////////////////////////////////////////////// /// <summary> /// Construct the sound buffer from another sound buffer /// </summary> /// <param name="copy">Sound buffer to copy</param> //////////////////////////////////////////////////////////// public SoundBuffer(SoundBuffer copy) : base(sfSoundBuffer_Copy(copy.This)) { } //////////////////////////////////////////////////////////// /// <summary> /// Save the sound buffer to an audio file /// </summary> /// <param name="filename">Path of the sound file to write</param> /// <returns>True if saving has been successful</returns> //////////////////////////////////////////////////////////// public bool SaveToFile(string filename) { return sfSoundBuffer_SaveToFile(This, filename); } //////////////////////////////////////////////////////////// /// <summary> /// Samples rate, in samples per second /// </summary> //////////////////////////////////////////////////////////// public uint SampleRate { get { return sfSoundBuffer_GetSampleRate(This); } } //////////////////////////////////////////////////////////// /// <summary> /// Number of channels (1 = mono, 2 = stereo) /// </summary> //////////////////////////////////////////////////////////// public uint ChannelsCount { get { return sfSoundBuffer_GetChannelsCount(This); } } //////////////////////////////////////////////////////////// /// <summary> /// Total duration of the buffer, in seconds /// </summary> //////////////////////////////////////////////////////////// public float Duration { get { return sfSoundBuffer_GetDuration(This); } } //////////////////////////////////////////////////////////// /// <summary> /// Array of samples contained in the buffer /// </summary> //////////////////////////////////////////////////////////// public short[] Samples { get { short[] SamplesArray = new short[sfSoundBuffer_GetSamplesCount(This)]; Marshal.Copy(sfSoundBuffer_GetSamples(This), SamplesArray, 0, SamplesArray.Length); return SamplesArray; } } //////////////////////////////////////////////////////////// /// <summary> /// Provide a string describing the object /// </summary> /// <returns>String description of the object</returns> //////////////////////////////////////////////////////////// public override string ToString() { return "[SoundBuffer]" + " SampleRate(" + SampleRate + ")" + " ChannelsCount(" + ChannelsCount + ")" + " Duration(" + Duration + ")"; } //////////////////////////////////////////////////////////// /// <summary> /// Handle the destruction of the object /// </summary> /// <param name="disposing">Is the GC disposing the object, or is it an explicit call ?</param> //////////////////////////////////////////////////////////// protected override void Destroy(bool disposing) { sfSoundBuffer_Destroy(This); } #region Imports [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfSoundBuffer_CreateFromFile(string Filename); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] unsafe static extern IntPtr sfSoundBuffer_CreateFromMemory(char* Data, uint SizeInBytes); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] unsafe static extern IntPtr sfSoundBuffer_CreateFromSamples(short* Samples, uint SamplesCount, uint ChannelsCount, uint SampleRate); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfSoundBuffer_Copy(IntPtr SoundBuffer); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfSoundBuffer_Destroy(IntPtr SoundBuffer); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfSoundBuffer_SaveToFile(IntPtr SoundBuffer, string Filename); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfSoundBuffer_GetSamples(IntPtr SoundBuffer); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern uint sfSoundBuffer_GetSamplesCount(IntPtr SoundBuffer); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern uint sfSoundBuffer_GetSampleRate(IntPtr SoundBuffer); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern uint sfSoundBuffer_GetChannelsCount(IntPtr SoundBuffer); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern float sfSoundBuffer_GetDuration(IntPtr SoundBuffer); #endregion } } }
/* * 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 System.Linq; using System.Diagnostics; using System.Collections.Generic; using System.Threading; using System.Security.Cryptography.X509Certificates; using Thrift.Collections; using Thrift.Protocol; using Thrift.Transport; using Thrift.Test; using System.Security.Authentication; namespace Test { public class TestClient { public class TestParams { public int numIterations = 1; public string host = "localhost"; public int port = 9090; public string url; public string pipe; public bool buffered; public bool framed; public string protocol; public bool encrypted = false; public bool multiplexed = false; protected bool _isFirstTransport = true; public TTransport CreateTransport() { if (url == null) { // endpoint transport TTransport trans = null; if (pipe != null) trans = new TNamedPipeClientTransport(pipe); else { if (encrypted) { string certPath = "../keys/client.p12"; X509Certificate cert = new X509Certificate2(certPath, "thrift"); trans = new TTLSSocket(host, port, 0, cert, (o, c, chain, errors) => true, null, SslProtocols.Tls); } else { trans = new TSocket(host, port); } } // layered transport if (buffered) trans = new TBufferedTransport(trans); if (framed) trans = new TFramedTransport(trans); if (_isFirstTransport) { //ensure proper open/close of transport trans.Open(); trans.Close(); _isFirstTransport = false; } return trans; } else { return new THttpClient(new Uri(url)); } } public TProtocol CreateProtocol(TTransport transport) { if (protocol == "compact") return new TCompactProtocol(transport); else if (protocol == "json") return new TJSONProtocol(transport); else return new TBinaryProtocol(transport); } }; private const int ErrorBaseTypes = 1; private const int ErrorStructs = 2; private const int ErrorContainers = 4; private const int ErrorExceptions = 8; private const int ErrorProtocol = 16; private const int ErrorUnknown = 64; private class ClientTest { private readonly TestParams param; private readonly TTransport transport; private readonly SecondService.Client second; private readonly ThriftTest.Client client; private readonly int numIterations; private bool done; public int ReturnCode { get; set; } public ClientTest(TestParams paramin) { param = paramin; transport = param.CreateTransport(); TProtocol protocol = param.CreateProtocol(transport); if (param.multiplexed) { second = new SecondService.Client(new TMultiplexedProtocol(protocol, "SecondService")); } client = new ThriftTest.Client(protocol); numIterations = param.numIterations; } public void Execute() { if (done) { Console.WriteLine("Execute called more than once"); throw new InvalidOperationException(); } for (int i = 0; i < numIterations; i++) { try { if (!transport.IsOpen) transport.Open(); } catch (TTransportException ex) { Console.WriteLine("*** FAILED ***"); Console.WriteLine("Connect failed: " + ex.Message); ReturnCode |= ErrorUnknown; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); continue; } try { ReturnCode |= ExecuteClientTest(client, second, param); } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); ReturnCode |= ErrorUnknown; } } try { transport.Close(); } catch(Exception ex) { Console.WriteLine("Error while closing transport"); Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } done = true; } } public static int Execute(string[] args) { try { TestParams param = new TestParams(); int numThreads = 1; try { for (int i = 0; i < args.Length; i++) { if (args[i] == "-u") { param.url = args[++i]; } else if (args[i] == "-n") { param.numIterations = Convert.ToInt32(args[++i]); } else if (args[i] == "-pipe") // -pipe <name> { param.pipe = args[++i]; Console.WriteLine("Using named pipes transport"); } else if (args[i].Contains("--host=")) { param.host = args[i].Substring(args[i].IndexOf("=") + 1); } else if (args[i].Contains("--port=")) { param.port = int.Parse(args[i].Substring(args[i].IndexOf("=")+1)); } else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered") { param.buffered = true; Console.WriteLine("Using buffered sockets"); } else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed") { param.framed = true; Console.WriteLine("Using framed transport"); } else if (args[i] == "-t") { numThreads = Convert.ToInt32(args[++i]); } else if (args[i] == "--compact" || args[i] == "--protocol=compact" || args[i] == "--protocol=multic") { param.protocol = "compact"; Console.WriteLine("Using compact protocol"); } else if (args[i] == "--json" || args[i] == "--protocol=json" || args[i] == "--protocol=multij") { param.protocol = "json"; Console.WriteLine("Using JSON protocol"); } else if (args[i] == "--ssl") { param.encrypted = true; Console.WriteLine("Using encrypted transport"); } if (args[i].StartsWith("--protocol=multi")) { param.multiplexed = true; } } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); Console.WriteLine("Error while parsing arguments"); Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); return ErrorUnknown; } var tests = Enumerable.Range(0, numThreads).Select(_ => new ClientTest(param)).ToArray(); //issue tests on separate threads simultaneously var threads = tests.Select(test => new Thread(test.Execute)).ToArray(); DateTime start = DateTime.Now; foreach (var t in threads) t.Start(); foreach (var t in threads) t.Join(); Console.WriteLine("Total time: " + (DateTime.Now - start)); Console.WriteLine(); return tests.Select(t => t.ReturnCode).Aggregate((r1, r2) => r1 | r2); } catch (Exception outerEx) { Console.WriteLine("*** FAILED ***"); Console.WriteLine("Unexpected error"); Console.WriteLine(outerEx.Message + " ST: " + outerEx.StackTrace); return ErrorUnknown; } } public static string BytesToHex(byte[] data) { return BitConverter.ToString(data).Replace("-", string.Empty); } public static byte[] PrepareTestData(bool randomDist, bool huge) { // huge = true tests for THRIFT-4372 byte[] retval = new byte[huge ? 0x12345 : 0x100]; int initLen = retval.Length; // linear distribution, unless random is requested if (!randomDist) { for (var i = 0; i < initLen; ++i) { retval[i] = (byte)i; } return retval; } // random distribution for (var i = 0; i < initLen; ++i) { retval[i] = (byte)0; } var rnd = new Random(); for (var i = 1; i < initLen; ++i) { while( true) { int nextPos = rnd.Next() % initLen; if (retval[nextPos] == 0) { retval[nextPos] = (byte)i; break; } } } return retval; } public static int ExecuteClientTest(ThriftTest.Client client, SecondService.Client second, TestParams param) { int returnCode = 0; Console.Write("testVoid()"); client.testVoid(); Console.WriteLine(" = void"); Console.Write("testString(\"Test\")"); string s = client.testString("Test"); Console.WriteLine(" = \"" + s + "\""); if ("Test" != s) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } if (param.multiplexed) { Console.WriteLine("secondTestString(\"Test2\")"); s = second.secondtestString("Test2"); Console.WriteLine(" = \"" + s + "\""); if ("testString(\"Test2\")" != s) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorProtocol; } } Console.Write("testBool(true)"); bool t = client.testBool((bool)true); Console.WriteLine(" = " + t); if (!t) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testBool(false)"); bool f = client.testBool((bool)false); Console.WriteLine(" = " + f); if (f) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testByte(1)"); sbyte i8 = client.testByte((sbyte)1); Console.WriteLine(" = " + i8); if (1 != i8) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testI32(-1)"); int i32 = client.testI32(-1); Console.WriteLine(" = " + i32); if (-1 != i32) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testI64(-34359738368)"); long i64 = client.testI64(-34359738368); Console.WriteLine(" = " + i64); if (-34359738368 != i64) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } // TODO: Validate received message Console.Write("testDouble(5.325098235)"); double dub = client.testDouble(5.325098235); Console.WriteLine(" = " + dub); if (5.325098235 != dub) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testDouble(-0.000341012439638598279)"); dub = client.testDouble(-0.000341012439638598279); Console.WriteLine(" = " + dub); if (-0.000341012439638598279 != dub) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } for (i32 = 0; i32 < 2; ++i32) { var huge = (i32 > 0); byte[] binOut = PrepareTestData(false,huge); Console.Write("testBinary(" + BytesToHex(binOut) + ")"); try { byte[] binIn = client.testBinary(binOut); Console.WriteLine(" = " + BytesToHex(binIn)); if (binIn.Length != binOut.Length) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } for (int ofs = 0; ofs < Math.Min(binIn.Length, binOut.Length); ++ofs) if (binIn[ofs] != binOut[ofs]) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } } catch (Thrift.TApplicationException ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } } // binary equals? only with hashcode option enabled ... Console.WriteLine("Test CrazyNesting"); if( typeof(CrazyNesting).GetMethod("Equals").DeclaringType == typeof(CrazyNesting)) { CrazyNesting one = new CrazyNesting(); CrazyNesting two = new CrazyNesting(); one.String_field = "crazy"; two.String_field = "crazy"; one.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF }; two.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF }; if (!one.Equals(two)) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorContainers; throw new Exception("CrazyNesting.Equals failed"); } } // TODO: Validate received message Console.Write("testStruct({\"Zero\", 1, -3, -5})"); Xtruct o = new Xtruct(); o.String_thing = "Zero"; o.Byte_thing = (sbyte)1; o.I32_thing = -3; o.I64_thing = -5; Xtruct i = client.testStruct(o); Console.WriteLine(" = {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}"); // TODO: Validate received message Console.Write("testNest({1, {\"Zero\", 1, -3, -5}, 5})"); Xtruct2 o2 = new Xtruct2(); o2.Byte_thing = (sbyte)1; o2.Struct_thing = o; o2.I32_thing = 5; Xtruct2 i2 = client.testNest(o2); i = i2.Struct_thing; Console.WriteLine(" = {" + i2.Byte_thing + ", {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}, " + i2.I32_thing + "}"); Dictionary<int, int> mapout = new Dictionary<int, int>(); for (int j = 0; j < 5; j++) { mapout[j] = j - 10; } Console.Write("testMap({"); bool first = true; foreach (int key in mapout.Keys) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(key + " => " + mapout[key]); } Console.Write("})"); Dictionary<int, int> mapin = client.testMap(mapout); Console.Write(" = {"); first = true; foreach (int key in mapin.Keys) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(key + " => " + mapin[key]); } Console.WriteLine("}"); // TODO: Validate received message List<int> listout = new List<int>(); for (int j = -2; j < 3; j++) { listout.Add(j); } Console.Write("testList({"); first = true; foreach (int j in listout) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.Write("})"); List<int> listin = client.testList(listout); Console.Write(" = {"); first = true; foreach (int j in listin) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.WriteLine("}"); //set // TODO: Validate received message THashSet<int> setout = new THashSet<int>(); for (int j = -2; j < 3; j++) { setout.Add(j); } Console.Write("testSet({"); first = true; foreach (int j in setout) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.Write("})"); THashSet<int> setin = client.testSet(setout); Console.Write(" = {"); first = true; foreach (int j in setin) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.WriteLine("}"); Console.Write("testEnum(ONE)"); Numberz ret = client.testEnum(Numberz.ONE); Console.WriteLine(" = " + ret); if (Numberz.ONE != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testEnum(TWO)"); ret = client.testEnum(Numberz.TWO); Console.WriteLine(" = " + ret); if (Numberz.TWO != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testEnum(THREE)"); ret = client.testEnum(Numberz.THREE); Console.WriteLine(" = " + ret); if (Numberz.THREE != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testEnum(FIVE)"); ret = client.testEnum(Numberz.FIVE); Console.WriteLine(" = " + ret); if (Numberz.FIVE != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testEnum(EIGHT)"); ret = client.testEnum(Numberz.EIGHT); Console.WriteLine(" = " + ret); if (Numberz.EIGHT != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testTypedef(309858235082523)"); long uid = client.testTypedef(309858235082523L); Console.WriteLine(" = " + uid); if (309858235082523L != uid) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } // TODO: Validate received message Console.Write("testMapMap(1)"); Dictionary<int, Dictionary<int, int>> mm = client.testMapMap(1); Console.Write(" = {"); foreach (int key in mm.Keys) { Console.Write(key + " => {"); Dictionary<int, int> m2 = mm[key]; foreach (int k2 in m2.Keys) { Console.Write(k2 + " => " + m2[k2] + ", "); } Console.Write("}, "); } Console.WriteLine("}"); // TODO: Validate received message Insanity insane = new Insanity(); insane.UserMap = new Dictionary<Numberz, long>(); insane.UserMap[Numberz.FIVE] = 5000L; Xtruct truck = new Xtruct(); truck.String_thing = "Truck"; truck.Byte_thing = (sbyte)8; truck.I32_thing = 8; truck.I64_thing = 8; insane.Xtructs = new List<Xtruct>(); insane.Xtructs.Add(truck); Console.Write("testInsanity()"); Dictionary<long, Dictionary<Numberz, Insanity>> whoa = client.testInsanity(insane); Console.Write(" = {"); foreach (long key in whoa.Keys) { Dictionary<Numberz, Insanity> val = whoa[key]; Console.Write(key + " => {"); foreach (Numberz k2 in val.Keys) { Insanity v2 = val[k2]; Console.Write(k2 + " => {"); Dictionary<Numberz, long> userMap = v2.UserMap; Console.Write("{"); if (userMap != null) { foreach (Numberz k3 in userMap.Keys) { Console.Write(k3 + " => " + userMap[k3] + ", "); } } else { Console.Write("null"); } Console.Write("}, "); List<Xtruct> xtructs = v2.Xtructs; Console.Write("{"); if (xtructs != null) { foreach (Xtruct x in xtructs) { Console.Write("{\"" + x.String_thing + "\", " + x.Byte_thing + ", " + x.I32_thing + ", " + x.I32_thing + "}, "); } } else { Console.Write("null"); } Console.Write("}"); Console.Write("}, "); } Console.Write("}, "); } Console.WriteLine("}"); sbyte arg0 = 1; int arg1 = 2; long arg2 = long.MaxValue; Dictionary<short, string> multiDict = new Dictionary<short, string>(); multiDict[1] = "one"; Numberz arg4 = Numberz.FIVE; long arg5 = 5000000; Console.Write("Test Multi(" + arg0 + "," + arg1 + "," + arg2 + "," + multiDict + "," + arg4 + "," + arg5 + ")"); Xtruct multiResponse = client.testMulti(arg0, arg1, arg2, multiDict, arg4, arg5); Console.Write(" = Xtruct(byte_thing:" + multiResponse.Byte_thing + ",String_thing:" + multiResponse.String_thing + ",i32_thing:" + multiResponse.I32_thing + ",i64_thing:" + multiResponse.I64_thing + ")\n"); try { Console.WriteLine("testException(\"Xception\")"); client.testException("Xception"); Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } catch (Xception ex) { if (ex.ErrorCode != 1001 || ex.Message != "Xception") { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } try { Console.WriteLine("testException(\"TException\")"); client.testException("TException"); Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } catch (Thrift.TException) { // OK } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } try { Console.WriteLine("testException(\"ok\")"); client.testException("ok"); // OK } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } try { Console.WriteLine("testMultiException(\"Xception\", ...)"); client.testMultiException("Xception", "ignore"); Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } catch (Xception ex) { if (ex.ErrorCode != 1001 || ex.Message != "This is an Xception") { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } try { Console.WriteLine("testMultiException(\"Xception2\", ...)"); client.testMultiException("Xception2", "ignore"); Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } catch (Xception2 ex) { if (ex.ErrorCode != 2002 || ex.Struct_thing.String_thing != "This is an Xception2") { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } try { Console.WriteLine("testMultiException(\"success\", \"OK\")"); if ("OK" != client.testMultiException("success", "OK").String_thing) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } Stopwatch sw = new Stopwatch(); sw.Start(); Console.WriteLine("Test Oneway(1)"); client.testOneway(1); sw.Stop(); if (sw.ElapsedMilliseconds > 1000) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("Test Calltime()"); var times = 50; sw.Reset(); sw.Start(); for (int k = 0; k < times; ++k) client.testVoid(); sw.Stop(); Console.WriteLine(" = {0} ms a testVoid() call", sw.ElapsedMilliseconds / times); return returnCode; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.IO; using System.Reflection; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Data.MSSQL { /// <summary> /// A MSSQL Interface for the Region Server. /// </summary> public class MSSQLSimulationData : ISimulationDataStore { private const string _migrationStore = "RegionStore"; // private static FileSystemDataStore Instance = new FileSystemDataStore(); private static readonly ILog _Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// The database manager /// </summary> private MSSQLManager _Database; private string m_connectionString; public MSSQLSimulationData() { } public MSSQLSimulationData(string connectionString) { Initialise(connectionString); } /// <summary> /// Initialises the region datastore /// </summary> /// <param name="connectionString">The connection string.</param> public void Initialise(string connectionString) { m_connectionString = connectionString; _Database = new MSSQLManager(connectionString); //Migration settings _Database.CheckMigration(_migrationStore); } /// <summary> /// Dispose the database /// </summary> public void Dispose() { } #region SceneObjectGroup region for loading and Store of the scene. /// <summary> /// Loads the objects present in the region. /// </summary> /// <param name="regionUUID">The region UUID.</param> /// <returns></returns> public List<SceneObjectGroup> LoadObjects(UUID regionUUID) { UUID lastGroupID = UUID.Zero; Dictionary<UUID, SceneObjectPart> prims = new Dictionary<UUID, SceneObjectPart>(); Dictionary<UUID, SceneObjectGroup> objects = new Dictionary<UUID, SceneObjectGroup>(); SceneObjectGroup grp = null; string sql = "SELECT *, " + "sort = CASE WHEN prims.UUID = prims.SceneGroupID THEN 0 ELSE 1 END " + "FROM prims " + "LEFT JOIN primshapes ON prims.UUID = primshapes.UUID " + "WHERE RegionUUID = @RegionUUID " + "ORDER BY SceneGroupID asc, sort asc, LinkNumber asc"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand command = new SqlCommand(sql, conn)) { command.Parameters.Add(_Database.CreateParameter("@regionUUID", regionUUID)); conn.Open(); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { SceneObjectPart sceneObjectPart = BuildPrim(reader); if (reader["Shape"] is DBNull) sceneObjectPart.Shape = PrimitiveBaseShape.Default; else sceneObjectPart.Shape = BuildShape(reader); prims[sceneObjectPart.UUID] = sceneObjectPart; UUID groupID = new UUID((Guid)reader["SceneGroupID"]); if (groupID != lastGroupID) // New SOG { if (grp != null) objects[grp.UUID] = grp; lastGroupID = groupID; // There sometimes exist OpenSim bugs that 'orphan groups' so that none of the prims are // recorded as the root prim (for which the UUID must equal the persisted group UUID). In // this case, force the UUID to be the same as the group UUID so that at least these can be // deleted (we need to change the UUID so that any other prims in the linkset can also be // deleted). if (sceneObjectPart.UUID != groupID && groupID != UUID.Zero) { _Log.WarnFormat( "[REGION DB]: Found root prim {0} {1} at {2} where group was actually {3}. Forcing UUID to group UUID", sceneObjectPart.Name, sceneObjectPart.UUID, sceneObjectPart.GroupPosition, groupID); sceneObjectPart.UUID = groupID; } grp = new SceneObjectGroup(sceneObjectPart); } else { // Black magic to preserve link numbers // Why is this needed, fix this in AddPart method. int link = sceneObjectPart.LinkNum; grp.AddPart(sceneObjectPart); if (link != 0) sceneObjectPart.LinkNum = link; } } } } if (grp != null) objects[grp.UUID] = grp; // Instead of attempting to LoadItems on every prim, // most of which probably have no items... get a // list from DB of all prims which have items and // LoadItems only on those List<SceneObjectPart> primsWithInventory = new List<SceneObjectPart>(); string qry = "select distinct primID from primitems"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand command = new SqlCommand(qry, conn)) { conn.Open(); using (SqlDataReader itemReader = command.ExecuteReader()) { while (itemReader.Read()) { if (!(itemReader["primID"] is DBNull)) { UUID primID = new UUID(itemReader["primID"].ToString()); if (prims.ContainsKey(primID)) { primsWithInventory.Add(prims[primID]); } } } } } LoadItems(primsWithInventory); _Log.DebugFormat("[REGION DB]: Loaded {0} objects using {1} prims", objects.Count, prims.Count); return new List<SceneObjectGroup>(objects.Values); } /// <summary> /// Load in the prim's persisted inventory. /// </summary> /// <param name="allPrims">all prims with inventory on a region</param> private void LoadItems(List<SceneObjectPart> allPrimsWithInventory) { string sql = "SELECT * FROM primitems WHERE PrimID = @PrimID"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand command = new SqlCommand(sql, conn)) { conn.Open(); foreach (SceneObjectPart objectPart in allPrimsWithInventory) { command.Parameters.Clear(); command.Parameters.Add(_Database.CreateParameter("@PrimID", objectPart.UUID)); List<TaskInventoryItem> inventory = new List<TaskInventoryItem>(); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { TaskInventoryItem item = BuildItem(reader); item.ParentID = objectPart.UUID; // Values in database are // often wrong inventory.Add(item); } } objectPart.Inventory.RestoreInventoryItems(inventory); } } } /// <summary> /// Stores all object's details apart from inventory /// </summary> /// <param name="obj"></param> /// <param name="regionUUID"></param> public void StoreObject(SceneObjectGroup obj, UUID regionUUID) { _Log.DebugFormat("[MSSQL]: Adding/Changing SceneObjectGroup: {0} to region: {1}, object has {2} prims.", obj.UUID, regionUUID, obj.Parts.Length); using (SqlConnection conn = new SqlConnection(m_connectionString)) { conn.Open(); SqlTransaction transaction = conn.BeginTransaction(); try { foreach (SceneObjectPart sceneObjectPart in obj.Parts) { //Update prim using (SqlCommand sqlCommand = conn.CreateCommand()) { sqlCommand.Transaction = transaction; try { StoreSceneObjectPrim(sceneObjectPart, sqlCommand, obj.UUID, regionUUID); } catch (SqlException sqlEx) { _Log.ErrorFormat("[REGION DB]: Store SceneObjectPrim SQL error: {0} at line {1}", sqlEx.Message, sqlEx.LineNumber); throw; } } //Update primshapes using (SqlCommand sqlCommand = conn.CreateCommand()) { sqlCommand.Transaction = transaction; try { StoreSceneObjectPrimShapes(sceneObjectPart, sqlCommand, obj.UUID, regionUUID); } catch (SqlException sqlEx) { _Log.ErrorFormat("[REGION DB]: Store SceneObjectPrimShapes SQL error: {0} at line {1}", sqlEx.Message, sqlEx.LineNumber); throw; } } } transaction.Commit(); } catch (Exception ex) { _Log.ErrorFormat("[REGION DB]: Store SceneObjectGroup error: {0}, Rolling back...", ex.Message); try { transaction.Rollback(); } catch (Exception ex2) { //Show error _Log.InfoFormat("[REGION DB]: Rollback of SceneObjectGroup store transaction failed with error: {0}", ex2.Message); } } } } /// <summary> /// Stores the prim of the sceneobjectpart. /// </summary> /// <param name="sceneObjectPart">The sceneobjectpart or prim.</param> /// <param name="sqlCommand">The SQL command with the transaction.</param> /// <param name="sceneGroupID">The scenegroup UUID.</param> /// <param name="regionUUID">The region UUID.</param> private void StoreSceneObjectPrim(SceneObjectPart sceneObjectPart, SqlCommand sqlCommand, UUID sceneGroupID, UUID regionUUID) { //Big query to update or insert a new prim. //Note for SQL Server 2008 this could be simplified string queryPrims = @" IF EXISTS (SELECT UUID FROM prims WHERE UUID = @UUID) BEGIN UPDATE prims SET CreationDate = @CreationDate, Name = @Name, Text = @Text, Description = @Description, SitName = @SitName, TouchName = @TouchName, ObjectFlags = @ObjectFlags, OwnerMask = @OwnerMask, NextOwnerMask = @NextOwnerMask, GroupMask = @GroupMask, EveryoneMask = @EveryoneMask, BaseMask = @BaseMask, PositionX = @PositionX, PositionY = @PositionY, PositionZ = @PositionZ, GroupPositionX = @GroupPositionX, GroupPositionY = @GroupPositionY, GroupPositionZ = @GroupPositionZ, VelocityX = @VelocityX, VelocityY = @VelocityY, VelocityZ = @VelocityZ, AngularVelocityX = @AngularVelocityX, AngularVelocityY = @AngularVelocityY, AngularVelocityZ = @AngularVelocityZ, AccelerationX = @AccelerationX, AccelerationY = @AccelerationY, AccelerationZ = @AccelerationZ, RotationX = @RotationX, RotationY = @RotationY, RotationZ = @RotationZ, RotationW = @RotationW, SitTargetOffsetX = @SitTargetOffsetX, SitTargetOffsetY = @SitTargetOffsetY, SitTargetOffsetZ = @SitTargetOffsetZ, SitTargetOrientW = @SitTargetOrientW, SitTargetOrientX = @SitTargetOrientX, SitTargetOrientY = @SitTargetOrientY, SitTargetOrientZ = @SitTargetOrientZ, RegionUUID = @RegionUUID, CreatorID = @CreatorID, OwnerID = @OwnerID, GroupID = @GroupID, LastOwnerID = @LastOwnerID, SceneGroupID = @SceneGroupID, PayPrice = @PayPrice, PayButton1 = @PayButton1, PayButton2 = @PayButton2, PayButton3 = @PayButton3, PayButton4 = @PayButton4, LoopedSound = @LoopedSound, LoopedSoundGain = @LoopedSoundGain, TextureAnimation = @TextureAnimation, OmegaX = @OmegaX, OmegaY = @OmegaY, OmegaZ = @OmegaZ, CameraEyeOffsetX = @CameraEyeOffsetX, CameraEyeOffsetY = @CameraEyeOffsetY, CameraEyeOffsetZ = @CameraEyeOffsetZ, CameraAtOffsetX = @CameraAtOffsetX, CameraAtOffsetY = @CameraAtOffsetY, CameraAtOffsetZ = @CameraAtOffsetZ, ForceMouselook = @ForceMouselook, ScriptAccessPin = @ScriptAccessPin, AllowedDrop = @AllowedDrop, DieAtEdge = @DieAtEdge, SalePrice = @SalePrice, SaleType = @SaleType, ColorR = @ColorR, ColorG = @ColorG, ColorB = @ColorB, ColorA = @ColorA, ParticleSystem = @ParticleSystem, ClickAction = @ClickAction, Material = @Material, CollisionSound = @CollisionSound, CollisionSoundVolume = @CollisionSoundVolume, PassTouches = @PassTouches, LinkNumber = @LinkNumber, MediaURL = @MediaURL WHERE UUID = @UUID END ELSE BEGIN INSERT INTO prims ( UUID, CreationDate, Name, Text, Description, SitName, TouchName, ObjectFlags, OwnerMask, NextOwnerMask, GroupMask, EveryoneMask, BaseMask, PositionX, PositionY, PositionZ, GroupPositionX, GroupPositionY, GroupPositionZ, VelocityX, VelocityY, VelocityZ, AngularVelocityX, AngularVelocityY, AngularVelocityZ, AccelerationX, AccelerationY, AccelerationZ, RotationX, RotationY, RotationZ, RotationW, SitTargetOffsetX, SitTargetOffsetY, SitTargetOffsetZ, SitTargetOrientW, SitTargetOrientX, SitTargetOrientY, SitTargetOrientZ, RegionUUID, CreatorID, OwnerID, GroupID, LastOwnerID, SceneGroupID, PayPrice, PayButton1, PayButton2, PayButton3, PayButton4, LoopedSound, LoopedSoundGain, TextureAnimation, OmegaX, OmegaY, OmegaZ, CameraEyeOffsetX, CameraEyeOffsetY, CameraEyeOffsetZ, CameraAtOffsetX, CameraAtOffsetY, CameraAtOffsetZ, ForceMouselook, ScriptAccessPin, AllowedDrop, DieAtEdge, SalePrice, SaleType, ColorR, ColorG, ColorB, ColorA, ParticleSystem, ClickAction, Material, CollisionSound, CollisionSoundVolume, PassTouches, LinkNumber, MediaURL ) VALUES ( @UUID, @CreationDate, @Name, @Text, @Description, @SitName, @TouchName, @ObjectFlags, @OwnerMask, @NextOwnerMask, @GroupMask, @EveryoneMask, @BaseMask, @PositionX, @PositionY, @PositionZ, @GroupPositionX, @GroupPositionY, @GroupPositionZ, @VelocityX, @VelocityY, @VelocityZ, @AngularVelocityX, @AngularVelocityY, @AngularVelocityZ, @AccelerationX, @AccelerationY, @AccelerationZ, @RotationX, @RotationY, @RotationZ, @RotationW, @SitTargetOffsetX, @SitTargetOffsetY, @SitTargetOffsetZ, @SitTargetOrientW, @SitTargetOrientX, @SitTargetOrientY, @SitTargetOrientZ, @RegionUUID, @CreatorID, @OwnerID, @GroupID, @LastOwnerID, @SceneGroupID, @PayPrice, @PayButton1, @PayButton2, @PayButton3, @PayButton4, @LoopedSound, @LoopedSoundGain, @TextureAnimation, @OmegaX, @OmegaY, @OmegaZ, @CameraEyeOffsetX, @CameraEyeOffsetY, @CameraEyeOffsetZ, @CameraAtOffsetX, @CameraAtOffsetY, @CameraAtOffsetZ, @ForceMouselook, @ScriptAccessPin, @AllowedDrop, @DieAtEdge, @SalePrice, @SaleType, @ColorR, @ColorG, @ColorB, @ColorA, @ParticleSystem, @ClickAction, @Material, @CollisionSound, @CollisionSoundVolume, @PassTouches, @LinkNumber, @MediaURL ) END"; //Set commandtext. sqlCommand.CommandText = queryPrims; //Add parameters sqlCommand.Parameters.AddRange(CreatePrimParameters(sceneObjectPart, sceneGroupID, regionUUID)); //Execute the query. If it fails then error is trapped in calling function sqlCommand.ExecuteNonQuery(); } /// <summary> /// Stores the scene object prim shapes. /// </summary> /// <param name="sceneObjectPart">The sceneobjectpart containing prim shape.</param> /// <param name="sqlCommand">The SQL command with the transaction.</param> /// <param name="sceneGroupID">The scenegroup UUID.</param> /// <param name="regionUUID">The region UUID.</param> private void StoreSceneObjectPrimShapes(SceneObjectPart sceneObjectPart, SqlCommand sqlCommand, UUID sceneGroupID, UUID regionUUID) { //Big query to or insert or update primshapes //Note for SQL Server 2008 this can be simplified string queryPrimShapes = @" IF EXISTS (SELECT UUID FROM primshapes WHERE UUID = @UUID) BEGIN UPDATE primshapes SET Shape = @Shape, ScaleX = @ScaleX, ScaleY = @ScaleY, ScaleZ = @ScaleZ, PCode = @PCode, PathBegin = @PathBegin, PathEnd = @PathEnd, PathScaleX = @PathScaleX, PathScaleY = @PathScaleY, PathShearX = @PathShearX, PathShearY = @PathShearY, PathSkew = @PathSkew, PathCurve = @PathCurve, PathRadiusOffset = @PathRadiusOffset, PathRevolutions = @PathRevolutions, PathTaperX = @PathTaperX, PathTaperY = @PathTaperY, PathTwist = @PathTwist, PathTwistBegin = @PathTwistBegin, ProfileBegin = @ProfileBegin, ProfileEnd = @ProfileEnd, ProfileCurve = @ProfileCurve, ProfileHollow = @ProfileHollow, Texture = @Texture, ExtraParams = @ExtraParams, State = @State, Media = @Media WHERE UUID = @UUID END ELSE BEGIN INSERT INTO primshapes ( UUID, Shape, ScaleX, ScaleY, ScaleZ, PCode, PathBegin, PathEnd, PathScaleX, PathScaleY, PathShearX, PathShearY, PathSkew, PathCurve, PathRadiusOffset, PathRevolutions, PathTaperX, PathTaperY, PathTwist, PathTwistBegin, ProfileBegin, ProfileEnd, ProfileCurve, ProfileHollow, Texture, ExtraParams, State, Media ) VALUES ( @UUID, @Shape, @ScaleX, @ScaleY, @ScaleZ, @PCode, @PathBegin, @PathEnd, @PathScaleX, @PathScaleY, @PathShearX, @PathShearY, @PathSkew, @PathCurve, @PathRadiusOffset, @PathRevolutions, @PathTaperX, @PathTaperY, @PathTwist, @PathTwistBegin, @ProfileBegin, @ProfileEnd, @ProfileCurve, @ProfileHollow, @Texture, @ExtraParams, @State, @Media ) END"; //Set commandtext. sqlCommand.CommandText = queryPrimShapes; //Add parameters sqlCommand.Parameters.AddRange(CreatePrimShapeParameters(sceneObjectPart, sceneGroupID, regionUUID)); //Execute the query. If it fails then error is trapped in calling function sqlCommand.ExecuteNonQuery(); } /// <summary> /// Removes a object from the database. /// Meaning removing it from tables Prims, PrimShapes and PrimItems /// </summary> /// <param name="objectID">id of scenegroup</param> /// <param name="regionUUID">regionUUID (is this used anyway</param> public void RemoveObject(UUID objectID, UUID regionUUID) { _Log.InfoFormat("[MSSQL]: Removing obj: {0} from region: {1}", objectID, regionUUID); //Remove from prims and primsitem table string sqlPrims = "DELETE FROM PRIMS WHERE SceneGroupID = @objectID"; string sqlPrimItems = "DELETE FROM PRIMITEMS WHERE primID in (SELECT UUID FROM PRIMS WHERE SceneGroupID = @objectID)"; string sqlPrimShapes = "DELETE FROM PRIMSHAPES WHERE uuid in (SELECT UUID FROM PRIMS WHERE SceneGroupID = @objectID)"; lock (_Database) { //Using the non transaction mode. using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandText = sqlPrimShapes; conn.Open(); cmd.Parameters.Add(_Database.CreateParameter("objectID", objectID)); cmd.ExecuteNonQuery(); cmd.CommandText = sqlPrimItems; cmd.ExecuteNonQuery(); cmd.CommandText = sqlPrims; cmd.ExecuteNonQuery(); } } } /// <summary> /// Store the inventory of a prim. Warning deletes everything first and then adds all again. /// </summary> /// <param name="primID"></param> /// <param name="items"></param> public void StorePrimInventory(UUID primID, ICollection<TaskInventoryItem> items) { //_Log.InfoFormat("[REGION DB: Persisting Prim Inventory with prim ID {0}", primID); //Statement from MySQL section! // For now, we're just going to crudely remove all the previous inventory items // no matter whether they have changed or not, and replace them with the current set. //Delete everything from PrimID //TODO add index on PrimID in DB, if not already exist string sql = "DELETE PRIMITEMS WHERE primID = @primID"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.Add(_Database.CreateParameter("@primID", primID)); conn.Open(); cmd.ExecuteNonQuery(); } sql = @"INSERT INTO primitems ( itemID,primID,assetID,parentFolderID,invType,assetType,name,description,creationDate,creatorID,ownerID,lastOwnerID,groupID, nextPermissions,currentPermissions,basePermissions,everyonePermissions,groupPermissions,flags) VALUES (@itemID,@primID,@assetID,@parentFolderID,@invType,@assetType,@name,@description,@creationDate,@creatorID,@ownerID, @lastOwnerID,@groupID,@nextPermissions,@currentPermissions,@basePermissions,@everyonePermissions,@groupPermissions,@flags)"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { foreach (TaskInventoryItem taskItem in items) { cmd.Parameters.AddRange(CreatePrimInventoryParameters(taskItem)); conn.Open(); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } } } #endregion /// <summary> /// Loads the terrain map. /// </summary> /// <param name="regionID">regionID.</param> /// <returns></returns> public double[,] LoadTerrain(UUID regionID) { double[,] terrain = new double[(int)Constants.RegionSize, (int)Constants.RegionSize]; terrain.Initialize(); string sql = "select top 1 RegionUUID, Revision, Heightfield from terrain where RegionUUID = @RegionUUID order by Revision desc"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { // MySqlParameter param = new MySqlParameter(); cmd.Parameters.Add(_Database.CreateParameter("@RegionUUID", regionID)); conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { int rev; if (reader.Read()) { MemoryStream str = new MemoryStream((byte[])reader["Heightfield"]); BinaryReader br = new BinaryReader(str); for (int x = 0; x < (int)Constants.RegionSize; x++) { for (int y = 0; y < (int)Constants.RegionSize; y++) { terrain[x, y] = br.ReadDouble(); } } rev = (int)reader["Revision"]; } else { _Log.Info("[REGION DB]: No terrain found for region"); return null; } _Log.Info("[REGION DB]: Loaded terrain revision r" + rev); } } return terrain; } /// <summary> /// Stores the terrain map to DB. /// </summary> /// <param name="terrain">terrain map data.</param> /// <param name="regionID">regionID.</param> public void StoreTerrain(double[,] terrain, UUID regionID) { int revision = Util.UnixTimeSinceEpoch(); //Delete old terrain map string sql = "delete from terrain where RegionUUID=@RegionUUID"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.Add(_Database.CreateParameter("@RegionUUID", regionID)); conn.Open(); cmd.ExecuteNonQuery(); } sql = "insert into terrain(RegionUUID, Revision, Heightfield) values(@RegionUUID, @Revision, @Heightfield)"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.Add(_Database.CreateParameter("@RegionUUID", regionID)); cmd.Parameters.Add(_Database.CreateParameter("@Revision", revision)); cmd.Parameters.Add(_Database.CreateParameter("@Heightfield", serializeTerrain(terrain))); conn.Open(); cmd.ExecuteNonQuery(); } _Log.Info("[REGION DB]: Stored terrain revision r " + revision); } /// <summary> /// Loads all the land objects of a region. /// </summary> /// <param name="regionUUID">The region UUID.</param> /// <returns></returns> public List<LandData> LoadLandObjects(UUID regionUUID) { List<LandData> LandDataForRegion = new List<LandData>(); string sql = "select * from land where RegionUUID = @RegionUUID"; //Retrieve all land data from region using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.Add(_Database.CreateParameter("@RegionUUID", regionUUID)); conn.Open(); using (SqlDataReader readerLandData = cmd.ExecuteReader()) { while (readerLandData.Read()) { LandDataForRegion.Add(BuildLandData(readerLandData)); } } } //Retrieve all accesslist data for all landdata foreach (LandData LandData in LandDataForRegion) { sql = "select * from landaccesslist where LandUUID = @LandUUID"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.Add(_Database.CreateParameter("@LandUUID", LandData.GlobalID)); conn.Open(); using (SqlDataReader readerAccessList = cmd.ExecuteReader()) { while (readerAccessList.Read()) { LandData.ParcelAccessList.Add(BuildLandAccessData(readerAccessList)); } } } } //Return data return LandDataForRegion; } /// <summary> /// Stores land object with landaccess list. /// </summary> /// <param name="parcel">parcel data.</param> public void StoreLandObject(ILandObject parcel) { //As this is only one record in land table I just delete all and then add a new record. //As the delete landaccess is already in the mysql code //Delete old values RemoveLandObject(parcel.LandData.GlobalID); //Insert new values string sql = @"INSERT INTO [land] ([UUID],[RegionUUID],[LocalLandID],[Bitmap],[Name],[Description],[OwnerUUID],[IsGroupOwned],[Area],[AuctionID],[Category],[ClaimDate],[ClaimPrice],[GroupUUID],[SalePrice],[LandStatus],[LandFlags],[LandingType],[MediaAutoScale],[MediaTextureUUID],[MediaURL],[MusicURL],[PassHours],[PassPrice],[SnapshotUUID],[UserLocationX],[UserLocationY],[UserLocationZ],[UserLookAtX],[UserLookAtY],[UserLookAtZ],[AuthbuyerID],[OtherCleanTime]) VALUES (@UUID,@RegionUUID,@LocalLandID,@Bitmap,@Name,@Description,@OwnerUUID,@IsGroupOwned,@Area,@AuctionID,@Category,@ClaimDate,@ClaimPrice,@GroupUUID,@SalePrice,@LandStatus,@LandFlags,@LandingType,@MediaAutoScale,@MediaTextureUUID,@MediaURL,@MusicURL,@PassHours,@PassPrice,@SnapshotUUID,@UserLocationX,@UserLocationY,@UserLocationZ,@UserLookAtX,@UserLookAtY,@UserLookAtZ,@AuthbuyerID,@OtherCleanTime)"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddRange(CreateLandParameters(parcel.LandData, parcel.RegionUUID)); conn.Open(); cmd.ExecuteNonQuery(); } sql = "INSERT INTO [landaccesslist] ([LandUUID],[AccessUUID],[Flags]) VALUES (@LandUUID,@AccessUUID,@Flags)"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { conn.Open(); foreach (ParcelManager.ParcelAccessEntry parcelAccessEntry in parcel.LandData.ParcelAccessList) { cmd.Parameters.AddRange(CreateLandAccessParameters(parcelAccessEntry, parcel.RegionUUID)); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } } } /// <summary> /// Removes a land object from DB. /// </summary> /// <param name="globalID">UUID of landobject</param> public void RemoveLandObject(UUID globalID) { string sql = "delete from land where UUID=@UUID"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.Add(_Database.CreateParameter("@UUID", globalID)); conn.Open(); cmd.ExecuteNonQuery(); } sql = "delete from landaccesslist where LandUUID=@UUID"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.Add(_Database.CreateParameter("@UUID", globalID)); conn.Open(); cmd.ExecuteNonQuery(); } } public RegionLightShareData LoadRegionWindlightSettings(UUID regionUUID) { //This connector doesn't support the windlight module yet //Return default LL windlight settings return new RegionLightShareData(); } public void RemoveRegionWindlightSettings(UUID regionID) { } public void StoreRegionWindlightSettings(RegionLightShareData wl) { //This connector doesn't support the windlight module yet } /// <summary> /// Loads the settings of a region. /// </summary> /// <param name="regionUUID">The region UUID.</param> /// <returns></returns> public RegionSettings LoadRegionSettings(UUID regionUUID) { string sql = "select * from regionsettings where regionUUID = @regionUUID"; RegionSettings regionSettings; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.Add(_Database.CreateParameter("@regionUUID", regionUUID)); conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { regionSettings = BuildRegionSettings(reader); regionSettings.OnSave += StoreRegionSettings; return regionSettings; } } } //If we reach this point then there are new region settings for that region regionSettings = new RegionSettings(); regionSettings.RegionUUID = regionUUID; regionSettings.OnSave += StoreRegionSettings; //Store new values StoreNewRegionSettings(regionSettings); return regionSettings; } /// <summary> /// Store region settings, need to check if the check is really necesary. If we can make something for creating new region. /// </summary> /// <param name="regionSettings">region settings.</param> public void StoreRegionSettings(RegionSettings regionSettings) { //Little check if regionUUID already exist in DB string regionUUID; string sql = "SELECT regionUUID FROM regionsettings WHERE regionUUID = @regionUUID"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.Add(_Database.CreateParameter("@regionUUID", regionSettings.RegionUUID)); conn.Open(); regionUUID = cmd.ExecuteScalar().ToString(); } if (string.IsNullOrEmpty(regionUUID)) { StoreNewRegionSettings(regionSettings); } else { //This method only updates region settings!!! First call LoadRegionSettings to create new region settings in DB sql = @"UPDATE [regionsettings] SET [block_terraform] = @block_terraform ,[block_fly] = @block_fly ,[allow_damage] = @allow_damage ,[restrict_pushing] = @restrict_pushing ,[allow_land_resell] = @allow_land_resell ,[allow_land_join_divide] = @allow_land_join_divide ,[block_show_in_search] = @block_show_in_search ,[agent_limit] = @agent_limit ,[object_bonus] = @object_bonus ,[maturity] = @maturity ,[disable_scripts] = @disable_scripts ,[disable_collisions] = @disable_collisions ,[disable_physics] = @disable_physics ,[terrain_texture_1] = @terrain_texture_1 ,[terrain_texture_2] = @terrain_texture_2 ,[terrain_texture_3] = @terrain_texture_3 ,[terrain_texture_4] = @terrain_texture_4 ,[elevation_1_nw] = @elevation_1_nw ,[elevation_2_nw] = @elevation_2_nw ,[elevation_1_ne] = @elevation_1_ne ,[elevation_2_ne] = @elevation_2_ne ,[elevation_1_se] = @elevation_1_se ,[elevation_2_se] = @elevation_2_se ,[elevation_1_sw] = @elevation_1_sw ,[elevation_2_sw] = @elevation_2_sw ,[water_height] = @water_height ,[terrain_raise_limit] = @terrain_raise_limit ,[terrain_lower_limit] = @terrain_lower_limit ,[use_estate_sun] = @use_estate_sun ,[fixed_sun] = @fixed_sun ,[sun_position] = @sun_position ,[covenant] = @covenant , [sunvectorx] = @sunvectorx, [sunvectory] = @sunvectory, [sunvectorz] = @sunvectorz, [Sandbox] = @Sandbox, [loaded_creation_datetime] = @loaded_creation_datetime, [loaded_creation_id] = @loaded_creation_id WHERE [regionUUID] = @regionUUID"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddRange(CreateRegionSettingParameters(regionSettings)); conn.Open(); cmd.ExecuteNonQuery(); } } } public void Shutdown() { //Not used?? } #region Private Methods /// <summary> /// Serializes the terrain data for storage in DB. /// </summary> /// <param name="val">terrain data</param> /// <returns></returns> private static Array serializeTerrain(double[,] val) { MemoryStream str = new MemoryStream(((int)Constants.RegionSize * (int)Constants.RegionSize) * sizeof(double)); BinaryWriter bw = new BinaryWriter(str); // TODO: COMPATIBILITY - Add byte-order conversions for (int x = 0; x < (int)Constants.RegionSize; x++) for (int y = 0; y < (int)Constants.RegionSize; y++) { double height = val[x, y]; if (height == 0.0) height = double.Epsilon; bw.Write(height); } return str.ToArray(); } /// <summary> /// Stores new regionsettings. /// </summary> /// <param name="regionSettings">The region settings.</param> private void StoreNewRegionSettings(RegionSettings regionSettings) { string sql = @"INSERT INTO [regionsettings] ([regionUUID],[block_terraform],[block_fly],[allow_damage],[restrict_pushing],[allow_land_resell],[allow_land_join_divide], [block_show_in_search],[agent_limit],[object_bonus],[maturity],[disable_scripts],[disable_collisions],[disable_physics], [terrain_texture_1],[terrain_texture_2],[terrain_texture_3],[terrain_texture_4],[elevation_1_nw],[elevation_2_nw],[elevation_1_ne], [elevation_2_ne],[elevation_1_se],[elevation_2_se],[elevation_1_sw],[elevation_2_sw],[water_height],[terrain_raise_limit], [terrain_lower_limit],[use_estate_sun],[fixed_sun],[sun_position],[covenant],[sunvectorx], [sunvectory], [sunvectorz],[Sandbox], [loaded_creation_datetime], [loaded_creation_id] ) VALUES (@regionUUID,@block_terraform,@block_fly,@allow_damage,@restrict_pushing,@allow_land_resell,@allow_land_join_divide, @block_show_in_search,@agent_limit,@object_bonus,@maturity,@disable_scripts,@disable_collisions,@disable_physics, @terrain_texture_1,@terrain_texture_2,@terrain_texture_3,@terrain_texture_4,@elevation_1_nw,@elevation_2_nw,@elevation_1_ne, @elevation_2_ne,@elevation_1_se,@elevation_2_se,@elevation_1_sw,@elevation_2_sw,@water_height,@terrain_raise_limit, @terrain_lower_limit,@use_estate_sun,@fixed_sun,@sun_position,@covenant,@sunvectorx,@sunvectory, @sunvectorz, @Sandbox, @loaded_creation_datetime, @loaded_creation_id)"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddRange(CreateRegionSettingParameters(regionSettings)); conn.Open(); cmd.ExecuteNonQuery(); } } #region Private DataRecord conversion methods /// <summary> /// Builds the region settings from a datarecod. /// </summary> /// <param name="row">datarecord with regionsettings.</param> /// <returns></returns> private static RegionSettings BuildRegionSettings(IDataRecord row) { //TODO change this is some more generic code so we doesnt have to change it every time a new field is added? RegionSettings newSettings = new RegionSettings(); newSettings.RegionUUID = new UUID((Guid)row["regionUUID"]); newSettings.BlockTerraform = Convert.ToBoolean(row["block_terraform"]); newSettings.AllowDamage = Convert.ToBoolean(row["allow_damage"]); newSettings.BlockFly = Convert.ToBoolean(row["block_fly"]); newSettings.RestrictPushing = Convert.ToBoolean(row["restrict_pushing"]); newSettings.AllowLandResell = Convert.ToBoolean(row["allow_land_resell"]); newSettings.AllowLandJoinDivide = Convert.ToBoolean(row["allow_land_join_divide"]); newSettings.BlockShowInSearch = Convert.ToBoolean(row["block_show_in_search"]); newSettings.AgentLimit = Convert.ToInt32(row["agent_limit"]); newSettings.ObjectBonus = Convert.ToDouble(row["object_bonus"]); newSettings.Maturity = Convert.ToInt32(row["maturity"]); newSettings.DisableScripts = Convert.ToBoolean(row["disable_scripts"]); newSettings.DisableCollisions = Convert.ToBoolean(row["disable_collisions"]); newSettings.DisablePhysics = Convert.ToBoolean(row["disable_physics"]); newSettings.TerrainTexture1 = new UUID((Guid)row["terrain_texture_1"]); newSettings.TerrainTexture2 = new UUID((Guid)row["terrain_texture_2"]); newSettings.TerrainTexture3 = new UUID((Guid)row["terrain_texture_3"]); newSettings.TerrainTexture4 = new UUID((Guid)row["terrain_texture_4"]); newSettings.Elevation1NW = Convert.ToDouble(row["elevation_1_nw"]); newSettings.Elevation2NW = Convert.ToDouble(row["elevation_2_nw"]); newSettings.Elevation1NE = Convert.ToDouble(row["elevation_1_ne"]); newSettings.Elevation2NE = Convert.ToDouble(row["elevation_2_ne"]); newSettings.Elevation1SE = Convert.ToDouble(row["elevation_1_se"]); newSettings.Elevation2SE = Convert.ToDouble(row["elevation_2_se"]); newSettings.Elevation1SW = Convert.ToDouble(row["elevation_1_sw"]); newSettings.Elevation2SW = Convert.ToDouble(row["elevation_2_sw"]); newSettings.WaterHeight = Convert.ToDouble(row["water_height"]); newSettings.TerrainRaiseLimit = Convert.ToDouble(row["terrain_raise_limit"]); newSettings.TerrainLowerLimit = Convert.ToDouble(row["terrain_lower_limit"]); newSettings.UseEstateSun = Convert.ToBoolean(row["use_estate_sun"]); newSettings.Sandbox = Convert.ToBoolean(row["sandbox"]); newSettings.FixedSun = Convert.ToBoolean(row["fixed_sun"]); newSettings.SunPosition = Convert.ToDouble(row["sun_position"]); newSettings.SunVector = new Vector3( Convert.ToSingle(row["sunvectorx"]), Convert.ToSingle(row["sunvectory"]), Convert.ToSingle(row["sunvectorz"]) ); newSettings.Covenant = new UUID((Guid)row["covenant"]); newSettings.LoadedCreationDateTime = Convert.ToInt32(row["loaded_creation_datetime"]); if (row["loaded_creation_id"] is DBNull) newSettings.LoadedCreationID = ""; else newSettings.LoadedCreationID = (String)row["loaded_creation_id"]; return newSettings; } /// <summary> /// Builds the land data from a datarecord. /// </summary> /// <param name="row">datarecord with land data</param> /// <returns></returns> private static LandData BuildLandData(IDataRecord row) { LandData newData = new LandData(); newData.GlobalID = new UUID((Guid)row["UUID"]); newData.LocalID = Convert.ToInt32(row["LocalLandID"]); // Bitmap is a byte[512] newData.Bitmap = (Byte[])row["Bitmap"]; newData.Name = (string)row["Name"]; newData.Description = (string)row["Description"]; newData.OwnerID = new UUID((Guid)row["OwnerUUID"]); newData.IsGroupOwned = Convert.ToBoolean(row["IsGroupOwned"]); newData.Area = Convert.ToInt32(row["Area"]); newData.AuctionID = Convert.ToUInt32(row["AuctionID"]); //Unemplemented newData.Category = (ParcelCategory)Convert.ToInt32(row["Category"]); //Enum libsecondlife.Parcel.ParcelCategory newData.ClaimDate = Convert.ToInt32(row["ClaimDate"]); newData.ClaimPrice = Convert.ToInt32(row["ClaimPrice"]); newData.GroupID = new UUID((Guid)row["GroupUUID"]); newData.SalePrice = Convert.ToInt32(row["SalePrice"]); newData.Status = (ParcelStatus)Convert.ToInt32(row["LandStatus"]); //Enum. libsecondlife.Parcel.ParcelStatus newData.Flags = Convert.ToUInt32(row["LandFlags"]); newData.LandingType = Convert.ToByte(row["LandingType"]); newData.MediaAutoScale = Convert.ToByte(row["MediaAutoScale"]); newData.MediaID = new UUID((Guid)row["MediaTextureUUID"]); newData.MediaURL = (string)row["MediaURL"]; newData.MusicURL = (string)row["MusicURL"]; newData.PassHours = Convert.ToSingle(row["PassHours"]); newData.PassPrice = Convert.ToInt32(row["PassPrice"]); // UUID authedbuyer; // UUID snapshotID; // // if (UUID.TryParse((string)row["AuthBuyerID"], out authedbuyer)) // newData.AuthBuyerID = authedbuyer; // // if (UUID.TryParse((string)row["SnapshotUUID"], out snapshotID)) // newData.SnapshotID = snapshotID; newData.AuthBuyerID = new UUID((Guid)row["AuthBuyerID"]); newData.SnapshotID = new UUID((Guid)row["SnapshotUUID"]); newData.OtherCleanTime = Convert.ToInt32(row["OtherCleanTime"]); try { newData.UserLocation = new Vector3(Convert.ToSingle(row["UserLocationX"]), Convert.ToSingle(row["UserLocationY"]), Convert.ToSingle(row["UserLocationZ"])); newData.UserLookAt = new Vector3(Convert.ToSingle(row["UserLookAtX"]), Convert.ToSingle(row["UserLookAtY"]), Convert.ToSingle(row["UserLookAtZ"])); } catch (InvalidCastException) { newData.UserLocation = Vector3.Zero; newData.UserLookAt = Vector3.Zero; _Log.ErrorFormat("[PARCEL]: unable to get parcel telehub settings for {1}", newData.Name); } newData.ParcelAccessList = new List<ParcelManager.ParcelAccessEntry>(); return newData; } /// <summary> /// Builds the landaccess data from a data record. /// </summary> /// <param name="row">datarecord with landaccess data</param> /// <returns></returns> private static ParcelManager.ParcelAccessEntry BuildLandAccessData(IDataRecord row) { ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry(); entry.AgentID = new UUID((Guid)row["AccessUUID"]); entry.Flags = (AccessList)Convert.ToInt32(row["Flags"]); entry.Time = new DateTime(); return entry; } /// <summary> /// Builds the prim from a datarecord. /// </summary> /// <param name="primRow">datarecord</param> /// <returns></returns> private static SceneObjectPart BuildPrim(IDataRecord primRow) { SceneObjectPart prim = new SceneObjectPart(); prim.UUID = new UUID((Guid)primRow["UUID"]); // explicit conversion of integers is required, which sort // of sucks. No idea if there is a shortcut here or not. prim.CreationDate = Convert.ToInt32(primRow["CreationDate"]); prim.Name = (string)primRow["Name"]; // various text fields prim.Text = (string)primRow["Text"]; prim.Color = Color.FromArgb(Convert.ToInt32(primRow["ColorA"]), Convert.ToInt32(primRow["ColorR"]), Convert.ToInt32(primRow["ColorG"]), Convert.ToInt32(primRow["ColorB"])); prim.Description = (string)primRow["Description"]; prim.SitName = (string)primRow["SitName"]; prim.TouchName = (string)primRow["TouchName"]; // permissions prim.Flags = (PrimFlags)Convert.ToUInt32(primRow["ObjectFlags"]); prim.CreatorID = new UUID((Guid)primRow["CreatorID"]); prim.OwnerID = new UUID((Guid)primRow["OwnerID"]); prim.GroupID = new UUID((Guid)primRow["GroupID"]); prim.LastOwnerID = new UUID((Guid)primRow["LastOwnerID"]); prim.OwnerMask = Convert.ToUInt32(primRow["OwnerMask"]); prim.NextOwnerMask = Convert.ToUInt32(primRow["NextOwnerMask"]); prim.GroupMask = Convert.ToUInt32(primRow["GroupMask"]); prim.EveryoneMask = Convert.ToUInt32(primRow["EveryoneMask"]); prim.BaseMask = Convert.ToUInt32(primRow["BaseMask"]); // vectors prim.OffsetPosition = new Vector3( Convert.ToSingle(primRow["PositionX"]), Convert.ToSingle(primRow["PositionY"]), Convert.ToSingle(primRow["PositionZ"])); prim.GroupPosition = new Vector3( Convert.ToSingle(primRow["GroupPositionX"]), Convert.ToSingle(primRow["GroupPositionY"]), Convert.ToSingle(primRow["GroupPositionZ"])); prim.Velocity = new Vector3( Convert.ToSingle(primRow["VelocityX"]), Convert.ToSingle(primRow["VelocityY"]), Convert.ToSingle(primRow["VelocityZ"])); prim.AngularVelocity = new Vector3( Convert.ToSingle(primRow["AngularVelocityX"]), Convert.ToSingle(primRow["AngularVelocityY"]), Convert.ToSingle(primRow["AngularVelocityZ"])); prim.Acceleration = new Vector3( Convert.ToSingle(primRow["AccelerationX"]), Convert.ToSingle(primRow["AccelerationY"]), Convert.ToSingle(primRow["AccelerationZ"])); // quaternions prim.RotationOffset = new Quaternion( Convert.ToSingle(primRow["RotationX"]), Convert.ToSingle(primRow["RotationY"]), Convert.ToSingle(primRow["RotationZ"]), Convert.ToSingle(primRow["RotationW"])); prim.SitTargetPositionLL = new Vector3( Convert.ToSingle(primRow["SitTargetOffsetX"]), Convert.ToSingle(primRow["SitTargetOffsetY"]), Convert.ToSingle(primRow["SitTargetOffsetZ"])); prim.SitTargetOrientationLL = new Quaternion( Convert.ToSingle(primRow["SitTargetOrientX"]), Convert.ToSingle(primRow["SitTargetOrientY"]), Convert.ToSingle(primRow["SitTargetOrientZ"]), Convert.ToSingle(primRow["SitTargetOrientW"])); prim.PayPrice[0] = Convert.ToInt32(primRow["PayPrice"]); prim.PayPrice[1] = Convert.ToInt32(primRow["PayButton1"]); prim.PayPrice[2] = Convert.ToInt32(primRow["PayButton2"]); prim.PayPrice[3] = Convert.ToInt32(primRow["PayButton3"]); prim.PayPrice[4] = Convert.ToInt32(primRow["PayButton4"]); prim.Sound = new UUID((Guid)primRow["LoopedSound"]); prim.SoundGain = Convert.ToSingle(primRow["LoopedSoundGain"]); prim.SoundFlags = 1; // If it's persisted at all, it's looped if (!(primRow["TextureAnimation"] is DBNull)) prim.TextureAnimation = (Byte[])primRow["TextureAnimation"]; if (!(primRow["ParticleSystem"] is DBNull)) prim.ParticleSystem = (Byte[])primRow["ParticleSystem"]; prim.AngularVelocity = new Vector3( Convert.ToSingle(primRow["OmegaX"]), Convert.ToSingle(primRow["OmegaY"]), Convert.ToSingle(primRow["OmegaZ"])); prim.SetCameraEyeOffset(new Vector3( Convert.ToSingle(primRow["CameraEyeOffsetX"]), Convert.ToSingle(primRow["CameraEyeOffsetY"]), Convert.ToSingle(primRow["CameraEyeOffsetZ"]) )); prim.SetCameraAtOffset(new Vector3( Convert.ToSingle(primRow["CameraAtOffsetX"]), Convert.ToSingle(primRow["CameraAtOffsetY"]), Convert.ToSingle(primRow["CameraAtOffsetZ"]) )); if (Convert.ToInt16(primRow["ForceMouselook"]) != 0) prim.SetForceMouselook(true); prim.ScriptAccessPin = Convert.ToInt32(primRow["ScriptAccessPin"]); if (Convert.ToInt16(primRow["AllowedDrop"]) != 0) prim.AllowedDrop = true; if (Convert.ToInt16(primRow["DieAtEdge"]) != 0) prim.DIE_AT_EDGE = true; prim.SalePrice = Convert.ToInt32(primRow["SalePrice"]); prim.ObjectSaleType = Convert.ToByte(primRow["SaleType"]); prim.Material = Convert.ToByte(primRow["Material"]); if (!(primRow["ClickAction"] is DBNull)) prim.ClickAction = Convert.ToByte(primRow["ClickAction"]); prim.CollisionSound = new UUID((Guid)primRow["CollisionSound"]); prim.CollisionSoundVolume = Convert.ToSingle(primRow["CollisionSoundVolume"]); if (Convert.ToInt16(primRow["PassTouches"]) != 0) prim.PassTouches = true; prim.LinkNum = Convert.ToInt32(primRow["LinkNumber"]); if (!(primRow["MediaURL"] is System.DBNull)) prim.MediaUrl = (string)primRow["MediaURL"]; return prim; } /// <summary> /// Builds the prim shape from a datarecord. /// </summary> /// <param name="shapeRow">The row.</param> /// <returns></returns> private static PrimitiveBaseShape BuildShape(IDataRecord shapeRow) { PrimitiveBaseShape baseShape = new PrimitiveBaseShape(); baseShape.Scale = new Vector3( Convert.ToSingle(shapeRow["ScaleX"]), Convert.ToSingle(shapeRow["ScaleY"]), Convert.ToSingle(shapeRow["ScaleZ"])); // paths baseShape.PCode = Convert.ToByte(shapeRow["PCode"]); baseShape.PathBegin = Convert.ToUInt16(shapeRow["PathBegin"]); baseShape.PathEnd = Convert.ToUInt16(shapeRow["PathEnd"]); baseShape.PathScaleX = Convert.ToByte(shapeRow["PathScaleX"]); baseShape.PathScaleY = Convert.ToByte(shapeRow["PathScaleY"]); baseShape.PathShearX = Convert.ToByte(shapeRow["PathShearX"]); baseShape.PathShearY = Convert.ToByte(shapeRow["PathShearY"]); baseShape.PathSkew = Convert.ToSByte(shapeRow["PathSkew"]); baseShape.PathCurve = Convert.ToByte(shapeRow["PathCurve"]); baseShape.PathRadiusOffset = Convert.ToSByte(shapeRow["PathRadiusOffset"]); baseShape.PathRevolutions = Convert.ToByte(shapeRow["PathRevolutions"]); baseShape.PathTaperX = Convert.ToSByte(shapeRow["PathTaperX"]); baseShape.PathTaperY = Convert.ToSByte(shapeRow["PathTaperY"]); baseShape.PathTwist = Convert.ToSByte(shapeRow["PathTwist"]); baseShape.PathTwistBegin = Convert.ToSByte(shapeRow["PathTwistBegin"]); // profile baseShape.ProfileBegin = Convert.ToUInt16(shapeRow["ProfileBegin"]); baseShape.ProfileEnd = Convert.ToUInt16(shapeRow["ProfileEnd"]); baseShape.ProfileCurve = Convert.ToByte(shapeRow["ProfileCurve"]); baseShape.ProfileHollow = Convert.ToUInt16(shapeRow["ProfileHollow"]); byte[] textureEntry = (byte[])shapeRow["Texture"]; baseShape.TextureEntry = textureEntry; baseShape.ExtraParams = (byte[])shapeRow["ExtraParams"]; try { baseShape.State = Convert.ToByte(shapeRow["State"]); } catch (InvalidCastException) { } if (!(shapeRow["Media"] is System.DBNull)) baseShape.Media = PrimitiveBaseShape.MediaList.FromXml((string)shapeRow["Media"]); return baseShape; } /// <summary> /// Build a prim inventory item from the persisted data. /// </summary> /// <param name="inventoryRow"></param> /// <returns></returns> private static TaskInventoryItem BuildItem(IDataRecord inventoryRow) { TaskInventoryItem taskItem = new TaskInventoryItem(); taskItem.ItemID = new UUID((Guid)inventoryRow["itemID"]); taskItem.ParentPartID = new UUID((Guid)inventoryRow["primID"]); taskItem.AssetID = new UUID((Guid)inventoryRow["assetID"]); taskItem.ParentID = new UUID((Guid)inventoryRow["parentFolderID"]); taskItem.InvType = Convert.ToInt32(inventoryRow["invType"]); taskItem.Type = Convert.ToInt32(inventoryRow["assetType"]); taskItem.Name = (string)inventoryRow["name"]; taskItem.Description = (string)inventoryRow["description"]; taskItem.CreationDate = Convert.ToUInt32(inventoryRow["creationDate"]); taskItem.CreatorID = new UUID((Guid)inventoryRow["creatorID"]); taskItem.OwnerID = new UUID((Guid)inventoryRow["ownerID"]); taskItem.LastOwnerID = new UUID((Guid)inventoryRow["lastOwnerID"]); taskItem.GroupID = new UUID((Guid)inventoryRow["groupID"]); taskItem.NextPermissions = Convert.ToUInt32(inventoryRow["nextPermissions"]); taskItem.CurrentPermissions = Convert.ToUInt32(inventoryRow["currentPermissions"]); taskItem.BasePermissions = Convert.ToUInt32(inventoryRow["basePermissions"]); taskItem.EveryonePermissions = Convert.ToUInt32(inventoryRow["everyonePermissions"]); taskItem.GroupPermissions = Convert.ToUInt32(inventoryRow["groupPermissions"]); taskItem.Flags = Convert.ToUInt32(inventoryRow["flags"]); return taskItem; } #endregion #region Create parameters methods /// <summary> /// Creates the prim inventory parameters. /// </summary> /// <param name="taskItem">item in inventory.</param> /// <returns></returns> private SqlParameter[] CreatePrimInventoryParameters(TaskInventoryItem taskItem) { List<SqlParameter> parameters = new List<SqlParameter>(); parameters.Add(_Database.CreateParameter("itemID", taskItem.ItemID)); parameters.Add(_Database.CreateParameter("primID", taskItem.ParentPartID)); parameters.Add(_Database.CreateParameter("assetID", taskItem.AssetID)); parameters.Add(_Database.CreateParameter("parentFolderID", taskItem.ParentID)); parameters.Add(_Database.CreateParameter("invType", taskItem.InvType)); parameters.Add(_Database.CreateParameter("assetType", taskItem.Type)); parameters.Add(_Database.CreateParameter("name", taskItem.Name)); parameters.Add(_Database.CreateParameter("description", taskItem.Description)); parameters.Add(_Database.CreateParameter("creationDate", taskItem.CreationDate)); parameters.Add(_Database.CreateParameter("creatorID", taskItem.CreatorID)); parameters.Add(_Database.CreateParameter("ownerID", taskItem.OwnerID)); parameters.Add(_Database.CreateParameter("lastOwnerID", taskItem.LastOwnerID)); parameters.Add(_Database.CreateParameter("groupID", taskItem.GroupID)); parameters.Add(_Database.CreateParameter("nextPermissions", taskItem.NextPermissions)); parameters.Add(_Database.CreateParameter("currentPermissions", taskItem.CurrentPermissions)); parameters.Add(_Database.CreateParameter("basePermissions", taskItem.BasePermissions)); parameters.Add(_Database.CreateParameter("everyonePermissions", taskItem.EveryonePermissions)); parameters.Add(_Database.CreateParameter("groupPermissions", taskItem.GroupPermissions)); parameters.Add(_Database.CreateParameter("flags", taskItem.Flags)); return parameters.ToArray(); } /// <summary> /// Creates the region setting parameters. /// </summary> /// <param name="settings">regionsettings.</param> /// <returns></returns> private SqlParameter[] CreateRegionSettingParameters(RegionSettings settings) { List<SqlParameter> parameters = new List<SqlParameter>(); parameters.Add(_Database.CreateParameter("regionUUID", settings.RegionUUID)); parameters.Add(_Database.CreateParameter("block_terraform", settings.BlockTerraform)); parameters.Add(_Database.CreateParameter("block_fly", settings.BlockFly)); parameters.Add(_Database.CreateParameter("allow_damage", settings.AllowDamage)); parameters.Add(_Database.CreateParameter("restrict_pushing", settings.RestrictPushing)); parameters.Add(_Database.CreateParameter("allow_land_resell", settings.AllowLandResell)); parameters.Add(_Database.CreateParameter("allow_land_join_divide", settings.AllowLandJoinDivide)); parameters.Add(_Database.CreateParameter("block_show_in_search", settings.BlockShowInSearch)); parameters.Add(_Database.CreateParameter("agent_limit", settings.AgentLimit)); parameters.Add(_Database.CreateParameter("object_bonus", settings.ObjectBonus)); parameters.Add(_Database.CreateParameter("maturity", settings.Maturity)); parameters.Add(_Database.CreateParameter("disable_scripts", settings.DisableScripts)); parameters.Add(_Database.CreateParameter("disable_collisions", settings.DisableCollisions)); parameters.Add(_Database.CreateParameter("disable_physics", settings.DisablePhysics)); parameters.Add(_Database.CreateParameter("terrain_texture_1", settings.TerrainTexture1)); parameters.Add(_Database.CreateParameter("terrain_texture_2", settings.TerrainTexture2)); parameters.Add(_Database.CreateParameter("terrain_texture_3", settings.TerrainTexture3)); parameters.Add(_Database.CreateParameter("terrain_texture_4", settings.TerrainTexture4)); parameters.Add(_Database.CreateParameter("elevation_1_nw", settings.Elevation1NW)); parameters.Add(_Database.CreateParameter("elevation_2_nw", settings.Elevation2NW)); parameters.Add(_Database.CreateParameter("elevation_1_ne", settings.Elevation1NE)); parameters.Add(_Database.CreateParameter("elevation_2_ne", settings.Elevation2NE)); parameters.Add(_Database.CreateParameter("elevation_1_se", settings.Elevation1SE)); parameters.Add(_Database.CreateParameter("elevation_2_se", settings.Elevation2SE)); parameters.Add(_Database.CreateParameter("elevation_1_sw", settings.Elevation1SW)); parameters.Add(_Database.CreateParameter("elevation_2_sw", settings.Elevation2SW)); parameters.Add(_Database.CreateParameter("water_height", settings.WaterHeight)); parameters.Add(_Database.CreateParameter("terrain_raise_limit", settings.TerrainRaiseLimit)); parameters.Add(_Database.CreateParameter("terrain_lower_limit", settings.TerrainLowerLimit)); parameters.Add(_Database.CreateParameter("use_estate_sun", settings.UseEstateSun)); parameters.Add(_Database.CreateParameter("sandbox", settings.Sandbox)); parameters.Add(_Database.CreateParameter("fixed_sun", settings.FixedSun)); parameters.Add(_Database.CreateParameter("sun_position", settings.SunPosition)); parameters.Add(_Database.CreateParameter("sunvectorx", settings.SunVector.X)); parameters.Add(_Database.CreateParameter("sunvectory", settings.SunVector.Y)); parameters.Add(_Database.CreateParameter("sunvectorz", settings.SunVector.Z)); parameters.Add(_Database.CreateParameter("covenant", settings.Covenant)); parameters.Add(_Database.CreateParameter("Loaded_Creation_DateTime", settings.LoadedCreationDateTime)); parameters.Add(_Database.CreateParameter("Loaded_Creation_ID", settings.LoadedCreationID)); return parameters.ToArray(); } /// <summary> /// Creates the land parameters. /// </summary> /// <param name="land">land parameters.</param> /// <param name="regionUUID">region UUID.</param> /// <returns></returns> private SqlParameter[] CreateLandParameters(LandData land, UUID regionUUID) { List<SqlParameter> parameters = new List<SqlParameter>(); parameters.Add(_Database.CreateParameter("UUID", land.GlobalID)); parameters.Add(_Database.CreateParameter("RegionUUID", regionUUID)); parameters.Add(_Database.CreateParameter("LocalLandID", land.LocalID)); // Bitmap is a byte[512] parameters.Add(_Database.CreateParameter("Bitmap", land.Bitmap)); parameters.Add(_Database.CreateParameter("Name", land.Name)); parameters.Add(_Database.CreateParameter("Description", land.Description)); parameters.Add(_Database.CreateParameter("OwnerUUID", land.OwnerID)); parameters.Add(_Database.CreateParameter("IsGroupOwned", land.IsGroupOwned)); parameters.Add(_Database.CreateParameter("Area", land.Area)); parameters.Add(_Database.CreateParameter("AuctionID", land.AuctionID)); //Unemplemented parameters.Add(_Database.CreateParameter("Category", (int)land.Category)); //Enum libsecondlife.Parcel.ParcelCategory parameters.Add(_Database.CreateParameter("ClaimDate", land.ClaimDate)); parameters.Add(_Database.CreateParameter("ClaimPrice", land.ClaimPrice)); parameters.Add(_Database.CreateParameter("GroupUUID", land.GroupID)); parameters.Add(_Database.CreateParameter("SalePrice", land.SalePrice)); parameters.Add(_Database.CreateParameter("LandStatus", (int)land.Status)); //Enum. libsecondlife.Parcel.ParcelStatus parameters.Add(_Database.CreateParameter("LandFlags", land.Flags)); parameters.Add(_Database.CreateParameter("LandingType", land.LandingType)); parameters.Add(_Database.CreateParameter("MediaAutoScale", land.MediaAutoScale)); parameters.Add(_Database.CreateParameter("MediaTextureUUID", land.MediaID)); parameters.Add(_Database.CreateParameter("MediaURL", land.MediaURL)); parameters.Add(_Database.CreateParameter("MusicURL", land.MusicURL)); parameters.Add(_Database.CreateParameter("PassHours", land.PassHours)); parameters.Add(_Database.CreateParameter("PassPrice", land.PassPrice)); parameters.Add(_Database.CreateParameter("SnapshotUUID", land.SnapshotID)); parameters.Add(_Database.CreateParameter("UserLocationX", land.UserLocation.X)); parameters.Add(_Database.CreateParameter("UserLocationY", land.UserLocation.Y)); parameters.Add(_Database.CreateParameter("UserLocationZ", land.UserLocation.Z)); parameters.Add(_Database.CreateParameter("UserLookAtX", land.UserLookAt.X)); parameters.Add(_Database.CreateParameter("UserLookAtY", land.UserLookAt.Y)); parameters.Add(_Database.CreateParameter("UserLookAtZ", land.UserLookAt.Z)); parameters.Add(_Database.CreateParameter("AuthBuyerID", land.AuthBuyerID)); parameters.Add(_Database.CreateParameter("OtherCleanTime", land.OtherCleanTime)); return parameters.ToArray(); } /// <summary> /// Creates the land access parameters. /// </summary> /// <param name="parcelAccessEntry">parcel access entry.</param> /// <param name="parcelID">parcel ID.</param> /// <returns></returns> private SqlParameter[] CreateLandAccessParameters(ParcelManager.ParcelAccessEntry parcelAccessEntry, UUID parcelID) { List<SqlParameter> parameters = new List<SqlParameter>(); parameters.Add(_Database.CreateParameter("LandUUID", parcelID)); parameters.Add(_Database.CreateParameter("AccessUUID", parcelAccessEntry.AgentID)); parameters.Add(_Database.CreateParameter("Flags", parcelAccessEntry.Flags)); return parameters.ToArray(); } /// <summary> /// Creates the prim parameters for storing in DB. /// </summary> /// <param name="prim">Basic data of SceneObjectpart prim.</param> /// <param name="sceneGroupID">The scenegroup ID.</param> /// <param name="regionUUID">The region ID.</param> /// <returns></returns> private SqlParameter[] CreatePrimParameters(SceneObjectPart prim, UUID sceneGroupID, UUID regionUUID) { List<SqlParameter> parameters = new List<SqlParameter>(); parameters.Add(_Database.CreateParameter("UUID", prim.UUID)); parameters.Add(_Database.CreateParameter("RegionUUID", regionUUID)); parameters.Add(_Database.CreateParameter("CreationDate", prim.CreationDate)); parameters.Add(_Database.CreateParameter("Name", prim.Name)); parameters.Add(_Database.CreateParameter("SceneGroupID", sceneGroupID)); // the UUID of the root part for this SceneObjectGroup // various text fields parameters.Add(_Database.CreateParameter("Text", prim.Text)); parameters.Add(_Database.CreateParameter("ColorR", prim.Color.R)); parameters.Add(_Database.CreateParameter("ColorG", prim.Color.G)); parameters.Add(_Database.CreateParameter("ColorB", prim.Color.B)); parameters.Add(_Database.CreateParameter("ColorA", prim.Color.A)); parameters.Add(_Database.CreateParameter("Description", prim.Description)); parameters.Add(_Database.CreateParameter("SitName", prim.SitName)); parameters.Add(_Database.CreateParameter("TouchName", prim.TouchName)); // permissions parameters.Add(_Database.CreateParameter("ObjectFlags", (uint)prim.Flags)); parameters.Add(_Database.CreateParameter("CreatorID", prim.CreatorID)); parameters.Add(_Database.CreateParameter("OwnerID", prim.OwnerID)); parameters.Add(_Database.CreateParameter("GroupID", prim.GroupID)); parameters.Add(_Database.CreateParameter("LastOwnerID", prim.LastOwnerID)); parameters.Add(_Database.CreateParameter("OwnerMask", prim.OwnerMask)); parameters.Add(_Database.CreateParameter("NextOwnerMask", prim.NextOwnerMask)); parameters.Add(_Database.CreateParameter("GroupMask", prim.GroupMask)); parameters.Add(_Database.CreateParameter("EveryoneMask", prim.EveryoneMask)); parameters.Add(_Database.CreateParameter("BaseMask", prim.BaseMask)); // vectors parameters.Add(_Database.CreateParameter("PositionX", prim.OffsetPosition.X)); parameters.Add(_Database.CreateParameter("PositionY", prim.OffsetPosition.Y)); parameters.Add(_Database.CreateParameter("PositionZ", prim.OffsetPosition.Z)); parameters.Add(_Database.CreateParameter("GroupPositionX", prim.GroupPosition.X)); parameters.Add(_Database.CreateParameter("GroupPositionY", prim.GroupPosition.Y)); parameters.Add(_Database.CreateParameter("GroupPositionZ", prim.GroupPosition.Z)); parameters.Add(_Database.CreateParameter("VelocityX", prim.Velocity.X)); parameters.Add(_Database.CreateParameter("VelocityY", prim.Velocity.Y)); parameters.Add(_Database.CreateParameter("VelocityZ", prim.Velocity.Z)); parameters.Add(_Database.CreateParameter("AngularVelocityX", prim.AngularVelocity.X)); parameters.Add(_Database.CreateParameter("AngularVelocityY", prim.AngularVelocity.Y)); parameters.Add(_Database.CreateParameter("AngularVelocityZ", prim.AngularVelocity.Z)); parameters.Add(_Database.CreateParameter("AccelerationX", prim.Acceleration.X)); parameters.Add(_Database.CreateParameter("AccelerationY", prim.Acceleration.Y)); parameters.Add(_Database.CreateParameter("AccelerationZ", prim.Acceleration.Z)); // quaternions parameters.Add(_Database.CreateParameter("RotationX", prim.RotationOffset.X)); parameters.Add(_Database.CreateParameter("RotationY", prim.RotationOffset.Y)); parameters.Add(_Database.CreateParameter("RotationZ", prim.RotationOffset.Z)); parameters.Add(_Database.CreateParameter("RotationW", prim.RotationOffset.W)); // Sit target Vector3 sitTargetPos = prim.SitTargetPositionLL; parameters.Add(_Database.CreateParameter("SitTargetOffsetX", sitTargetPos.X)); parameters.Add(_Database.CreateParameter("SitTargetOffsetY", sitTargetPos.Y)); parameters.Add(_Database.CreateParameter("SitTargetOffsetZ", sitTargetPos.Z)); Quaternion sitTargetOrient = prim.SitTargetOrientationLL; parameters.Add(_Database.CreateParameter("SitTargetOrientW", sitTargetOrient.W)); parameters.Add(_Database.CreateParameter("SitTargetOrientX", sitTargetOrient.X)); parameters.Add(_Database.CreateParameter("SitTargetOrientY", sitTargetOrient.Y)); parameters.Add(_Database.CreateParameter("SitTargetOrientZ", sitTargetOrient.Z)); parameters.Add(_Database.CreateParameter("PayPrice", prim.PayPrice[0])); parameters.Add(_Database.CreateParameter("PayButton1", prim.PayPrice[1])); parameters.Add(_Database.CreateParameter("PayButton2", prim.PayPrice[2])); parameters.Add(_Database.CreateParameter("PayButton3", prim.PayPrice[3])); parameters.Add(_Database.CreateParameter("PayButton4", prim.PayPrice[4])); if ((prim.SoundFlags & 1) != 0) // Looped { parameters.Add(_Database.CreateParameter("LoopedSound", prim.Sound)); parameters.Add(_Database.CreateParameter("LoopedSoundGain", prim.SoundGain)); } else { parameters.Add(_Database.CreateParameter("LoopedSound", UUID.Zero)); parameters.Add(_Database.CreateParameter("LoopedSoundGain", 0.0f)); } parameters.Add(_Database.CreateParameter("TextureAnimation", prim.TextureAnimation)); parameters.Add(_Database.CreateParameter("ParticleSystem", prim.ParticleSystem)); parameters.Add(_Database.CreateParameter("OmegaX", prim.AngularVelocity.X)); parameters.Add(_Database.CreateParameter("OmegaY", prim.AngularVelocity.Y)); parameters.Add(_Database.CreateParameter("OmegaZ", prim.AngularVelocity.Z)); parameters.Add(_Database.CreateParameter("CameraEyeOffsetX", prim.GetCameraEyeOffset().X)); parameters.Add(_Database.CreateParameter("CameraEyeOffsetY", prim.GetCameraEyeOffset().Y)); parameters.Add(_Database.CreateParameter("CameraEyeOffsetZ", prim.GetCameraEyeOffset().Z)); parameters.Add(_Database.CreateParameter("CameraAtOffsetX", prim.GetCameraAtOffset().X)); parameters.Add(_Database.CreateParameter("CameraAtOffsetY", prim.GetCameraAtOffset().Y)); parameters.Add(_Database.CreateParameter("CameraAtOffsetZ", prim.GetCameraAtOffset().Z)); if (prim.GetForceMouselook()) parameters.Add(_Database.CreateParameter("ForceMouselook", 1)); else parameters.Add(_Database.CreateParameter("ForceMouselook", 0)); parameters.Add(_Database.CreateParameter("ScriptAccessPin", prim.ScriptAccessPin)); if (prim.AllowedDrop) parameters.Add(_Database.CreateParameter("AllowedDrop", 1)); else parameters.Add(_Database.CreateParameter("AllowedDrop", 0)); if (prim.DIE_AT_EDGE) parameters.Add(_Database.CreateParameter("DieAtEdge", 1)); else parameters.Add(_Database.CreateParameter("DieAtEdge", 0)); parameters.Add(_Database.CreateParameter("SalePrice", prim.SalePrice)); parameters.Add(_Database.CreateParameter("SaleType", prim.ObjectSaleType)); byte clickAction = prim.ClickAction; parameters.Add(_Database.CreateParameter("ClickAction", clickAction)); parameters.Add(_Database.CreateParameter("Material", prim.Material)); parameters.Add(_Database.CreateParameter("CollisionSound", prim.CollisionSound)); parameters.Add(_Database.CreateParameter("CollisionSoundVolume", prim.CollisionSoundVolume)); if (prim.PassTouches) parameters.Add(_Database.CreateParameter("PassTouches", 1)); else parameters.Add(_Database.CreateParameter("PassTouches", 0)); parameters.Add(_Database.CreateParameter("LinkNumber", prim.LinkNum)); parameters.Add(_Database.CreateParameter("MediaURL", prim.MediaUrl)); return parameters.ToArray(); } /// <summary> /// Creates the primshape parameters for stroing in DB. /// </summary> /// <param name="prim">Basic data of SceneObjectpart prim.</param> /// <param name="sceneGroupID">The scene group ID.</param> /// <param name="regionUUID">The region UUID.</param> /// <returns></returns> private SqlParameter[] CreatePrimShapeParameters(SceneObjectPart prim, UUID sceneGroupID, UUID regionUUID) { List<SqlParameter> parameters = new List<SqlParameter>(); PrimitiveBaseShape s = prim.Shape; parameters.Add(_Database.CreateParameter("UUID", prim.UUID)); // shape is an enum parameters.Add(_Database.CreateParameter("Shape", 0)); // vectors parameters.Add(_Database.CreateParameter("ScaleX", s.Scale.X)); parameters.Add(_Database.CreateParameter("ScaleY", s.Scale.Y)); parameters.Add(_Database.CreateParameter("ScaleZ", s.Scale.Z)); // paths parameters.Add(_Database.CreateParameter("PCode", s.PCode)); parameters.Add(_Database.CreateParameter("PathBegin", s.PathBegin)); parameters.Add(_Database.CreateParameter("PathEnd", s.PathEnd)); parameters.Add(_Database.CreateParameter("PathScaleX", s.PathScaleX)); parameters.Add(_Database.CreateParameter("PathScaleY", s.PathScaleY)); parameters.Add(_Database.CreateParameter("PathShearX", s.PathShearX)); parameters.Add(_Database.CreateParameter("PathShearY", s.PathShearY)); parameters.Add(_Database.CreateParameter("PathSkew", s.PathSkew)); parameters.Add(_Database.CreateParameter("PathCurve", s.PathCurve)); parameters.Add(_Database.CreateParameter("PathRadiusOffset", s.PathRadiusOffset)); parameters.Add(_Database.CreateParameter("PathRevolutions", s.PathRevolutions)); parameters.Add(_Database.CreateParameter("PathTaperX", s.PathTaperX)); parameters.Add(_Database.CreateParameter("PathTaperY", s.PathTaperY)); parameters.Add(_Database.CreateParameter("PathTwist", s.PathTwist)); parameters.Add(_Database.CreateParameter("PathTwistBegin", s.PathTwistBegin)); // profile parameters.Add(_Database.CreateParameter("ProfileBegin", s.ProfileBegin)); parameters.Add(_Database.CreateParameter("ProfileEnd", s.ProfileEnd)); parameters.Add(_Database.CreateParameter("ProfileCurve", s.ProfileCurve)); parameters.Add(_Database.CreateParameter("ProfileHollow", s.ProfileHollow)); parameters.Add(_Database.CreateParameter("Texture", s.TextureEntry)); parameters.Add(_Database.CreateParameter("ExtraParams", s.ExtraParams)); parameters.Add(_Database.CreateParameter("State", s.State)); parameters.Add(_Database.CreateParameter("Media", null == s.Media ? null : s.Media.ToXml())); return parameters.ToArray(); } #endregion #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace Project_LoFi { //Enum for Game States public enum GameState { Intro, Menu, Menu2, Playing, Won, Credits, GameOver } //Enum for seperate states that run along side game states public enum CoState { } //Enum for who's turn it is public enum TurnState { Player, NPC } //Enum for unit selection public enum SelectState { Selected, NotSelected } /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; // Map GridOccupant[,] map; //class declarations Level scenario; GamePlay gamePlay; GameVariables gameVars; //Darren Farr CharacterSheet characterSheet; Cursor cursor; PlayerUnit selectedUnit; Drawer screenDrawer; //Jesse Cooper EnemyAI enemyAI; //Darren Farr //States GameState currentState; TurnState currentTurn; SelectState selected; //Keyboard states to track keys KeyboardState keyState; KeyboardState previousKeyState; //Lists List<PlayerUnit> characterList; List<EnemyUnit> enemyList; List<PlayerUnit> activePList; //Arrays // 0:Number of turns, 1:did player move, 2:player name, 3: did enemy move, 4:enemy name, 5:was attack called, 6:dmg delt // 7:Attacker, 8:Target string[] textLog; //variables int numOfTurns; double timer; int enemyNum; float timeToMove; int frameNum; int level; int maxLevel = 3; bool winSound = false; bool songStarted = false; private Random rand; //Get this game started public Game1() { graphics = new GraphicsDeviceManager(this); //set window size graphics.PreferredBackBufferHeight = 780; graphics.PreferredBackBufferWidth = 1200; //set content directory Content.RootDirectory = "Content"; //setup variable storage class gameVars = new GameVariables(this.Content); //set initial game state currentState = GameState.Intro; selected = SelectState.NotSelected; //set the cursor cursor = new Cursor(); // Set up the draw class screenDrawer = new Drawer(); //set number of turns to 6 numOfTurns = 6; enemyNum = 0; timeToMove = 2; //set level to 1 level = 1; //setup the textLog array textLog = new string[10]{numOfTurns.ToString(), "false", "", "false", "", "false", "", "", "", ""}; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here gamePlay = new GamePlay(); characterSheet = new CharacterSheet(); characterSheet.Hide(); rand = new Random(); frameNum = 0; base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // TODO: use this.Content to load your game content here //load images gameVars.setImages(); //load fonts gameVars.setFont(); gameVars.setSounds(); cursor.setCursorTextures(gameVars.cursor, gameVars.selCursor); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit, pressing escape while playing closes game if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); timer += gameTime.ElapsedGameTime.TotalSeconds; // TODO: Add your update logic here //get current keyboard state keyState = Keyboard.GetState(); //////////////////////////////////////////////////////////////////////////////////////////// //Move to it's own class to keep with current coding form // Play Songs at different stages if (currentState == GameState.Menu) { if (!songStarted) { MediaPlayer.IsRepeating = true; MediaPlayer.Play(gameVars.inGame[5]); songStarted = true; } if (keyState.IsKeyDown(Keys.Enter)) { MediaPlayer.IsRepeating = false; songStarted = false; } } else if (currentState == GameState.Menu2) { if (!songStarted) { MediaPlayer.IsRepeating = true; MediaPlayer.Play(gameVars.inGame[5]); songStarted = true; } if (keyState.IsKeyDown(Keys.Enter)) { MediaPlayer.IsRepeating = false; songStarted = false; } } else if (currentState == GameState.Credits) { if (!songStarted) { MediaPlayer.IsRepeating = true; MediaPlayer.Play(gameVars.inGame[3]); songStarted = true; } if (keyState.IsKeyDown(Keys.Enter)) { MediaPlayer.IsRepeating = false; songStarted = false; } } else if (currentState == GameState.GameOver) { if (!songStarted) { MediaPlayer.IsRepeating = true; MediaPlayer.Play(gameVars.inGame[4]); songStarted = true; } if (keyState.IsKeyDown(Keys.Enter)) { MediaPlayer.IsRepeating = false; songStarted = false; } } //end of chunk to move /////////////////////////////////////////////////////// /*/////////////////////////////////////////////////////////////////////////////////////////////////// --------------------------------------Main Game Loop----------------------------------------------- ///////////////////////////////////////////////////////////////////////////////////////////////////*/ switch (currentState) { case GameState.Intro: { if (keyState.IsKeyDown(Keys.Enter)) //if enter is pressed move to playing state { if (SingleKeyPress(keyState, previousKeyState, Keys.Enter)) { currentState = GameState.Menu; } } if (keyState.IsKeyDown(Keys.Escape)) { currentState = GameState.Menu; } break; } case GameState.Menu: { if (keyState.IsKeyDown(Keys.Enter)) { if (SingleKeyPress(keyState, previousKeyState, Keys.Enter)) { currentState = GameState.Menu2; } } if (keyState.IsKeyDown(Keys.Escape)) //if escape is pressed close game, this is a quick exit for testing { Exit(); } break; } case GameState.Menu2: { if (keyState.IsKeyDown(Keys.Enter)) { if (SingleKeyPress(keyState, previousKeyState, Keys.Enter)) { if (level > 3) { ResetGameForNextLevel(); level = 1; } currentTurn = TurnState.Player; currentState = GameState.Playing; //setup level //level = 3; //test code to force a level not 1 to start first SetupLevel(level, "ItemDatabase.txt", "players.LFP", "MonsterDatabase.txt"); } } if (keyState.IsKeyDown(Keys.Escape)) //if escape is pressed close game, this is a quick exit for testing { Exit(); } break; } case GameState.Playing: { enemyList = scenario.enemyList; if (frameNum % 30 == 0) { characterSheet.UpdateCharSheet(characterList); if (frameNum > 3000) { frameNum = 0; } } frameNum++; /*/////////////////////////////////////////////////////////////////////////////////////////////////// --------------------------------------Start of PC TURN----------------------------------------------- ///////////////////////////////////////////////////////////////////////////////////////////////////*/ if (currentTurn == TurnState.Player) { screenDrawer.HighlightCurrentEnemy(false, null); textLog[0] = numOfTurns.ToString(); if (numOfTurns == 0) { numOfTurns = 6; textLog[3] = "false"; textLog[1] = "false"; } cursor.isVisible = true; screenDrawer.updateTextLog(textLog); //check for cursor movement if (keyState.IsKeyDown(Keys.Up)) { if (SingleKeyPress(keyState, previousKeyState, Keys.Up)) { //move the cursor up 1 grid space if (cursor.cursorPos.Y > 0) { cursor.cursorPos.Y -= 1; } } } if (keyState.IsKeyDown(Keys.Down)) { if (SingleKeyPress(keyState, previousKeyState, Keys.Down)) { if (cursor.cursorPos.Y < 10) { cursor.cursorPos.Y += 1; } } } if (keyState.IsKeyDown(Keys.Left)) { if (SingleKeyPress(keyState, previousKeyState, Keys.Left)) { //move the cursor left 1 grid space if (cursor.cursorPos.X > 0) { cursor.cursorPos.X -= 1; } } } if (keyState.IsKeyDown(Keys.Right)) { if (SingleKeyPress(keyState, previousKeyState, Keys.Right)) { //move the cursor right 1 grid space if (cursor.cursorPos.X < 19) { cursor.cursorPos.X += 1; } } } // Check if they selected a unit if (keyState.IsKeyDown(Keys.Z)) { if (SingleKeyPress(keyState, previousKeyState, Keys.Z)) { int cursorX = cursor.cursorPos.X; int cursorY = cursor.cursorPos.Y; if (selected == SelectState.NotSelected) // If we haven't selected a unit { if (map[cursorX, cursorY] is PlayerUnit) { cursor.Selected = true; selectedUnit = (PlayerUnit)map[cursorX, cursorY]; // Cast the unit selected = SelectState.Selected; } } else // We have a unit selected, now we want to move { if (map[cursorX, cursorY] is Terrain) // They aren't moving into another unit { if (MovementValid(cursorX, cursorY, selectedUnit.X, selectedUnit.Y) == true) { Terrain tempHolder = (Terrain)map[cursorX, cursorY]; if (tempHolder.Impassable == false) // If they *can* move there { // Re-insert the terrain they're on right now map[selectedUnit.X, selectedUnit.Y] = selectedUnit.OccupiedSpace; // Assign the space they're moving into to occupiedSpace selectedUnit.OccupiedSpace = (Terrain)map[cursorX, cursorY]; // Move the unit map[cursorX, cursorY] = selectedUnit; selectedUnit.X = cursorX; selectedUnit.Y = cursorY; //update text log info to be drawn to screen textLog[1] = "true"; textLog[2] = selectedUnit.Name; textLog[5] = "false"; textLog[6] = ""; textLog[7] = ""; textLog[8] = ""; screenDrawer.updateTextLog(textLog); // Deselect the unit, they've moved selected = SelectState.NotSelected; cursor.Selected = false; //change cursor back to unselected and decrement their number of turns //screenDrawer.SelectedUnit = null; selectedUnit = null; numOfTurns--; } } } else if (map[cursorX, cursorY] is EnemyUnit) { if (MovementValid(cursorX, cursorY, selectedUnit.X, selectedUnit.Y) == true) { EnemyUnit target = (EnemyUnit)map[cursorX, cursorY]; //pop up pre-attack info here (e.g. tell them the expected result) //Will also need to mess with adding more states again, to see if //they press Z to confirm the attack or X to cancel //update text log info to be drawn to screen textLog[1] = "false"; textLog[7] = selectedUnit.Name; textLog[8] = target.Name; textLog[5] = "true"; screenDrawer.updateTextLog(textLog); textLog[6] = selectedUnit.Attack(target).ToString(); //attack sounds int soundNum = DetermineCharcaterAttackSoundAccordingToJesse(selectedUnit); if (soundNum == 1) gameVars.attackWithSword.Play(); else if (soundNum == 2) gameVars.rogueAttack.Play(); else if (soundNum == 3) gameVars.mageAttack.Play(); if (target.IsDead() == true) { //remove monster corpse target.RemoveCorpse(map); enemyList.Remove(target); if (target.IsBoss) { currentState = GameState.Won; winSound = true; } } // Deselect the unit, they've attacked selected = SelectState.NotSelected; cursor.Selected = false; //change cursor back to unselected and decrement their number of turns selectedUnit = null; numOfTurns--; } } }//End of else }//End of singleKeyPress } if (keyState.IsKeyDown(Keys.X)) { if (SingleKeyPress(keyState, previousKeyState, Keys.X)) { cursor.Selected = false; //screenDrawer.SelectedUnit = null; if (selected == SelectState.Selected) { selected = SelectState.NotSelected; selectedUnit = null; } } } if(keyState.IsKeyDown(Keys.C)) { if (SingleKeyPress(keyState, previousKeyState, Keys.C)) { if(characterSheet.IsOpen()) { gamePlay.CloseCharacterSheet(characterSheet); } else if (!characterSheet.IsOpen()) { gamePlay.OpenCharacterSheet(characterSheet); } } } if (Keyboard.GetState().GetPressedKeys().Length > 0) { gamePlay.MoveCursor(keyState); } //if player uses all their turns change game state if(numOfTurns == 0) { currentTurn = TurnState.NPC; timer = 0; enemyNum = 0; timeToMove = 2; cursor.isVisible = false; } } /*///////////////////////////////////////////////////////////////////////////////////////////////////// --------------------------------------------------End of PC TURN-------------------------------------- /////////////////////////////////////////////////////////////////////////////////////////////////////// --------------------------------------------------Start of NPC TURN----------------------------------- /////////////////////////////////////////////////////////////////////////////////////////////////////*/ if (currentTurn == TurnState.NPC) { if (keyState.IsKeyDown(Keys.C)) { if (SingleKeyPress(keyState, previousKeyState, Keys.C)) { if (characterSheet.IsOpen()) { gamePlay.CloseCharacterSheet(characterSheet); } else if (!characterSheet.IsOpen()) { gamePlay.OpenCharacterSheet(characterSheet); } } } textLog[0] = numOfTurns.ToString(); textLog[1] = "false"; screenDrawer.updateTextLog(textLog); //read through list of enemy npcs and perform actions EnemyUnit enemy; if( timer > timeToMove) { enemy = enemyList[enemyNum]; EnemyLogic(enemy); if(enemyNum < enemyList.Count()) { enemyNum++; } timeToMove += 2; } //change back to players state if(enemyNum == enemyList.Count()) { currentTurn = TurnState.Player; timer = 0; } } /*///////////////////////////////////////////////////////////////////////////////////////////////////// --------------------------------------------------End of NPC TURN-------------------------------------- /////////////////////////////////////////////////////////////////////////////////////////////////////*/ if (keyState.IsKeyDown(Keys.Escape)) //if escape is pressed close game, this is a quick exit for testing { Exit(); } foreach (PlayerUnit scrub in characterList) { if (scrub.CurrentExp >= scrub.Level * 8) { scrub.CurrentExp -= scrub.Level * 8; scrub.Level += 1; scrub.Dexterity += 2; scrub.Magic += 2; scrub.Strength += 2; scrub.setStats(); } } //secert key to auto win level if (keyState.IsKeyDown(Keys.NumLock)) //if escape is pressed close game, this is a quick exit for testing { currentState = GameState.Won; winSound = true; } break; } case GameState.Won: { if( winSound ) { gameVars.levelComplete.Play(); winSound = false; } if (keyState.IsKeyDown(Keys.Enter)) { if (SingleKeyPress(keyState, previousKeyState, Keys.Enter)) { level++; if(level >= 4) { currentState = GameState.Credits; } else { currentState = GameState.Playing; //setup level SetupLevel(level, "ItemDatabase.txt", "players.LFP", "MonsterDatabase.txt"); currentTurn = TurnState.Player; } } } if (keyState.IsKeyDown(Keys.Escape)) //if escape is pressed close game, this is a quick exit for testing { Exit(); } break; } case GameState.Credits: { if (keyState.IsKeyDown(Keys.Enter)) { if (SingleKeyPress(keyState, previousKeyState, Keys.Enter)) { currentState = GameState.Menu; } } break; } case GameState.GameOver: { if (keyState.IsKeyDown(Keys.Enter)) { if (SingleKeyPress(keyState, previousKeyState, Keys.Enter)) { currentState = GameState.Menu; } } if (keyState.IsKeyDown(Keys.Escape)) //if escape is pressed close game, this is a quick exit for testing { Exit(); } break; } default: { break; } }//end gamestate switch previousKeyState = keyState;//set previous state for next update base.Update(gameTime); } /*/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// --------------------------------------------------End of Update-------------------------------------------------------------- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////*/ /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); // TODO: Add your drawing code here spriteBatch.Begin(); //draw based on the games current state switch(currentState) { case GameState.Intro: { if(frameNum > 299) { currentState = GameState.Menu; break; } GraphicsDevice.Clear(Color.White); screenDrawer.DrawIntro(gameVars, spriteBatch, GraphicsDevice); //draws the game intro frameNum++; break; } case GameState.Menu: { //stubs for menu code, will need graphics and such here GraphicsDevice.Clear(Color.Black); screenDrawer.DrawMenu(gameVars, spriteBatch, GraphicsDevice); //draws the game menu frameNum = 0; break; } case GameState.Menu2: { GraphicsDevice.Clear(Color.Black); screenDrawer.DrawStory(gameVars, spriteBatch, GraphicsDevice); frameNum = 0; break; } case GameState.Playing: { screenDrawer.DrawMap(map, spriteBatch, gameVars); if (selectedUnit != null) screenDrawer.DrawHighlighter(map, selectedUnit, gameVars, spriteBatch); cursor.Draw(spriteBatch, map, gameVars); screenDrawer.DrawGameInfo(gameVars, spriteBatch, GraphicsDevice, currentTurn); break; } case GameState.Won: { screenDrawer.DrawWon(gameVars, spriteBatch, GraphicsDevice, level, maxLevel); break; } case GameState.GameOver: { screenDrawer.DrawGameOver(gameVars, spriteBatch, GraphicsDevice); break; } case GameState.Credits: { GraphicsDevice.Clear(Color.Black); screenDrawer.DrawCredits(gameVars, spriteBatch, GraphicsDevice); //draws the game menu break; } }//end switch spriteBatch.End(); base.Draw(gameTime); }//end draw /// <summary> /// Setup the game level for play. /// </summary> /// <param name="level"></param> /// <param name="itemListName"></param> /// <param name="pListName"></param> /// <param name="eListName"></param> protected void SetupLevel(int level, string itemListName, string pListName, string eListName) { MediaPlayer.Volume = 0.2f; MediaPlayer.IsRepeating = true; // Load map switch (level) { case 1: { MediaPlayer.Play(gameVars.inGame[0]); scenario = new Level("map1alt.txt", itemListName, pListName, eListName, gameVars); textLog[9] = "Defeat the Red Devil"; screenDrawer.updateTextLog(textLog); characterList = scenario.PlayerList; activePList = characterList; break; } case 2: { ResetGameForNextLevel(); MediaPlayer.Play(gameVars.inGame[1]); scenario.ConstructMap("map2alt.txt"); textLog[9] = "Defeat the Rock Golem"; screenDrawer.updateTextLog(textLog); enemyList = scenario.enemyList; break; } case 3: { ResetGameForNextLevel(); MediaPlayer.Play(gameVars.inGame[2]); scenario.ConstructMap("map3alt.txt"); textLog[9] = "Defeat the evil master Dead Beard"; screenDrawer.updateTextLog(textLog); enemyList = scenario.enemyList; break; } default: { currentState = GameState.Menu; break; } } map = scenario.MapGrid; //setup AI for enemies enemyAI = new EnemyAI(characterList, enemyList); }//end setup level /// <summary> /// Resets variables and the onscreen log to prepare for the next level. /// </summary> protected void ResetGameForNextLevel() { selected = SelectState.NotSelected; //set number of turns to 6 numOfTurns = 6; enemyNum = 0; timeToMove = 2; //setup the textLog array textLog = new string[10] { numOfTurns.ToString(), "false", "", "false", "", "false", "", "", "", "" }; }//end reset /// <summary> /// check to see if a key has been pressed only once /// </summary> /// <param name="current"></param> /// <param name="previous"></param> /// <param name="key"></param> /// <returns></returns> protected bool SingleKeyPress(KeyboardState current, KeyboardState previous, Keys key) { if (current.IsKeyDown(key) && previousKeyState.IsKeyUp(key)) { return true; } else { return false; } }//end single keypress /// <summary> /// Check to see if movement is valid. /// </summary> /// <param name="cX"> cursor.CursorPos.X </param> /// <param name="cY"> cursor.CursorPos.Y </param> /// <param name="sX"> selectedUnit.X </param> /// <param name="sY"> selectedUnit.Y </param> /// <returns></returns> private bool MovementValid(int cX, int cY, int sX, int sY) { bool resultFlag = false; if ((cX == (sX - 1) && cY == sY) || (cX == (sX + 1) && cY == sY) || (cY == (sY - 1) && cX == sX) || (cY == (sY + 1) && cX == sX)) resultFlag = true; return resultFlag; }//end movementValid /// <summary> /// Decides what the enemy will do on their move. /// </summary> /// <param name="enemy"></param> private void EnemyLogic(EnemyUnit enemy) { PlayerUnit player; player = enemyAI.ClosestPlayer(enemy); //get the player closest to the enemy if(player == null && characterList.Count < 1 ) { currentState = GameState.GameOver; return; } screenDrawer.HighlightCurrentEnemy(true, enemy); if (enemyAI.IsPlayerVisible(enemy, player)) //can the enemy see/hear that player { if (enemyAI.IsNextTo(enemy, player)) //is the player next to them { if (enemyAI.AttackPlayer(enemy, player)) //check to see if they should attack { textLog[6] = enemy.Attack(player).ToString(); textLog[2] = ""; textLog[3] = "false"; textLog[5] = "true"; textLog[7] = enemy.Name; textLog[8] = player.Name; screenDrawer.updateTextLog(textLog); if (enemy.Name == "Devil Scorpion" || enemy.Name == "Mauler" || enemy.Name == "Tornado Lizard" || enemy.Name == "Ant Lion" || enemy.Name == "Zombie" || enemy.Name == "Wyvern Chick" || enemy.Name == "Nightmare" || enemy.Name == "Foul Mummy" ) gameVars.enemyBite.Play(); else if (enemy.Name == "Bone Fighter" || enemy.Name == "Living Armor" || enemy.Name == "Sentinel" || enemy.Name == "Dead Beard" || enemy.Name == "Evil Armor" || enemy.Name == "White Knight" || enemy.Name == "Satrage") gameVars.enemySwordAttack.Play(); else if (enemy.Name == "Rock Golem" || enemy.Name == "Red Devil") gameVars.punch.Play(); if(player.IsDead()) { player.RemoveCorpse(map); characterList.Remove(player); if(characterList.Count < 1) { currentState = GameState.GameOver; } } } else if (enemyAI.RunAway(enemy, player)) //should they run away { switch (enemyAI.WhichSide(enemy, player)) { case 0: { enemy.Move(map, 1); break; } case 1: { enemy.Move(map, 0); break; } case 2: { enemy.Move(map, 3); break; } case 3: { enemy.Move(map, 2); break; } case 4: { /* No Movement */ break; } default: { /* No Movement */ break; } }//end switch //update draw information textLog[2] = ""; textLog[3] = "true"; textLog[4] = enemy.Name; textLog[5] = "false"; screenDrawer.updateTextLog(textLog); }//end run away move }//end if next to else { if (enemyAI.MoveTowardsPlayer(enemy, player)) //if a playe is nearby and visible, maybe move towards them { switch (enemyAI.WhichSide(enemy, player)) { case 0: { enemy.Move(map, 0); break; } case 1: { enemy.Move(map, 1); break; } case 2: { enemy.Move(map, 2); break; } case 3: { enemy.Move(map, 3); break; } case 4: { /* No Movement */ break; } default: { /* No Movement */ break; } }//end switch //update draw information textLog[2] = ""; textLog[3] = "true"; textLog[4] = enemy.Name; textLog[5] = "false"; screenDrawer.updateTextLog(textLog); } } }//end is player visible logic else if((rand.Next(1,101) % 2) == 0) { enemy.Move(map, rand.Next(0, 5)); } }//end enemy logic /// <summary> /// Determine which sound effect to play. /// </summary> /// <param name="selectedUnit"></param> /// <returns>int value of sound effect</returns> protected int DetermineCharcaterAttackSoundAccordingToJesse(Unit selectedUnit) { if (selectedUnit.Strength > selectedUnit.Dexterity && selectedUnit.Strength > selectedUnit.Magic) { return 1; } if (selectedUnit.Dexterity > selectedUnit.Strength && selectedUnit.Dexterity > selectedUnit.Magic) { return 2; } if (selectedUnit.Magic > selectedUnit.Strength && selectedUnit.Magic > selectedUnit.Dexterity) { return 3; } return 1; }//end determine sound effect }//end class }
/* MIT License Copyright (c) 2017 Saied Zarrinmehr 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.Linq; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Shapes; using System.Windows.Controls; using System.Windows.Input; using SpatialAnalysis.FieldUtility; using SpatialAnalysis.Visualization; using System.Collections.Generic; using System; using SpatialAnalysis.CellularEnvironment; using SpatialAnalysis.Geometry; using SpatialAnalysis.Miscellaneous; namespace SpatialAnalysis.FieldUtility.Visualization { /// <summary> /// Visualize gradient paths /// </summary> public class PathVisualHost : FrameworkElement { private OSMDocument _host { get; set; } private double pathThickness { get; set; } private Brush pathBrush { get; set; } private List<System.Windows.Media.Geometry> geoms { get; set; } private MenuItem visualizationMenu { get; set; } private MenuItem draw_menu { get; set; } private MenuItem set_iterations_menu { get; set; } private MenuItem set_gradient_stepSize_menu { get; set; } private MenuItem hide_Show_Menu { get; set; } private MenuItem boarderThickness_Menu { get; set; } private MenuItem boarderBrush_Menu { get; set; } private MenuItem clear_Menu { get; set; } private double maximum_gradient_stepSize; private int maximum_gradient_descent_iterations; // Create a collection of child visual objects. private VisualCollection _children { get; set; } /// <summary> /// Initializes a new instance of the <see cref="PathVisualHost"/> class. /// </summary> public PathVisualHost() { this.maximum_gradient_stepSize = 0.1d; this.maximum_gradient_descent_iterations = 10000; this.pathThickness = 1; this.pathBrush = Brushes.Black; this.geoms = new List<System.Windows.Media.Geometry>(); _children = new VisualCollection(this); this.visualizationMenu = new MenuItem() { Header = "Gradient Path" }; this.draw_menu = new MenuItem() { Header = "Draw Path" }; this.set_iterations_menu = new MenuItem { Header = "Maximum Descent Iterations" }; this.set_gradient_stepSize_menu = new MenuItem { Header = "Maximum Gradient Step-Size" }; this.boarderBrush_Menu = new MenuItem() { Header = "Path Brush" }; this.boarderThickness_Menu = new MenuItem() { Header = "Path Thickness" }; this.hide_Show_Menu = new MenuItem() { Header = "Hide" }; this.clear_Menu = new MenuItem() { Header = "Clear" }; this.visualizationMenu.Items.Add(this.draw_menu); this.visualizationMenu.Items.Add(this.set_gradient_stepSize_menu); this.visualizationMenu.Items.Add(this.set_iterations_menu); this.visualizationMenu.Items.Add(this.boarderThickness_Menu); this.visualizationMenu.Items.Add(this.boarderBrush_Menu); this.visualizationMenu.Items.Add(this.hide_Show_Menu); this.visualizationMenu.Items.Add(this.clear_Menu); this.hide_Show_Menu.Click += hide_Show_Menu_Click; this.boarderThickness_Menu.Click += boarderThickness_Menu_Click; this.boarderBrush_Menu.Click += boarderBrush_Menu_Click; this.clear_Menu.Click += clear_Menu_Click; this.draw_menu.Click += new RoutedEventHandler(findGradientPath_Click); this.set_iterations_menu.Click += Set_iterations_menu_Click; this.set_gradient_stepSize_menu.Click += Set_stepFactor_menu_Click; } private void Set_stepFactor_menu_Click(object sender, RoutedEventArgs e) { GetNumber getNumber = new GetNumber("Gradient Step Size Factor", "Gradients will be multiplied with this factor to descent.", this.maximum_gradient_stepSize); getNumber.Owner = this._host; getNumber.ShowInTaskbar = false; getNumber.ShowDialog(); double number = getNumber.NumberValue; if (number < 0.01) { MessageBox.Show("The new factor should be larger than 0.01"); } else if(number>this._host.cellularFloor.CellSize) { MessageBox.Show("The new factor should be smaller than cell size: " + this._host.cellularFloor.CellSize.ToString("0.0000")); } else { if (number != this.maximum_gradient_stepSize) { this.maximum_gradient_stepSize = number; } } } private void Set_iterations_menu_Click(object sender, RoutedEventArgs e) { GetNumber getNumber = new GetNumber("Set Maximum Descent Iterations", "Descending process will terminate after this number of iterations.", this.maximum_gradient_descent_iterations); getNumber.Owner = this._host; getNumber.ShowInTaskbar = false; getNumber.ShowDialog(); int number = (int)getNumber.NumberValue; if (number < 100) { MessageBox.Show("Iterations should be larger than 100"); } else { if(number != this.maximum_gradient_descent_iterations) { this.maximum_gradient_descent_iterations = number; } } } void clear_Menu_Click(object sender, RoutedEventArgs e) { this._children.Clear(); this.geoms.Clear(); } /// <summary> /// Clears this instance. /// </summary> public void Clear() { this._host = null; this.geoms.Clear(); this.geoms = null; this.hide_Show_Menu.Click -= hide_Show_Menu_Click; this.boarderThickness_Menu.Click -= boarderThickness_Menu_Click; this.boarderBrush_Menu.Click -= boarderBrush_Menu_Click; this.clear_Menu.Click -= clear_Menu_Click; this.draw_menu.Click -= findGradientPath_Click; this.set_iterations_menu.Click -= Set_iterations_menu_Click; this.set_gradient_stepSize_menu.Click -= Set_stepFactor_menu_Click; this.pathBrush = null; this.visualizationMenu = null; this.draw_menu = null; this.hide_Show_Menu = null; this.boarderThickness_Menu = null; this.boarderBrush_Menu = null; this.clear_Menu = null; } void boarderBrush_Menu_Click(object sender, RoutedEventArgs e) { BrushPicker colorPicker = new BrushPicker(this.pathBrush); colorPicker.Owner = this._host; colorPicker.ShowDialog(); this.pathBrush = colorPicker._Brush; //this.reDraw(); /*Do not change the color of the previous pathes*/ colorPicker = null; } void boarderThickness_Menu_Click(object sender, RoutedEventArgs e) { GetNumber gn = new GetNumber("Enter New Thickness Value", "New thickness value will be applied to the paths", this.pathThickness); gn.Owner = this._host; gn.ShowDialog(); this.pathThickness = gn.NumberValue; this.reDraw(); /*Do not change the thickness of the previous pathes*/ gn = null; } void hide_Show_Menu_Click(object sender, RoutedEventArgs e) { if (this.Visibility == System.Windows.Visibility.Visible) { this.Visibility = System.Windows.Visibility.Collapsed; this.hide_Show_Menu.Header = "Show"; this.boarderBrush_Menu.IsEnabled = false; this.boarderThickness_Menu.IsEnabled = false; this.clear_Menu.IsEnabled = false; this.draw_menu.IsEnabled = false; } else { this.Visibility = System.Windows.Visibility.Visible; this.hide_Show_Menu.Header = "Hide"; this.boarderBrush_Menu.IsEnabled = true; this.boarderThickness_Menu.IsEnabled = true; this.clear_Menu.IsEnabled = true; this.draw_menu.IsEnabled = true; } } // Provide a required override for the VisualChildrenCount property. protected override int VisualChildrenCount { get { return _children.Count; } } // Provide a required override for the GetVisualChild method. protected override Visual GetVisualChild(int index) { if (index < 0 || index >= _children.Count) { throw new ArgumentOutOfRangeException(); } return _children[index]; } private void draw(List<UV> path) { double scale = this.getScaleFactor(); Pen pen = new Pen(this.pathBrush, this.pathThickness / scale); DrawingVisual drawingVisual = new DrawingVisual(); using (DrawingContext drawingContext = drawingVisual.RenderOpen()) { StreamGeometry sg = new StreamGeometry(); using (StreamGeometryContext sgc = sg.Open()) { sgc.BeginFigure(this.toPoint(path[0]), false, false); for (int i = 1; i < path.Count; i++) { sgc.LineTo(this.toPoint(path[i]), true, true); } } sg.Freeze(); this.geoms.Add(sg); drawingContext.DrawGeometry(null, pen, sg); } drawingVisual.Drawing.Freeze(); this._children.Add(drawingVisual); } private void reDraw() { if (this.geoms == null || this.geoms.Count == 0) return; double scale = this.getScaleFactor(); Pen pen = new Pen(this.pathBrush, this.pathThickness / scale); _children.Clear(); DrawingVisual drawingVisual = new DrawingVisual(); using (DrawingContext drawingContext = drawingVisual.RenderOpen()) { foreach (System.Windows.Media.Geometry geom in this.geoms) { drawingContext.DrawGeometry(null, pen, geom); } } drawingVisual.Drawing.Freeze(); this._children.Add(drawingVisual); } /// <summary> /// Sets the host. /// </summary> /// <param name="host">The main document to which this control belongs.</param> public void SetHost(OSMDocument host) { this._host = host; this.RenderTransform = this._host.RenderTransformation; this._host._activities.Items.Add(this.visualizationMenu); this.maximum_gradient_stepSize = this._host.UnitConvertor.Convert(0.1); } #region find gradient path private void findGradientPath_Click(object sender, RoutedEventArgs e) { this._host.Menues.IsEnabled = false; this._host.FloorScene.MouseLeftButtonDown += floorScene_GradientPathActive; this._host.MouseBtn.MouseDown += gradientPathRelease; this._host.UIMessage.Text = "Pick a point on the Field"; this._host.UIMessage.Visibility = System.Windows.Visibility.Visible; this._host.Cursor = Cursors.Pen; } private void gradientPathRelease(object sender, MouseButtonEventArgs e) { this._host.FloorScene.MouseLeftButtonDown -= floorScene_GradientPathActive; this._host.CommandReset.MouseDown -= gradientPathRelease; this._host.Menues.IsEnabled = true; this._host.UIMessage.Visibility = System.Windows.Visibility.Hidden; this._host.Cursor = Cursors.Arrow; } private void floorScene_GradientPathActive(object sender, MouseButtonEventArgs e) { Activity activeField = null; foreach (MenuItem item in this._host.ActiveFieldName.Items) { if (item.IsChecked) { if (this._host.AllActivities.TryGetValue((string)item.Header, out activeField)) { break; } } } if (activeField == null) { MessageBox.Show("Active field not found!"); return; } Point p1 = Mouse.GetPosition(this._host.FloorScene); Point p2 = this._host.InverseRenderTransform.Transform(p1); UV p = new UV(p2.X, p2.Y); Cell cellOrigin = this._host.cellularFloor.FindCell(p); if (cellOrigin.VisualOverlapState != OverlapState.Outside) { MessageBox.Show("Pick a point on the walkable field and try again!\n"); return; } try { var path = activeField.GetGradientPath(p,this.maximum_gradient_stepSize,this.maximum_gradient_descent_iterations); this.draw(path); } catch (Exception error) { MessageBox.Show(error.Report()); } } #endregion private Point toPoint(UV p) { return new Point(p.U, p.V); } private double getScaleFactor() { double scale = this.RenderTransform.Value.M11 * this.RenderTransform.Value.M11 + this.RenderTransform.Value.M12 * this.RenderTransform.Value.M12; return Math.Sqrt(scale); } } }
/* * Copyright 2021 Google LLC All Rights Reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file or at * https://developers.google.com/open-source/licenses/bsd */ // <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/type/date.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Type { /// <summary>Holder for reflection information generated from google/type/date.proto</summary> public static partial class DateReflection { #region Descriptor /// <summary>File descriptor for google/type/date.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static DateReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChZnb29nbGUvdHlwZS9kYXRlLnByb3RvEgtnb29nbGUudHlwZSIwCgREYXRl", "EgwKBHllYXIYASABKAUSDQoFbW9udGgYAiABKAUSCwoDZGF5GAMgASgFQl0K", "D2NvbS5nb29nbGUudHlwZUIJRGF0ZVByb3RvUAFaNGdvb2dsZS5nb2xhbmcu", "b3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvdHlwZS9kYXRlO2RhdGX4AQGiAgNH", "VFBiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Type.Date), global::Google.Type.Date.Parser, new[]{ "Year", "Month", "Day" }, null, null, null, null) })); } #endregion } #region Messages /// <summary> /// Represents a whole or partial calendar date, such as a birthday. The time of /// day and time zone are either specified elsewhere or are insignificant. The /// date is relative to the Gregorian Calendar. This can represent one of the /// following: /// /// * A full date, with non-zero year, month, and day values /// * A month and day value, with a zero year, such as an anniversary /// * A year on its own, with zero month and day values /// * A year and month value, with a zero day, such as a credit card expiration /// date /// /// Related types are [google.type.TimeOfDay][google.type.TimeOfDay] and /// `google.protobuf.Timestamp`. /// </summary> public sealed partial class Date : pb::IMessage<Date> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<Date> _parser = new pb::MessageParser<Date>(() => new Date()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Date> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Type.DateReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Date() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Date(Date other) : this() { year_ = other.year_; month_ = other.month_; day_ = other.day_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Date Clone() { return new Date(this); } /// <summary>Field number for the "year" field.</summary> public const int YearFieldNumber = 1; private int year_; /// <summary> /// Year of the date. Must be from 1 to 9999, or 0 to specify a date without /// a year. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Year { get { return year_; } set { year_ = value; } } /// <summary>Field number for the "month" field.</summary> public const int MonthFieldNumber = 2; private int month_; /// <summary> /// Month of a year. Must be from 1 to 12, or 0 to specify a year without a /// month and day. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Month { get { return month_; } set { month_ = value; } } /// <summary>Field number for the "day" field.</summary> public const int DayFieldNumber = 3; private int day_; /// <summary> /// Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 /// to specify a year by itself or a year and month where the day isn't /// significant. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Day { get { return day_; } set { day_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Date); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Date other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Year != other.Year) return false; if (Month != other.Month) return false; if (Day != other.Day) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Year != 0) hash ^= Year.GetHashCode(); if (Month != 0) hash ^= Month.GetHashCode(); if (Day != 0) hash ^= Day.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Year != 0) { output.WriteRawTag(8); output.WriteInt32(Year); } if (Month != 0) { output.WriteRawTag(16); output.WriteInt32(Month); } if (Day != 0) { output.WriteRawTag(24); output.WriteInt32(Day); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Year != 0) { output.WriteRawTag(8); output.WriteInt32(Year); } if (Month != 0) { output.WriteRawTag(16); output.WriteInt32(Month); } if (Day != 0) { output.WriteRawTag(24); output.WriteInt32(Day); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Year != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Year); } if (Month != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Month); } if (Day != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Day); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Date other) { if (other == null) { return; } if (other.Year != 0) { Year = other.Year; } if (other.Month != 0) { Month = other.Month; } if (other.Day != 0) { Day = other.Day; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { Year = input.ReadInt32(); break; } case 16: { Month = input.ReadInt32(); break; } case 24: { Day = input.ReadInt32(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 8: { Year = input.ReadInt32(); break; } case 16: { Month = input.ReadInt32(); break; } case 24: { Day = input.ReadInt32(); break; } } } } #endif } #endregion } #endregion Designer generated code
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // A pair of schedulers that together support concurrent (reader) / exclusive (writer) // task scheduling. Using just the exclusive scheduler can be used to simulate a serial // processing queue, and using just the concurrent scheduler with a specified // MaximumConcurrentlyLevel can be used to achieve a MaxDegreeOfParallelism across // a bunch of tasks, parallel loops, dataflow blocks, etc. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Security; namespace System.Threading.Tasks { /// <summary> /// Provides concurrent and exclusive task schedulers that coordinate to execute /// tasks while ensuring that concurrent tasks may run concurrently and exclusive tasks never do. /// </summary> [DebuggerDisplay("Concurrent={ConcurrentTaskCountForDebugger}, Exclusive={ExclusiveTaskCountForDebugger}, Mode={ModeForDebugger}")] [DebuggerTypeProxy(typeof(ConcurrentExclusiveSchedulerPair.DebugView))] public class ConcurrentExclusiveSchedulerPair { /// <summary>A dictionary mapping thread ID to a processing mode to denote what kinds of tasks are currently being processed on this thread.</summary> private readonly ConcurrentDictionary<int, ProcessingMode> m_threadProcessingMapping = new ConcurrentDictionary<int, ProcessingMode>(); /// <summary>The scheduler used to queue and execute "concurrent" tasks that may run concurrently with other concurrent tasks.</summary> private readonly ConcurrentExclusiveTaskScheduler m_concurrentTaskScheduler; /// <summary>The scheduler used to queue and execute "exclusive" tasks that must run exclusively while no other tasks for this pair are running.</summary> private readonly ConcurrentExclusiveTaskScheduler m_exclusiveTaskScheduler; /// <summary>The underlying task scheduler to which all work should be scheduled.</summary> private readonly TaskScheduler m_underlyingTaskScheduler; /// <summary> /// The maximum number of tasks allowed to run concurrently. This only applies to concurrent tasks, /// since exclusive tasks are inherently limited to 1. /// </summary> private readonly int m_maxConcurrencyLevel; /// <summary>The maximum number of tasks we can process before recycling our runner tasks.</summary> private readonly int m_maxItemsPerTask; /// <summary> /// If positive, it represents the number of concurrently running concurrent tasks. /// If negative, it means an exclusive task has been scheduled. /// If 0, nothing has been scheduled. /// </summary> private int m_processingCount; /// <summary>Completion state for a task representing the completion of this pair.</summary> /// <remarks>Lazily-initialized only if the scheduler pair is shutting down or if the Completion is requested.</remarks> private CompletionState m_completionState; /// <summary>A constant value used to signal unlimited processing.</summary> private const int UNLIMITED_PROCESSING = -1; /// <summary>Constant used for m_processingCount to indicate that an exclusive task is being processed.</summary> private const int EXCLUSIVE_PROCESSING_SENTINEL = -1; /// <summary>Default MaxItemsPerTask to use for processing if none is specified.</summary> private const int DEFAULT_MAXITEMSPERTASK = UNLIMITED_PROCESSING; /// <summary>Default MaxConcurrencyLevel is the processor count if not otherwise specified.</summary> private static Int32 DefaultMaxConcurrencyLevel { get { return Environment.ProcessorCount; } } /// <summary>Gets the sync obj used to protect all state on this instance.</summary> private object ValueLock { get { return m_threadProcessingMapping; } } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair. /// </summary> public ConcurrentExclusiveSchedulerPair() : this(TaskScheduler.Default, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler. /// </summary> /// <param name="taskScheduler">The target scheduler on which this pair should execute.</param> public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler) : this(taskScheduler, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler with a maximum concurrency level. /// </summary> /// <param name="taskScheduler">The target scheduler on which this pair should execute.</param> /// <param name="maxConcurrencyLevel">The maximum number of tasks to run concurrently.</param> public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel) : this(taskScheduler, maxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler with a maximum /// concurrency level and a maximum number of scheduled tasks that may be processed as a unit. /// </summary> /// <param name="taskScheduler">The target scheduler on which this pair should execute.</param> /// <param name="maxConcurrencyLevel">The maximum number of tasks to run concurrently.</param> /// <param name="maxItemsPerTask">The maximum number of tasks to process for each underlying scheduled task used by the pair.</param> public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel, int maxItemsPerTask) { // Validate arguments if (taskScheduler == null) throw new ArgumentNullException(nameof(taskScheduler)); if (maxConcurrencyLevel == 0 || maxConcurrencyLevel < -1) throw new ArgumentOutOfRangeException(nameof(maxConcurrencyLevel)); if (maxItemsPerTask == 0 || maxItemsPerTask < -1) throw new ArgumentOutOfRangeException(nameof(maxItemsPerTask)); Contract.EndContractBlock(); // Store configuration m_underlyingTaskScheduler = taskScheduler; m_maxConcurrencyLevel = maxConcurrencyLevel; m_maxItemsPerTask = maxItemsPerTask; // Downgrade to the underlying scheduler's max degree of parallelism if it's lower than the user-supplied level int mcl = taskScheduler.MaximumConcurrencyLevel; if (mcl > 0 && mcl < m_maxConcurrencyLevel) m_maxConcurrencyLevel = mcl; // Treat UNLIMITED_PROCESSING/-1 for both MCL and MIPT as the biggest possible value so that we don't // have to special case UNLIMITED_PROCESSING later on in processing. if (m_maxConcurrencyLevel == UNLIMITED_PROCESSING) m_maxConcurrencyLevel = Int32.MaxValue; if (m_maxItemsPerTask == UNLIMITED_PROCESSING) m_maxItemsPerTask = Int32.MaxValue; // Create the concurrent/exclusive schedulers for this pair m_exclusiveTaskScheduler = new ConcurrentExclusiveTaskScheduler(this, 1, ProcessingMode.ProcessingExclusiveTask); m_concurrentTaskScheduler = new ConcurrentExclusiveTaskScheduler(this, m_maxConcurrencyLevel, ProcessingMode.ProcessingConcurrentTasks); } /// <summary>Informs the scheduler pair that it should not accept any more tasks.</summary> /// <remarks> /// Calling <see cref="Complete"/> is optional, and it's only necessary if the <see cref="Completion"/> /// will be relied on for notification of all processing being completed. /// </remarks> public void Complete() { lock (ValueLock) { if (!CompletionRequested) { RequestCompletion(); CleanupStateIfCompletingAndQuiesced(); } } } /// <summary>Gets a <see cref="System.Threading.Tasks.Task"/> that will complete when the scheduler has completed processing.</summary> public Task Completion { // ValueLock not needed, but it's ok if it's held get { return EnsureCompletionStateInitialized().Task; } } /// <summary>Gets the lazily-initialized completion state.</summary> private CompletionState EnsureCompletionStateInitialized() { // ValueLock not needed, but it's ok if it's held return LazyInitializer.EnsureInitialized(ref m_completionState, () => new CompletionState()); } /// <summary>Gets whether completion has been requested.</summary> private bool CompletionRequested { // ValueLock not needed, but it's ok if it's held get { return m_completionState != null && Volatile.Read(ref m_completionState.m_completionRequested); } } /// <summary>Sets that completion has been requested.</summary> private void RequestCompletion() { ContractAssertMonitorStatus(ValueLock, held: true); EnsureCompletionStateInitialized().m_completionRequested = true; } /// <summary> /// Cleans up state if and only if there's no processing currently happening /// and no more to be done later. /// </summary> private void CleanupStateIfCompletingAndQuiesced() { ContractAssertMonitorStatus(ValueLock, held: true); if (ReadyToComplete) CompleteTaskAsync(); } /// <summary>Gets whether the pair is ready to complete.</summary> private bool ReadyToComplete { get { ContractAssertMonitorStatus(ValueLock, held: true); // We can only complete if completion has been requested and no processing is currently happening. if (!CompletionRequested || m_processingCount != 0) return false; // Now, only allow shutdown if an exception occurred or if there are no more tasks to process. var cs = EnsureCompletionStateInitialized(); return (cs.m_exceptions != null && cs.m_exceptions.Count > 0) || (m_concurrentTaskScheduler.m_tasks.IsEmpty && m_exclusiveTaskScheduler.m_tasks.IsEmpty); } } /// <summary>Completes the completion task asynchronously.</summary> private void CompleteTaskAsync() { Contract.Requires(ReadyToComplete, "The block must be ready to complete to be here."); ContractAssertMonitorStatus(ValueLock, held: true); // Ensure we only try to complete once, then schedule completion // in order to escape held locks and the caller's context var cs = EnsureCompletionStateInitialized(); if (!cs.m_completionQueued) { cs.m_completionQueued = true; ThreadPool.QueueUserWorkItem(state => { var localCs = (CompletionState)state; // don't use 'cs', as it'll force a closure Debug.Assert(!localCs.Task.IsCompleted, "Completion should only happen once."); var exceptions = localCs.m_exceptions; bool success = (exceptions != null && exceptions.Count > 0) ? localCs.TrySetException(exceptions) : localCs.TrySetResult(default(VoidTaskResult)); Debug.Assert(success, "Expected to complete completion task."); }, cs); } } /// <summary>Initiates scheduler shutdown due to a worker task faulting.</summary> /// <param name="faultedTask">The faulted worker task that's initiating the shutdown.</param> private void FaultWithTask(Task faultedTask) { Contract.Requires(faultedTask != null && faultedTask.IsFaulted && faultedTask.Exception.InnerExceptions.Count > 0, "Needs a task in the faulted state and thus with exceptions."); ContractAssertMonitorStatus(ValueLock, held: true); // Store the faulted task's exceptions var cs = EnsureCompletionStateInitialized(); if (cs.m_exceptions == null) cs.m_exceptions = new List<Exception>(); cs.m_exceptions.AddRange(faultedTask.Exception.InnerExceptions); // Now that we're doomed, request completion RequestCompletion(); } /// <summary> /// Gets a TaskScheduler that can be used to schedule tasks to this pair /// that may run concurrently with other tasks on this pair. /// </summary> public TaskScheduler ConcurrentScheduler { get { return m_concurrentTaskScheduler; } } /// <summary> /// Gets a TaskScheduler that can be used to schedule tasks to this pair /// that must run exclusively with regards to other tasks on this pair. /// </summary> public TaskScheduler ExclusiveScheduler { get { return m_exclusiveTaskScheduler; } } /// <summary>Gets the number of tasks waiting to run concurrently.</summary> /// <remarks>This does not take the necessary lock, as it's only called from under the debugger.</remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private int ConcurrentTaskCountForDebugger { get { return m_concurrentTaskScheduler.m_tasks.Count; } } /// <summary>Gets the number of tasks waiting to run exclusively.</summary> /// <remarks>This does not take the necessary lock, as it's only called from under the debugger.</remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private int ExclusiveTaskCountForDebugger { get { return m_exclusiveTaskScheduler.m_tasks.Count; } } /// <summary>Notifies the pair that new work has arrived to be processed.</summary> /// <param name="fairly">Whether tasks should be scheduled fairly with regards to other tasks.</param> /// <remarks>Must only be called while holding the lock.</remarks> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals")] [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private void ProcessAsyncIfNecessary(bool fairly = false) { ContractAssertMonitorStatus(ValueLock, held: true); // If the current processing count is >= 0, we can potentially launch further processing. if (m_processingCount >= 0) { // We snap whether there are any exclusive tasks or concurrent tasks waiting. // (We grab the concurrent count below only once we know we need it.) // With processing happening concurrent to this operation, this data may // immediately be out of date, but it can only go from non-empty // to empty and not the other way around. As such, this is safe, // as worst case is we'll schedule an extra task when we didn't // otherwise need to, and we'll just eat its overhead. bool exclusiveTasksAreWaiting = !m_exclusiveTaskScheduler.m_tasks.IsEmpty; // If there's no processing currently happening but there are waiting exclusive tasks, // let's start processing those exclusive tasks. Task processingTask = null; if (m_processingCount == 0 && exclusiveTasksAreWaiting) { // Launch exclusive task processing m_processingCount = EXCLUSIVE_PROCESSING_SENTINEL; // -1 try { processingTask = new Task(thisPair => ((ConcurrentExclusiveSchedulerPair)thisPair).ProcessExclusiveTasks(), this, default(CancellationToken), GetCreationOptionsForTask(fairly)); processingTask.Start(m_underlyingTaskScheduler); // When we call Start, if the underlying scheduler throws in QueueTask, TPL will fault the task and rethrow // the exception. To deal with that, we need a reference to the task object, so that we can observe its exception. // Hence, we separate creation and starting, so that we can store a reference to the task before we attempt QueueTask. } catch { m_processingCount = 0; FaultWithTask(processingTask); } } // If there are no waiting exclusive tasks, there are concurrent tasks, and we haven't reached our maximum // concurrency level for processing, let's start processing more concurrent tasks. else { int concurrentTasksWaitingCount = m_concurrentTaskScheduler.m_tasks.Count; if (concurrentTasksWaitingCount > 0 && !exclusiveTasksAreWaiting && m_processingCount < m_maxConcurrencyLevel) { // Launch concurrent task processing, up to the allowed limit for (int i = 0; i < concurrentTasksWaitingCount && m_processingCount < m_maxConcurrencyLevel; ++i) { ++m_processingCount; try { processingTask = new Task(thisPair => ((ConcurrentExclusiveSchedulerPair)thisPair).ProcessConcurrentTasks(), this, default(CancellationToken), GetCreationOptionsForTask(fairly)); processingTask.Start(m_underlyingTaskScheduler); // See above logic for why we use new + Start rather than StartNew } catch { --m_processingCount; FaultWithTask(processingTask); } } } } // Check to see if all tasks have completed and if completion has been requested. CleanupStateIfCompletingAndQuiesced(); } else Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing count must be the sentinel if it's not >= 0."); } /// <summary> /// Processes exclusive tasks serially until either there are no more to process /// or we've reached our user-specified maximum limit. /// </summary> private void ProcessExclusiveTasks() { Contract.Requires(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "Processing exclusive tasks requires being in exclusive mode."); Contract.Requires(!m_exclusiveTaskScheduler.m_tasks.IsEmpty, "Processing exclusive tasks requires tasks to be processed."); ContractAssertMonitorStatus(ValueLock, held: false); try { // Note that we're processing exclusive tasks on the current thread Debug.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId), "This thread should not yet be involved in this pair's processing."); m_threadProcessingMapping[Thread.CurrentThread.ManagedThreadId] = ProcessingMode.ProcessingExclusiveTask; // Process up to the maximum number of items per task allowed for (int i = 0; i < m_maxItemsPerTask; i++) { // Get the next available exclusive task. If we can't find one, bail. Task exclusiveTask; if (!m_exclusiveTaskScheduler.m_tasks.TryDequeue(out exclusiveTask)) break; // Execute the task. If the scheduler was previously faulted, // this task could have been faulted when it was queued; ignore such tasks. if (!exclusiveTask.IsFaulted) m_exclusiveTaskScheduler.ExecuteTask(exclusiveTask); } } finally { // We're no longer processing exclusive tasks on the current thread ProcessingMode currentMode; m_threadProcessingMapping.TryRemove(Thread.CurrentThread.ManagedThreadId, out currentMode); Debug.Assert(currentMode == ProcessingMode.ProcessingExclusiveTask, "Somehow we ended up escaping exclusive mode."); lock (ValueLock) { // When this task was launched, we tracked it by setting m_processingCount to WRITER_IN_PROGRESS. // now reset it to 0. Then check to see whether there's more processing to be done. // There might be more concurrent tasks available, for example, if concurrent tasks arrived // after we exited the loop, or if we exited the loop while concurrent tasks were still // available but we hit our maxItemsPerTask limit. Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing mode should not have deviated from exclusive."); m_processingCount = 0; ProcessAsyncIfNecessary(true); } } } /// <summary> /// Processes concurrent tasks serially until either there are no more to process, /// we've reached our user-specified maximum limit, or exclusive tasks have arrived. /// </summary> private void ProcessConcurrentTasks() { Contract.Requires(m_processingCount > 0, "Processing concurrent tasks requires us to be in concurrent mode."); ContractAssertMonitorStatus(ValueLock, held: false); try { // Note that we're processing concurrent tasks on the current thread Debug.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId), "This thread should not yet be involved in this pair's processing."); m_threadProcessingMapping[Thread.CurrentThread.ManagedThreadId] = ProcessingMode.ProcessingConcurrentTasks; // Process up to the maximum number of items per task allowed for (int i = 0; i < m_maxItemsPerTask; i++) { // Get the next available concurrent task. If we can't find one, bail. Task concurrentTask; if (!m_concurrentTaskScheduler.m_tasks.TryDequeue(out concurrentTask)) break; // Execute the task. If the scheduler was previously faulted, // this task could have been faulted when it was queued; ignore such tasks. if (!concurrentTask.IsFaulted) m_concurrentTaskScheduler.ExecuteTask(concurrentTask); // Now check to see if exclusive tasks have arrived; if any have, they take priority // so we'll bail out here. Note that we could have checked this condition // in the for loop's condition, but that could lead to extra overhead // in the case where a concurrent task arrives, this task is launched, and then // before entering the loop an exclusive task arrives. If we didn't execute at // least one task, we would have spent all of the overhead to launch a // task but with none of the benefit. There's of course also an inherent // race condition here with regards to exclusive tasks arriving, and we're ok with // executing one more concurrent task than we should before giving priority to exclusive tasks. if (!m_exclusiveTaskScheduler.m_tasks.IsEmpty) break; } } finally { // We're no longer processing concurrent tasks on the current thread ProcessingMode currentMode; m_threadProcessingMapping.TryRemove(Thread.CurrentThread.ManagedThreadId, out currentMode); Debug.Assert(currentMode == ProcessingMode.ProcessingConcurrentTasks, "Somehow we ended up escaping concurrent mode."); lock (ValueLock) { // When this task was launched, we tracked it with a positive processing count; // decrement that count. Then check to see whether there's more processing to be done. // There might be more concurrent tasks available, for example, if concurrent tasks arrived // after we exited the loop, or if we exited the loop while concurrent tasks were still // available but we hit our maxItemsPerTask limit. Debug.Assert(m_processingCount > 0, "The procesing mode should not have deviated from concurrent."); if (m_processingCount > 0) --m_processingCount; ProcessAsyncIfNecessary(true); } } } #if PRENET45 /// <summary> /// Type used with TaskCompletionSource(Of TResult) as the TResult /// to ensure that the resulting task can't be upcast to something /// that in the future could lead to compat problems. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] [DebuggerNonUserCode] private struct VoidTaskResult { } #endif /// <summary> /// Holder for lazily-initialized state about the completion of a scheduler pair. /// Completion is only triggered either by rare exceptional conditions or by /// the user calling Complete, and as such we only lazily initialize this /// state in one of those conditions or if the user explicitly asks for /// the Completion. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] private sealed class CompletionState : TaskCompletionSource<VoidTaskResult> { /// <summary>Whether the scheduler has had completion requested.</summary> /// <remarks>This variable is not volatile, so to gurantee safe reading reads, Volatile.Read is used in TryExecuteTaskInline.</remarks> internal bool m_completionRequested; /// <summary>Whether completion processing has been queued.</summary> internal bool m_completionQueued; /// <summary>Unrecoverable exceptions incurred while processing.</summary> internal List<Exception> m_exceptions; } /// <summary> /// A scheduler shim used to queue tasks to the pair and execute those tasks on request of the pair. /// </summary> [DebuggerDisplay("Count={CountForDebugger}, MaxConcurrencyLevel={m_maxConcurrencyLevel}, Id={Id}")] [DebuggerTypeProxy(typeof(ConcurrentExclusiveTaskScheduler.DebugView))] private sealed class ConcurrentExclusiveTaskScheduler : TaskScheduler { /// <summary>Cached delegate for invoking TryExecuteTaskShim.</summary> private static readonly Func<object, bool> s_tryExecuteTaskShim = new Func<object, bool>(TryExecuteTaskShim); /// <summary>The parent pair.</summary> private readonly ConcurrentExclusiveSchedulerPair m_pair; /// <summary>The maximum concurrency level for the scheduler.</summary> private readonly int m_maxConcurrencyLevel; /// <summary>The processing mode of this scheduler, exclusive or concurrent.</summary> private readonly ProcessingMode m_processingMode; /// <summary>Gets the queue of tasks for this scheduler.</summary> internal readonly IProducerConsumerQueue<Task> m_tasks; /// <summary>Initializes the scheduler.</summary> /// <param name="pair">The parent pair.</param> /// <param name="maxConcurrencyLevel">The maximum degree of concurrency this scheduler may use.</param> /// <param name="processingMode">The processing mode of this scheduler.</param> internal ConcurrentExclusiveTaskScheduler(ConcurrentExclusiveSchedulerPair pair, int maxConcurrencyLevel, ProcessingMode processingMode) { Contract.Requires(pair != null, "Scheduler must be associated with a valid pair."); Contract.Requires(processingMode == ProcessingMode.ProcessingConcurrentTasks || processingMode == ProcessingMode.ProcessingExclusiveTask, "Scheduler must be for concurrent or exclusive processing."); Contract.Requires( (processingMode == ProcessingMode.ProcessingConcurrentTasks && (maxConcurrencyLevel >= 1 || maxConcurrencyLevel == UNLIMITED_PROCESSING)) || (processingMode == ProcessingMode.ProcessingExclusiveTask && maxConcurrencyLevel == 1), "If we're in concurrent mode, our concurrency level should be positive or unlimited. If exclusive, it should be 1."); m_pair = pair; m_maxConcurrencyLevel = maxConcurrencyLevel; m_processingMode = processingMode; m_tasks = (processingMode == ProcessingMode.ProcessingExclusiveTask) ? (IProducerConsumerQueue<Task>)new SingleProducerSingleConsumerQueue<Task>() : (IProducerConsumerQueue<Task>)new MultiProducerMultiConsumerQueue<Task>(); } /// <summary>Gets the maximum concurrency level this scheduler is able to support.</summary> public override int MaximumConcurrencyLevel { get { return m_maxConcurrencyLevel; } } /// <summary>Queues a task to the scheduler.</summary> /// <param name="task">The task to be queued.</param> protected internal override void QueueTask(Task task) { Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); lock (m_pair.ValueLock) { // If the scheduler has already had completion requested, no new work is allowed to be scheduled if (m_pair.CompletionRequested) throw new InvalidOperationException(GetType().Name); // Queue the task, and then let the pair know that more work is now available to be scheduled m_tasks.Enqueue(task); m_pair.ProcessAsyncIfNecessary(); } } /// <summary>Executes a task on this scheduler.</summary> /// <param name="task">The task to be executed.</param> internal void ExecuteTask(Task task) { Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); base.TryExecuteTask(task); } /// <summary>Tries to execute the task synchronously on this scheduler.</summary> /// <param name="task">The task to execute.</param> /// <param name="taskWasPreviouslyQueued">Whether the task was previously queued to the scheduler.</param> /// <returns>true if the task could be executed; otherwise, false.</returns> protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); // If the scheduler has had completion requested, no new work is allowed to be scheduled. // A non-locked read on m_completionRequested (in CompletionRequested) is acceptable here because: // a) we don't need to be exact... a Complete call could come in later in the function anyway // b) this is only a fast path escape hatch. To actually inline the task, // we need to be inside of an already executing task, and in such a case, // while completion may have been requested, we can't have shutdown yet. if (!taskWasPreviouslyQueued && m_pair.CompletionRequested) return false; // We know the implementation of the default scheduler and how it will behave. // As it's the most common underlying scheduler, we optimize for it. bool isDefaultScheduler = m_pair.m_underlyingTaskScheduler == TaskScheduler.Default; // If we're targeting the default scheduler and taskWasPreviouslyQueued is true, // we know that the default scheduler will only allow it to be inlined // if we're on a thread pool thread (but it won't always allow it in that case, // since it'll only allow inlining if it can find the task in the local queue). // As such, if we're not on a thread pool thread, we know for sure the // task won't be inlined, so let's not even try. if (isDefaultScheduler && taskWasPreviouslyQueued && !Thread.CurrentThread.IsThreadPoolThread) { return false; } else { // If a task is already running on this thread, allow inline execution to proceed. // If there's already a task from this scheduler running on the current thread, we know it's safe // to run this task, in effect temporarily taking that task's count allocation. ProcessingMode currentThreadMode; if (m_pair.m_threadProcessingMapping.TryGetValue(Thread.CurrentThread.ManagedThreadId, out currentThreadMode) && currentThreadMode == m_processingMode) { // If we're targeting the default scheduler and taskWasPreviouslyQueued is false, // we know the default scheduler will allow it, so we can just execute it here. // Otherwise, delegate to the target scheduler's inlining. return (isDefaultScheduler && !taskWasPreviouslyQueued) ? TryExecuteTask(task) : TryExecuteTaskInlineOnTargetScheduler(task); } } // We're not in the context of a task already executing on this scheduler. Bail. return false; } /// <summary> /// Implements a reasonable approximation for TryExecuteTaskInline on the underlying scheduler, /// which we can't call directly on the underlying scheduler. /// </summary> /// <param name="task">The task to execute inline if possible.</param> /// <returns>true if the task was inlined successfully; otherwise, false.</returns> [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "ignored")] private bool TryExecuteTaskInlineOnTargetScheduler(Task task) { // We'd like to simply call TryExecuteTaskInline here, but we can't. // As there's no built-in API for this, a workaround is to create a new task that, // when executed, will simply call TryExecuteTask to run the real task, and then // we run our new shim task synchronously on the target scheduler. If all goes well, // our synchronous invocation will succeed in running the shim task on the current thread, // which will in turn run the real task on the current thread. If the scheduler // doesn't allow that execution, RunSynchronously will block until the underlying scheduler // is able to invoke the task, which might account for an additional but unavoidable delay. // Once it's done, we can return whether the task executed by returning the // shim task's Result, which is in turn the result of TryExecuteTask. var t = new Task<bool>(s_tryExecuteTaskShim, Tuple.Create(this, task)); try { t.RunSynchronously(m_pair.m_underlyingTaskScheduler); return t.Result; } catch { Debug.Assert(t.IsFaulted, "Task should be faulted due to the scheduler faulting it and throwing the exception."); var ignored = t.Exception; throw; } finally { t.Dispose(); } } /// <summary>Shim used to invoke this.TryExecuteTask(task).</summary> /// <param name="state">A tuple of the ConcurrentExclusiveTaskScheduler and the task to execute.</param> /// <returns>true if the task was successfully inlined; otherwise, false.</returns> /// <remarks> /// This method is separated out not because of performance reasons but so that /// the SecuritySafeCritical attribute may be employed. /// </remarks> private static bool TryExecuteTaskShim(object state) { var tuple = (Tuple<ConcurrentExclusiveTaskScheduler, Task>)state; return tuple.Item1.TryExecuteTask(tuple.Item2); } /// <summary>Gets for debugging purposes the tasks scheduled to this scheduler.</summary> /// <returns>An enumerable of the tasks queued.</returns> protected override IEnumerable<Task> GetScheduledTasks() { return m_tasks; } /// <summary>Gets the number of tasks queued to this scheduler.</summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private int CountForDebugger { get { return m_tasks.Count; } } /// <summary>Provides a debug view for ConcurrentExclusiveTaskScheduler.</summary> private sealed class DebugView { /// <summary>The scheduler being debugged.</summary> private readonly ConcurrentExclusiveTaskScheduler m_taskScheduler; /// <summary>Initializes the debug view.</summary> /// <param name="scheduler">The scheduler being debugged.</param> public DebugView(ConcurrentExclusiveTaskScheduler scheduler) { Contract.Requires(scheduler != null, "Need a scheduler with which to construct the debug view."); m_taskScheduler = scheduler; } /// <summary>Gets this pair's maximum allowed concurrency level.</summary> public int MaximumConcurrencyLevel { get { return m_taskScheduler.m_maxConcurrencyLevel; } } /// <summary>Gets the tasks scheduled to this scheduler.</summary> public IEnumerable<Task> ScheduledTasks { get { return m_taskScheduler.m_tasks; } } /// <summary>Gets the scheduler pair with which this scheduler is associated.</summary> public ConcurrentExclusiveSchedulerPair SchedulerPair { get { return m_taskScheduler.m_pair; } } } } /// <summary>Provides a debug view for ConcurrentExclusiveSchedulerPair.</summary> private sealed class DebugView { /// <summary>The pair being debugged.</summary> private readonly ConcurrentExclusiveSchedulerPair m_pair; /// <summary>Initializes the debug view.</summary> /// <param name="pair">The pair being debugged.</param> public DebugView(ConcurrentExclusiveSchedulerPair pair) { Contract.Requires(pair != null, "Need a pair with which to construct the debug view."); m_pair = pair; } /// <summary>Gets a representation of the execution state of the pair.</summary> public ProcessingMode Mode { get { return m_pair.ModeForDebugger; } } /// <summary>Gets the number of tasks waiting to run exclusively.</summary> public IEnumerable<Task> ScheduledExclusive { get { return m_pair.m_exclusiveTaskScheduler.m_tasks; } } /// <summary>Gets the number of tasks waiting to run concurrently.</summary> public IEnumerable<Task> ScheduledConcurrent { get { return m_pair.m_concurrentTaskScheduler.m_tasks; } } /// <summary>Gets the number of tasks currently being executed.</summary> public int CurrentlyExecutingTaskCount { get { return (m_pair.m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL) ? 1 : m_pair.m_processingCount; } } /// <summary>Gets the underlying task scheduler that actually executes the tasks.</summary> public TaskScheduler TargetScheduler { get { return m_pair.m_underlyingTaskScheduler; } } } /// <summary>Gets an enumeration for debugging that represents the current state of the scheduler pair.</summary> /// <remarks>This is only for debugging. It does not take the necessary locks to be useful for runtime usage.</remarks> private ProcessingMode ModeForDebugger { get { // If our completion task is done, so are we. if (m_completionState != null && m_completionState.Task.IsCompleted) return ProcessingMode.Completed; // Otherwise, summarize our current state. var mode = ProcessingMode.NotCurrentlyProcessing; if (m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL) mode |= ProcessingMode.ProcessingExclusiveTask; if (m_processingCount >= 1) mode |= ProcessingMode.ProcessingConcurrentTasks; if (CompletionRequested) mode |= ProcessingMode.Completing; return mode; } } /// <summary>Asserts that a given synchronization object is either held or not held.</summary> /// <param name="syncObj">The monitor to check.</param> /// <param name="held">Whether we want to assert that it's currently held or not held.</param> [Conditional("DEBUG")] internal static void ContractAssertMonitorStatus(object syncObj, bool held) { Contract.Requires(syncObj != null, "The monitor object to check must be provided."); #if PRENET45 #if DEBUG // This check is expensive, // which is why it's protected by ShouldCheckMonitorStatus and controlled by an environment variable DEBUGSYNC. if (ShouldCheckMonitorStatus) { bool exceptionThrown; try { Monitor.Pulse(syncObj); // throws a SynchronizationLockException if the monitor isn't held by this thread exceptionThrown = false; } catch (SynchronizationLockException) { exceptionThrown = true; } Debug.Assert(held == !exceptionThrown, "The locking scheme was not correctly followed."); } #endif #else Debug.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed."); #endif } /// <summary>Gets the options to use for tasks.</summary> /// <param name="isReplacementReplica">If this task is being created to replace another.</param> /// <remarks> /// These options should be used for all tasks that have the potential to run user code or /// that are repeatedly spawned and thus need a modicum of fair treatment. /// </remarks> /// <returns>The options to use.</returns> internal static TaskCreationOptions GetCreationOptionsForTask(bool isReplacementReplica = false) { TaskCreationOptions options = #if PRENET45 TaskCreationOptions.None; #else TaskCreationOptions.DenyChildAttach; #endif if (isReplacementReplica) options |= TaskCreationOptions.PreferFairness; return options; } /// <summary>Provides an enumeration that represents the current state of the scheduler pair.</summary> [Flags] private enum ProcessingMode : byte { /// <summary>The scheduler pair is currently dormant, with no work scheduled.</summary> NotCurrentlyProcessing = 0x0, /// <summary>The scheduler pair has queued processing for exclusive tasks.</summary> ProcessingExclusiveTask = 0x1, /// <summary>The scheduler pair has queued processing for concurrent tasks.</summary> ProcessingConcurrentTasks = 0x2, /// <summary>Completion has been requested.</summary> Completing = 0x4, /// <summary>The scheduler pair is finished processing.</summary> Completed = 0x8 } } }
using System.Diagnostics; using System.Text; using HANDLE = System.IntPtr; using i64 = System.Int64; using u32 = System.UInt32; using sqlite3_int64 = System.Int64; namespace System.Data.SQLite { public partial class Sqlite3 { /* ** 2005 November 29 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains OS interface code that is common to all ** architectures. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-12-07 20:14:09 a586a4deeb25330037a49df295b36aaf624d0f45 ** ************************************************************************* */ //#define _SQLITE_OS_C_ 1 //#include "sqliteInt.h" //#undef _SQLITE_OS_C_ /* ** The default SQLite sqlite3_vfs implementations do not allocate ** memory (actually, os_unix.c allocates a small amount of memory ** from within OsOpen()), but some third-party implementations may. ** So we test the effects of a malloc() failing and the sqlite3OsXXX() ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro. ** ** The following functions are instrumented for malloc() failure ** testing: ** ** sqlite3OsOpen() ** sqlite3OsRead() ** sqlite3OsWrite() ** sqlite3OsSync() ** sqlite3OsLock() ** */ #if (SQLITE_TEST) static int sqlite3_memdebug_vfs_oom_test = 1; //#define DO_OS_MALLOC_TEST(x) \ //if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \ // void *pTstAlloc = sqlite3Malloc(10); \ // if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \ // sqlite3_free(pTstAlloc); \ //} static void DO_OS_MALLOC_TEST( sqlite3_file x ) { } #else //#define DO_OS_MALLOC_TEST(x) static void DO_OS_MALLOC_TEST(sqlite3_file x) { } #endif /* ** The following routines are convenience wrappers around methods ** of the sqlite3_file object. This is mostly just syntactic sugar. All ** of this would be completely automatic if SQLite were coded using ** C++ instead of plain old C. */ static int sqlite3OsClose(sqlite3_file pId) { int rc = SQLITE_OK; if (pId.pMethods != null) { rc = pId.pMethods.xClose(pId); pId.pMethods = null; } return rc; } static int sqlite3OsRead(sqlite3_file id, byte[] pBuf, int amt, i64 offset) { DO_OS_MALLOC_TEST(id); if (pBuf == null) pBuf = sqlite3Malloc(amt); return id.pMethods.xRead(id, pBuf, amt, offset); } static int sqlite3OsWrite(sqlite3_file id, byte[] pBuf, int amt, i64 offset) { DO_OS_MALLOC_TEST(id); return id.pMethods.xWrite(id, pBuf, amt, offset); } static int sqlite3OsTruncate(sqlite3_file id, i64 size) { return id.pMethods.xTruncate(id, size); } static int sqlite3OsSync(sqlite3_file id, int flags) { DO_OS_MALLOC_TEST(id); return id.pMethods.xSync(id, flags); } static int sqlite3OsFileSize(sqlite3_file id, ref long pSize) { return id.pMethods.xFileSize(id, ref pSize); } static int sqlite3OsLock(sqlite3_file id, int lockType) { DO_OS_MALLOC_TEST(id); return id.pMethods.xLock(id, lockType); } static int sqlite3OsUnlock(sqlite3_file id, int lockType) { return id.pMethods.xUnlock(id, lockType); } static int sqlite3OsCheckReservedLock(sqlite3_file id, ref int pResOut) { DO_OS_MALLOC_TEST(id); return id.pMethods.xCheckReservedLock(id, ref pResOut); } static int sqlite3OsFileControl(sqlite3_file id, u32 op, ref sqlite3_int64 pArg) { return id.pMethods.xFileControl(id, (int)op, ref pArg); } static int sqlite3OsSectorSize(sqlite3_file id) { dxSectorSize xSectorSize = id.pMethods.xSectorSize; return (xSectorSize != null ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE); } static int sqlite3OsDeviceCharacteristics(sqlite3_file id) { return id.pMethods.xDeviceCharacteristics(id); } static int sqlite3OsShmLock(sqlite3_file id, int offset, int n, int flags) { return id.pMethods.xShmLock(id, offset, n, flags); } static void sqlite3OsShmBarrier(sqlite3_file id) { id.pMethods.xShmBarrier(id); } static int sqlite3OsShmUnmap(sqlite3_file id, int deleteFlag) { return id.pMethods.xShmUnmap(id, deleteFlag); } static int sqlite3OsShmMap( sqlite3_file id, /* Database file handle */ int iPage, int pgsz, int bExtend, /* True to extend file if necessary */ out object pp /* OUT: Pointer to mapping */ ) { return id.pMethods.xShmMap(id, iPage, pgsz, bExtend, out pp); } /* ** The next group of routines are convenience wrappers around the ** VFS methods. */ static int sqlite3OsOpen( sqlite3_vfs pVfs, string zPath, sqlite3_file pFile, int flags, ref int pFlagsOut ) { int rc; DO_OS_MALLOC_TEST(null); /* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example, ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before ** reaching the VFS. */ rc = pVfs.xOpen(pVfs, zPath, pFile, flags & 0x87f3f, out pFlagsOut); Debug.Assert(rc == SQLITE_OK || pFile.pMethods == null); return rc; } static int sqlite3OsDelete(sqlite3_vfs pVfs, string zPath, int dirSync) { return pVfs.xDelete(pVfs, zPath, dirSync); } static int sqlite3OsAccess(sqlite3_vfs pVfs, string zPath, int flags, ref int pResOut) { DO_OS_MALLOC_TEST(null); return pVfs.xAccess(pVfs, zPath, flags, out pResOut); } static int sqlite3OsFullPathname( sqlite3_vfs pVfs, string zPath, int nPathOut, StringBuilder zPathOut ) { zPathOut.Length = 0;//zPathOut[0] = 0; return pVfs.xFullPathname(pVfs, zPath, nPathOut, zPathOut); } #if !SQLITE_OMIT_LOAD_EXTENSION static HANDLE sqlite3OsDlOpen(sqlite3_vfs pVfs, string zPath) { return pVfs.xDlOpen(pVfs, zPath); } static void sqlite3OsDlError(sqlite3_vfs pVfs, int nByte, string zBufOut) { pVfs.xDlError(pVfs, nByte, zBufOut); } static object sqlite3OsDlSym(sqlite3_vfs pVfs, HANDLE pHdle, ref string zSym) { return pVfs.xDlSym(pVfs, pHdle, zSym); } static void sqlite3OsDlClose(sqlite3_vfs pVfs, HANDLE pHandle) { pVfs.xDlClose(pVfs, pHandle); } #endif static int sqlite3OsRandomness(sqlite3_vfs pVfs, int nByte, byte[] zBufOut) { return pVfs.xRandomness(pVfs, nByte, zBufOut); } static int sqlite3OsSleep(sqlite3_vfs pVfs, int nMicro) { return pVfs.xSleep(pVfs, nMicro); } static int sqlite3OsCurrentTimeInt64(sqlite3_vfs pVfs, ref sqlite3_int64 pTimeOut) { int rc; /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64() ** method to get the current date and time if that method is available ** (if iVersion is 2 or greater and the function pointer is not NULL) and ** will fall back to xCurrentTime() if xCurrentTimeInt64() is ** unavailable. */ if (pVfs.iVersion >= 2 && pVfs.xCurrentTimeInt64 != null) { rc = pVfs.xCurrentTimeInt64(pVfs, ref pTimeOut); } else { double r = 0; rc = pVfs.xCurrentTime(pVfs, ref r); pTimeOut = (sqlite3_int64)(r * 86400000.0); } return rc; } static int sqlite3OsOpenMalloc( ref sqlite3_vfs pVfs, string zFile, ref sqlite3_file ppFile, int flags, ref int pOutFlags ) { int rc = SQLITE_NOMEM; sqlite3_file pFile; pFile = new sqlite3_file(); //sqlite3Malloc(ref pVfs.szOsFile); if (pFile != null) { rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, ref pOutFlags); if (rc != SQLITE_OK) { pFile = null; // was sqlite3DbFree(db,ref pFile); } else { ppFile = pFile; } } return rc; } static int sqlite3OsCloseFree(sqlite3_file pFile) { int rc = SQLITE_OK; Debug.Assert(pFile != null); rc = sqlite3OsClose(pFile); //sqlite3_free( ref pFile ); return rc; } /* ** This function is a wrapper around the OS specific implementation of ** sqlite3_os_init(). The purpose of the wrapper is to provide the ** ability to simulate a malloc failure, so that the handling of an ** error in sqlite3_os_init() by the upper layers can be tested. */ static int sqlite3OsInit() { //void *p = sqlite3_malloc(10); //if( p==null ) return SQLITE_NOMEM; //sqlite3_free(ref p); return sqlite3_os_init(); } /* ** The list of all registered VFS implementations. */ static sqlite3_vfs vfsList; //#define vfsList GLOBAL(sqlite3_vfs *, vfsList) /* ** Locate a VFS by name. If no name is given, simply return the ** first VFS on the list. */ static bool isInit = false; static sqlite3_vfs sqlite3_vfs_find(string zVfs) { sqlite3_vfs pVfs = null; #if SQLITE_THREADSAFE sqlite3_mutex mutex; #endif #if !SQLITE_OMIT_AUTOINIT int rc = sqlite3_initialize(); if (rc != 0) return null; #endif #if SQLITE_THREADSAFE mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #endif sqlite3_mutex_enter(mutex); for (pVfs = vfsList; pVfs != null; pVfs = pVfs.pNext) { if (zVfs == null || zVfs == "") break; if (zVfs == pVfs.zName) break; //strcmp(zVfs, pVfs.zName) == null) break; } sqlite3_mutex_leave(mutex); return pVfs; } /* ** Unlink a VFS from the linked list */ static void vfsUnlink(sqlite3_vfs pVfs) { Debug.Assert(sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER))); if (pVfs == null) { /* No-op */ } else if (vfsList == pVfs) { vfsList = pVfs.pNext; } else if (vfsList != null) { sqlite3_vfs p = vfsList; while (p.pNext != null && p.pNext != pVfs) { p = p.pNext; } if (p.pNext == pVfs) { p.pNext = pVfs.pNext; } } } /* ** Register a VFS with the system. It is harmless to register the same ** VFS multiple times. The new VFS becomes the default if makeDflt is ** true. */ static int sqlite3_vfs_register(sqlite3_vfs pVfs, int makeDflt) { sqlite3_mutex mutex; #if !SQLITE_OMIT_AUTOINIT int rc = sqlite3_initialize(); if (rc != 0) return rc; #endif mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); sqlite3_mutex_enter(mutex); vfsUnlink(pVfs); if (makeDflt != 0 || vfsList == null) { pVfs.pNext = vfsList; vfsList = pVfs; } else { pVfs.pNext = vfsList.pNext; vfsList.pNext = pVfs; } Debug.Assert(vfsList != null); sqlite3_mutex_leave(mutex); return SQLITE_OK; } /* ** Unregister a VFS so that it is no longer accessible. */ static int sqlite3_vfs_unregister(sqlite3_vfs pVfs) { #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #endif sqlite3_mutex_enter(mutex); vfsUnlink(pVfs); sqlite3_mutex_leave(mutex); return SQLITE_OK; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Collections.Specialized { [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct BitVector32 { public BitVector32(System.Collections.Specialized.BitVector32 value) { throw null;} public BitVector32(int data) { throw null;} public int Data { get { throw null; } } public int this[System.Collections.Specialized.BitVector32.Section section] { get { throw null; } set { } } public bool this[int bit] { get { throw null; } set { } } public static int CreateMask() { throw null; } public static int CreateMask(int previous) { throw null; } public static System.Collections.Specialized.BitVector32.Section CreateSection(short maxValue) { throw null; } public static System.Collections.Specialized.BitVector32.Section CreateSection(short maxValue, System.Collections.Specialized.BitVector32.Section previous) { throw null; } public override bool Equals(object o) { throw null; } public override int GetHashCode() { throw null; } public override string ToString() { throw null; } public static string ToString(System.Collections.Specialized.BitVector32 value) { throw null; } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Section { public short Mask { get { throw null; } } public short Offset { get { throw null; } } public bool Equals(System.Collections.Specialized.BitVector32.Section obj) { throw null; } public override bool Equals(object o) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Collections.Specialized.BitVector32.Section a, System.Collections.Specialized.BitVector32.Section b) { throw null; } public static bool operator !=(System.Collections.Specialized.BitVector32.Section a, System.Collections.Specialized.BitVector32.Section b) { throw null; } public override string ToString() { throw null; } public static string ToString(System.Collections.Specialized.BitVector32.Section value) { throw null; } } } public partial class CollectionsUtil { public CollectionsUtil() { } public static System.Collections.Hashtable CreateCaseInsensitiveHashtable() { throw null; } public static System.Collections.Hashtable CreateCaseInsensitiveHashtable(System.Collections.IDictionary d) { throw null; } public static System.Collections.Hashtable CreateCaseInsensitiveHashtable(int capacity) { throw null; } public static System.Collections.SortedList CreateCaseInsensitiveSortedList() { throw null; } } public partial class HybridDictionary : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { public HybridDictionary() { } public HybridDictionary(bool caseInsensitive) { } public HybridDictionary(int initialSize) { } public HybridDictionary(int initialSize, bool caseInsensitive) { } public int Count { get { throw null; } } public bool IsFixedSize { get { throw null; } } public bool IsReadOnly { get { throw null; } } public bool IsSynchronized { get { throw null; } } public object this[object key] { get { throw null; } set { } } public System.Collections.ICollection Keys { get { throw null; } } public object SyncRoot { get { throw null; } } public System.Collections.ICollection Values { get { throw null; } } public void Add(object key, object value) { } public void Clear() { } public bool Contains(object key) { throw null; } public void CopyTo(System.Array array, int index) { } public System.Collections.IDictionaryEnumerator GetEnumerator() { throw null; } public void Remove(object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public partial interface INotifyCollectionChanged { event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged; } public partial interface IOrderedDictionary : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { object this[int index] { get; set; } new System.Collections.IDictionaryEnumerator GetEnumerator(); void Insert(int index, object key, object value); void RemoveAt(int index); } public partial class ListDictionary : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { public ListDictionary() { } public ListDictionary(System.Collections.IComparer comparer) { } public int Count { get { throw null; } } public bool IsFixedSize { get { throw null; } } public bool IsReadOnly { get { throw null; } } public bool IsSynchronized { get { throw null; } } public object this[object key] { get { throw null; } set { } } public System.Collections.ICollection Keys { get { throw null; } } public object SyncRoot { get { throw null; } } public System.Collections.ICollection Values { get { throw null; } } public void Add(object key, object value) { } public void Clear() { } public bool Contains(object key) { throw null; } public void CopyTo(System.Array array, int index) { } public System.Collections.IDictionaryEnumerator GetEnumerator() { throw null; } public void Remove(object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public abstract partial class NameObjectCollectionBase : System.Collections.ICollection, System.Collections.IEnumerable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable { protected NameObjectCollectionBase() { } protected NameObjectCollectionBase(System.Collections.IEqualityComparer equalityComparer) { } [System.ObsoleteAttribute("Please use NameObjectCollectionBase(IEqualityComparer) instead.")] protected NameObjectCollectionBase(System.Collections.IHashCodeProvider hashProvider, System.Collections.IComparer comparer) { } protected NameObjectCollectionBase(int capacity) { } protected NameObjectCollectionBase(int capacity, System.Collections.IEqualityComparer equalityComparer) { } [System.ObsoleteAttribute("Please use NameObjectCollectionBase(Int32, IEqualityComparer) instead.")] protected NameObjectCollectionBase(int capacity, System.Collections.IHashCodeProvider hashProvider, System.Collections.IComparer comparer) { } protected NameObjectCollectionBase(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual int Count { get { throw null; } } protected bool IsReadOnly { get { throw null; } set { } } public virtual System.Collections.Specialized.NameObjectCollectionBase.KeysCollection Keys { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } protected void BaseAdd(string name, object value) { } protected void BaseClear() { } protected object BaseGet(int index) { throw null; } protected object BaseGet(string name) { throw null; } protected string[] BaseGetAllKeys() { throw null; } protected object[] BaseGetAllValues() { throw null; } protected object[] BaseGetAllValues(System.Type type) { throw null; } protected string BaseGetKey(int index) { throw null; } protected bool BaseHasKeys() { throw null; } protected void BaseRemove(string name) { } protected void BaseRemoveAt(int index) { } protected void BaseSet(int index, object value) { } protected void BaseSet(string name, object value) { } public virtual System.Collections.IEnumerator GetEnumerator() { throw null; } public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual void OnDeserialization(object sender) { } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } public partial class KeysCollection : System.Collections.ICollection, System.Collections.IEnumerable { internal KeysCollection() { } public int Count { get { throw null; } } public string this[int index] { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public virtual string Get(int index) { throw null; } public System.Collections.IEnumerator GetEnumerator() { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } } } public partial class NameValueCollection : System.Collections.Specialized.NameObjectCollectionBase { public NameValueCollection() { } public NameValueCollection(System.Collections.IEqualityComparer equalityComparer) { } [System.ObsoleteAttribute("Please use NameValueCollection(IEqualityComparer) instead.")] public NameValueCollection(System.Collections.IHashCodeProvider hashProvider, System.Collections.IComparer comparer) { } public NameValueCollection(System.Collections.Specialized.NameValueCollection col) { } public NameValueCollection(int capacity) { } public NameValueCollection(int capacity, System.Collections.IEqualityComparer equalityComparer) { } [System.ObsoleteAttribute("Please use NameValueCollection(Int32, IEqualityComparer) instead.")] public NameValueCollection(int capacity, System.Collections.IHashCodeProvider hashProvider, System.Collections.IComparer comparer) { } public NameValueCollection(int capacity, System.Collections.Specialized.NameValueCollection col) { } protected NameValueCollection(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual string[] AllKeys { get { throw null; } } public string this[int index] { get { throw null; } } public string this[string name] { get { throw null; } set { } } public void Add(System.Collections.Specialized.NameValueCollection c) { } public virtual void Add(string name, string value) { } public virtual void Clear() { } public void CopyTo(System.Array dest, int index) { } public virtual string Get(int index) { throw null; } public virtual string Get(string name) { throw null; } public virtual string GetKey(int index) { throw null; } public virtual string[] GetValues(int index) { throw null; } public virtual string[] GetValues(string name) { throw null; } public bool HasKeys() { throw null; } protected void InvalidateCachedArrays() { } public virtual void Remove(string name) { } public virtual void Set(string name, string value) { } } public enum NotifyCollectionChangedAction { Add = 0, Move = 3, Remove = 1, Replace = 2, Reset = 4, } public partial class NotifyCollectionChangedEventArgs : System.EventArgs { public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList changedItems) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList newItems, System.Collections.IList oldItems) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList newItems, System.Collections.IList oldItems, int startingIndex) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList changedItems, int startingIndex) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList changedItems, int index, int oldIndex) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object changedItem) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object changedItem, int index) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object changedItem, int index, int oldIndex) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object newItem, object oldItem) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object newItem, object oldItem, int index) { } public System.Collections.Specialized.NotifyCollectionChangedAction Action { get { throw null; } } public System.Collections.IList NewItems { get { throw null; } } public int NewStartingIndex { get { throw null; } } public System.Collections.IList OldItems { get { throw null; } } public int OldStartingIndex { get { throw null; } } } public delegate void NotifyCollectionChangedEventHandler(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e); public partial class OrderedDictionary : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable, System.Collections.Specialized.IOrderedDictionary, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable { public OrderedDictionary() { } public OrderedDictionary(System.Collections.IEqualityComparer comparer) { } public OrderedDictionary(int capacity) { } public OrderedDictionary(int capacity, System.Collections.IEqualityComparer comparer) { } protected OrderedDictionary(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public int Count { get { throw null; } } public bool IsReadOnly { get { throw null; } } public object this[int index] { get { throw null; } set { } } public object this[object key] { get { throw null; } set { } } public System.Collections.ICollection Keys { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } bool System.Collections.IDictionary.IsFixedSize { get { throw null; } } public System.Collections.ICollection Values { get { throw null; } } public void Add(object key, object value) { } public System.Collections.Specialized.OrderedDictionary AsReadOnly() { throw null; } public void Clear() { } public bool Contains(object key) { throw null; } public void CopyTo(System.Array array, int index) { } public virtual System.Collections.IDictionaryEnumerator GetEnumerator() { throw null; } public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public void Insert(int index, object key, object value) { } protected virtual void OnDeserialization(object sender) { } public void Remove(object key) { } public void RemoveAt(int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(object sender) { } } public partial class StringCollection : System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList { public StringCollection() { } public int Count { get { throw null; } } public bool IsReadOnly { get { throw null; } } public bool IsSynchronized { get { throw null; } } public string this[int index] { get { throw null; } set { } } public object SyncRoot { get { throw null; } } bool System.Collections.IList.IsFixedSize { get { throw null; } } bool System.Collections.IList.IsReadOnly { get { throw null; } } object System.Collections.IList.this[int index] { get { throw null; } set { } } public int Add(string value) { throw null; } public void AddRange(string[] value) { } public void Clear() { } public bool Contains(string value) { throw null; } public void CopyTo(string[] array, int index) { } public System.Collections.Specialized.StringEnumerator GetEnumerator() { throw null; } public int IndexOf(string value) { throw null; } public void Insert(int index, string value) { } public void Remove(string value) { } public void RemoveAt(int index) { } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } int System.Collections.IList.Add(object value) { throw null; } bool System.Collections.IList.Contains(object value) { throw null; } int System.Collections.IList.IndexOf(object value) { throw null; } void System.Collections.IList.Insert(int index, object value) { } void System.Collections.IList.Remove(object value) { } } public partial class StringDictionary : System.Collections.IEnumerable { public StringDictionary() { } public virtual int Count { get { throw null; } } public virtual bool IsSynchronized { get { throw null; } } public virtual string this[string key] { get { throw null; } set { } } public virtual System.Collections.ICollection Keys { get { throw null; } } public virtual object SyncRoot { get { throw null; } } public virtual System.Collections.ICollection Values { get { throw null; } } public virtual void Add(string key, string value) { } public virtual void Clear() { } public virtual bool ContainsKey(string key) { throw null; } public virtual bool ContainsValue(string value) { throw null; } public virtual void CopyTo(System.Array array, int index) { } public virtual System.Collections.IEnumerator GetEnumerator() { throw null; } public virtual void Remove(string key) { } } public partial class StringEnumerator { internal StringEnumerator() { } public string Current { get { throw null; } } public bool MoveNext() { throw null; } public void Reset() { } } }
/* New BSD License ------------------------------------------------------------------------------- Copyright (c) 2006-2012, EntitySpaces, LLC All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the EntitySpaces, LLC 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 EntitySpaces, LLC 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.Data; using System.Collections.Generic; using iAnywhere.Data.SQLAnywhere; using Tiraggo.Interfaces; using Tiraggo.DynamicQuery; using System.Threading; using System.Diagnostics; namespace Tiraggo.SybaseSqlAnywhereProvider { public class DataProvider : IDataProvider { public DataProvider() { } #region esTraceArguments private sealed class esTraceArguments : Tiraggo.Interfaces.ITraceArguments, IDisposable { static private long packetOrder = 0; private sealed class esTraceParameter : ITraceParameter { public string Name { get; set; } public string Direction { get; set; } public string ParamType { get; set; } public string BeforeValue { get; set; } public string AfterValue { get; set; } } public esTraceArguments() { } public esTraceArguments(tgDataRequest request, IDbCommand cmd, tgEntitySavePacket packet, string action, string callStack) { PacketOrder = Interlocked.Increment(ref esTraceArguments.packetOrder); this.command = cmd; TraceChannel = DataProvider.sTraceChannel; Syntax = "SYBASE"; Request = request; ThreadId = Thread.CurrentThread.ManagedThreadId; Action = action; CallStack = callStack; SqlCommand = cmd; ApplicationName = System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location); IDataParameterCollection parameters = cmd.Parameters; if (parameters.Count > 0) { Parameters = new List<ITraceParameter>(parameters.Count); for (int i = 0; i < parameters.Count; i++) { SAParameter param = parameters[i] as SAParameter; esTraceParameter p = new esTraceParameter() { Name = param.ParameterName, Direction = param.Direction.ToString(), ParamType = param.SADbType.ToString().ToUpper(), BeforeValue = param.Value != null && param.Value != DBNull.Value ? Convert.ToString(param.Value) : "null" }; try { // Let's make it look like we're using parameters for the profiler if (param.Value == null || param.Value == DBNull.Value) { if (param.SourceVersion == DataRowVersion.Current) { object o = packet.CurrentValues[param.SourceColumn]; if (o != null && o != DBNull.Value) { p.BeforeValue = Convert.ToString(o); } } else if (param.SourceVersion == DataRowVersion.Original) { object o = packet.OriginalValues[param.SourceColumn]; if (o != null && o != DBNull.Value) { p.BeforeValue = Convert.ToString(o); } } } } catch { } this.Parameters.Add(p); } } stopwatch = Stopwatch.StartNew(); } public esTraceArguments(tgDataRequest request, IDbCommand cmd, string action, string callStack) { PacketOrder = Interlocked.Increment(ref esTraceArguments.packetOrder); this.command = cmd; TraceChannel = DataProvider.sTraceChannel; Syntax = "SYBASE"; Request = request; ThreadId = Thread.CurrentThread.ManagedThreadId; Action = action; CallStack = callStack; SqlCommand = cmd; ApplicationName = System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location); IDataParameterCollection parameters = cmd.Parameters; if (parameters.Count > 0) { Parameters = new List<ITraceParameter>(parameters.Count); for (int i = 0; i < parameters.Count; i++) { SAParameter param = parameters[i] as SAParameter; esTraceParameter p = new esTraceParameter() { Name = param.ParameterName, Direction = param.Direction.ToString(), ParamType = param.SADbType.ToString().ToUpper(), BeforeValue = param.Value != null && param.Value != DBNull.Value ? Convert.ToString(param.Value) : "null" }; this.Parameters.Add(p); } } stopwatch = Stopwatch.StartNew(); } // Temporary variable private IDbCommand command; public long PacketOrder { get; set; } public string Syntax { get; set; } public tgDataRequest Request { get; set; } public int ThreadId { get; set; } public string Action { get; set; } public string CallStack { get; set; } public IDbCommand SqlCommand { get; set; } public string ApplicationName { get; set; } public string TraceChannel { get; set; } public long Duration { get; set; } public long Ticks { get; set; } public string Exception { get; set; } public List<ITraceParameter> Parameters { get; set; } private Stopwatch stopwatch; void IDisposable.Dispose() { stopwatch.Stop(); Duration = stopwatch.ElapsedMilliseconds; Ticks = stopwatch.ElapsedTicks; // Gather Output Parameters if (this.Parameters != null && this.Parameters.Count > 0) { IDataParameterCollection parameters = command.Parameters; for (int i = 0; i < this.Parameters.Count; i++) { ITraceParameter esParam = this.Parameters[i]; IDbDataParameter param = parameters[esParam.Name] as IDbDataParameter; if (param.Direction == ParameterDirection.InputOutput || param.Direction == ParameterDirection.Output) { esParam.AfterValue = param.Value != null ? Convert.ToString(param.Value) : "null"; } } } DataProvider.sTraceHandler(this); } } #endregion esTraceArguments #region Profiling Logic /// <summary> /// The EventHandler used to decouple the profiling code from the core assemblies /// </summary> event TraceEventHandler IDataProvider.TraceHandler { add { DataProvider.sTraceHandler += value; } remove { DataProvider.sTraceHandler -= value; } } static private event TraceEventHandler sTraceHandler; /// <summary> /// Returns true if this Provider is current being profiled /// </summary> bool IDataProvider.IsTracing { get { return sTraceHandler != null ? true : false; } } /// <summary> /// Used to set the Channel this provider is to use during Profiling /// </summary> string IDataProvider.TraceChannel { get { return DataProvider.sTraceChannel; } set { DataProvider.sTraceChannel = value; } } static private string sTraceChannel = "Channel1"; #endregion Profiling Logic /// <summary> /// This method acts as a delegate for tgTransactionScope /// </summary> /// <returns></returns> static private IDbConnection CreateIDbConnectionDelegate() { return new SAConnection(); } static private void CleanupCommand(SACommand cmd) { if (cmd != null && cmd.Connection != null) { if (cmd.Connection.State == ConnectionState.Open) { cmd.Connection.Close(); } } } #region IDataProvider Members tgDataResponse IDataProvider.esLoadDataTable(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); try { switch (request.QueryType) { case tgQueryType.StoredProcedure: response = LoadDataTableFromStoredProcedure(request); break; case tgQueryType.Text: response = LoadDataTableFromText(request); break; case tgQueryType.DynamicQuery: response = new tgDataResponse(); SACommand cmd = QueryBuilder.PrepareCommand(request); LoadDataTableFromDynamicQuery(request, response, cmd); break; case tgQueryType.DynamicQueryParseOnly: response = new tgDataResponse(); SACommand cmd1 = QueryBuilder.PrepareCommand(request); response.LastQuery = cmd1.CommandText; break; case tgQueryType.ManyToMany: response = LoadManyToMany(request); break; default: break; } } catch (Exception ex) { response.Exception = ex; } return response; } tgDataResponse IDataProvider.esSaveDataTable(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); try { if (request.SqlAccessType == tgSqlAccessType.StoredProcedure) { if (request.CollectionSavePacket != null) SaveStoredProcCollection(request); else SaveStoredProcEntity(request); } else { if (request.EntitySavePacket.CurrentValues == null) SaveDynamicCollection(request); else SaveDynamicEntity(request); } } catch (SAException ex) { tgException es = Shared.CheckForConcurrencyException(ex); if (es != null) response.Exception = es; else response.Exception = ex; } catch (DBConcurrencyException dbex) { response.Exception = new tgConcurrencyException("Error in SybaseSqlAnywhereProvider.esSaveDataTable", dbex); } response.Table = request.Table; return response; } tgDataResponse IDataProvider.ExecuteNonQuery(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); SACommand cmd = null; try { cmd = new SACommand(); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; if (request.Parameters != null) Shared.AddParameters(cmd, request); switch (request.QueryType) { case tgQueryType.TableDirect: cmd.CommandType = CommandType.TableDirect; cmd.CommandText = request.QueryText; break; case tgQueryType.StoredProcedure: cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = Shared.CreateFullName(request); break; case tgQueryType.Text: cmd.CommandType = CommandType.Text; cmd.CommandText = request.QueryText; break; } try { tgTransactionScope.Enlist(cmd, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "ExecuteNonQuery", System.Environment.StackTrace)) { try { response.RowsEffected = cmd.ExecuteNonQuery(); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { response.RowsEffected = cmd.ExecuteNonQuery(); } } finally { tgTransactionScope.DeEnlist(cmd); } if (request.Parameters != null) { Shared.GatherReturnParameters(cmd, request, response); } } catch (Exception ex) { CleanupCommand(cmd); response.Exception = ex; } return response; } tgDataResponse IDataProvider.ExecuteReader(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); SACommand cmd = null; try { cmd = new SACommand(); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; if (request.Parameters != null) Shared.AddParameters(cmd, request); switch (request.QueryType) { case tgQueryType.TableDirect: cmd.CommandType = CommandType.TableDirect; cmd.CommandText = request.QueryText; break; case tgQueryType.StoredProcedure: cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = Shared.CreateFullName(request); break; case tgQueryType.Text: cmd.CommandType = CommandType.Text; cmd.CommandText = request.QueryText; break; case tgQueryType.DynamicQuery: cmd = QueryBuilder.PrepareCommand(request); break; } cmd.Connection = new SAConnection(request.ConnectionString); cmd.Connection.Open(); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "ExecuteReader", System.Environment.StackTrace)) { try { response.DataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { response.DataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); } } catch (Exception ex) { CleanupCommand(cmd); response.Exception = ex; } return response; } tgDataResponse IDataProvider.ExecuteScalar(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); SACommand cmd = null; try { cmd = new SACommand(); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; if (request.Parameters != null) Shared.AddParameters(cmd, request); switch (request.QueryType) { case tgQueryType.TableDirect: cmd.CommandType = CommandType.TableDirect; cmd.CommandText = request.QueryText; break; case tgQueryType.StoredProcedure: cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = Shared.CreateFullName(request); break; case tgQueryType.Text: cmd.CommandType = CommandType.Text; cmd.CommandText = request.QueryText; break; case tgQueryType.DynamicQuery: cmd = QueryBuilder.PrepareCommand(request); break; } try { tgTransactionScope.Enlist(cmd, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "ExecuteScalar", System.Environment.StackTrace)) { try { response.Scalar = cmd.ExecuteScalar(); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { response.Scalar = cmd.ExecuteScalar(); } } finally { tgTransactionScope.DeEnlist(cmd); } if (request.Parameters != null) { Shared.GatherReturnParameters(cmd, request, response); } } catch (Exception ex) { CleanupCommand(cmd); response.Exception = ex; } return response; } tgDataResponse IDataProvider.FillDataSet(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); try { switch (request.QueryType) { case tgQueryType.StoredProcedure: response = LoadDataSetFromStoredProcedure(request); break; case tgQueryType.Text: response = LoadDataSetFromText(request); break; default: break; } } catch (Exception ex) { response.Exception = ex; } return response; } tgDataResponse IDataProvider.FillDataTable(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); try { switch (request.QueryType) { case tgQueryType.StoredProcedure: response = LoadDataTableFromStoredProcedure(request); break; case tgQueryType.Text: response = LoadDataTableFromText(request); break; default: break; } } catch (Exception ex) { response.Exception = ex; } return response; } #endregion IDataProvider Members static private tgDataResponse LoadDataSetFromStoredProcedure(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); SACommand cmd = null; try { DataSet dataSet = new DataSet(); cmd = new SACommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = Shared.CreateFullName(request); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; if (request.Parameters != null) Shared.AddParameters(cmd, request); SADataAdapter da = new SADataAdapter(); da.SelectCommand = cmd; try { tgTransactionScope.Enlist(da.SelectCommand, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "LoadFromStoredProcedure", System.Environment.StackTrace)) { try { da.Fill(dataSet); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Fill(dataSet); } } finally { tgTransactionScope.DeEnlist(da.SelectCommand); } response.DataSet = dataSet; if (request.Parameters != null) { Shared.GatherReturnParameters(cmd, request, response); } } catch (Exception) { CleanupCommand(cmd); throw; } finally { } return response; } static private tgDataResponse LoadDataSetFromText(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); SACommand cmd = null; try { DataSet dataSet = new DataSet(); cmd = new SACommand(); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; if (request.Parameters != null) Shared.AddParameters(cmd, request); SADataAdapter da = new SADataAdapter(); cmd.CommandText = request.QueryText; da.SelectCommand = cmd; try { tgTransactionScope.Enlist(da.SelectCommand, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "LoadDataSetFromText", System.Environment.StackTrace)) { try { da.Fill(dataSet); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Fill(dataSet); } } finally { tgTransactionScope.DeEnlist(da.SelectCommand); } response.DataSet = dataSet; if (request.Parameters != null) { Shared.GatherReturnParameters(cmd, request, response); } } catch (Exception) { CleanupCommand(cmd); throw; } finally { } return response; } static private tgDataResponse LoadDataTableFromStoredProcedure(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); SACommand cmd = null; try { DataTable dataTable = new DataTable(request.ProviderMetadata.Destination); cmd = new SACommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = Shared.CreateFullName(request); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; if (request.Parameters != null) Shared.AddParameters(cmd, request); SADataAdapter da = new SADataAdapter(); da.SelectCommand = cmd; try { tgTransactionScope.Enlist(da.SelectCommand, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "LoadFromStoredProcedure", System.Environment.StackTrace)) { try { da.Fill(dataTable); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Fill(dataTable); } } finally { tgTransactionScope.DeEnlist(da.SelectCommand); } response.Table = dataTable; if (request.Parameters != null) { Shared.GatherReturnParameters(cmd, request, response); } } catch (Exception) { CleanupCommand(cmd); throw; } finally { } return response; } static private tgDataResponse LoadDataTableFromText(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); SACommand cmd = null; try { DataTable dataTable = new DataTable(request.ProviderMetadata.Destination); cmd = new SACommand(); cmd.CommandType = CommandType.Text; if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; if (request.Parameters != null) Shared.AddParameters(cmd, request); SADataAdapter da = new SADataAdapter(); cmd.CommandText = request.QueryText; da.SelectCommand = cmd; try { tgTransactionScope.Enlist(da.SelectCommand, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "LoadFromText", System.Environment.StackTrace)) { try { da.Fill(dataTable); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Fill(dataTable); } } finally { tgTransactionScope.DeEnlist(da.SelectCommand); } response.Table = dataTable; if (request.Parameters != null) { Shared.GatherReturnParameters(cmd, request, response); } } catch (Exception) { CleanupCommand(cmd); throw; } finally { } return response; } static private tgDataResponse LoadManyToMany(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); SACommand cmd = null; try { DataTable dataTable = new DataTable(request.ProviderMetadata.Destination); cmd = new SACommand(); cmd.CommandType = CommandType.Text; if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; string mmQuery = request.QueryText; string[] sections = mmQuery.Split('|'); string[] tables = sections[0].Split(','); string[] columns = sections[1].Split(','); string prefix = String.Empty; if (request.Catalog != null || request.ProviderMetadata.Catalog != null) { prefix += Delimiters.TableOpen; prefix += request.Catalog != null ? request.Catalog : request.ProviderMetadata.Catalog; prefix += Delimiters.TableClose + "."; } if (request.Schema != null || request.ProviderMetadata.Schema != null) { prefix += Delimiters.TableOpen; prefix += request.Schema != null ? request.Schema : request.ProviderMetadata.Schema; prefix += Delimiters.TableClose + "."; } string table0 = prefix + Delimiters.TableOpen + tables[0] + Delimiters.TableClose; string table1 = prefix + Delimiters.TableOpen + tables[1] + Delimiters.TableClose; string sql = "SELECT * FROM " + table0 + " JOIN " + table1 + " ON " + table0 + ".[" + columns[0] + "] = "; sql += table1 + ".[" + columns[1] + "] WHERE " + table1 + ".[" + sections[2] + "] = ?"; if (request.Parameters != null) { Shared.AddParameters(cmd, request); } SADataAdapter da = new SADataAdapter(); cmd.CommandText = sql; da.SelectCommand = cmd; try { tgTransactionScope.Enlist(da.SelectCommand, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "LoadManyToMany", System.Environment.StackTrace)) { try { da.Fill(dataTable); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Fill(dataTable); } } finally { tgTransactionScope.DeEnlist(da.SelectCommand); } response.Table = dataTable; } catch (Exception) { CleanupCommand(cmd); throw; } finally { } return response; } // This is used only to execute the Dynamic Query API static private void LoadDataTableFromDynamicQuery(tgDataRequest request, tgDataResponse response, SACommand cmd) { try { response.LastQuery = cmd.CommandText; if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; DataTable dataTable = new DataTable(request.ProviderMetadata.Destination); SADataAdapter da = new SADataAdapter(); da.SelectCommand = cmd; try { tgTransactionScope.Enlist(da.SelectCommand, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "LoadFromDynamicQuery", System.Environment.StackTrace)) { try { da.Fill(dataTable); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Fill(dataTable); } } finally { tgTransactionScope.DeEnlist(da.SelectCommand); }; response.Table = dataTable; } catch (Exception) { CleanupCommand(cmd); throw; } finally { } } static private DataTable SaveStoredProcCollection(tgDataRequest request) { bool needToInsert = false; bool needToUpdate = false; bool needToDelete = false; Dictionary<DataRow, tgEntitySavePacket> rowMapping = null; if (request.ContinueUpdateOnError) { rowMapping = new Dictionary<DataRow, tgEntitySavePacket>(); } //================================================ // Create the DataTable ... //================================================ DataTable dataTable = CreateDataTable(request); foreach (tgEntitySavePacket packet in request.CollectionSavePacket) { DataRow row = dataTable.NewRow(); switch (request.EntitySavePacket.RowState) { case tgDataRowState.Added: SetModifiedValues(request, packet, row); dataTable.Rows.Add(row); if (request.ContinueUpdateOnError) rowMapping[row] = packet; break; case tgDataRowState.Modified: SetOriginalValues(request, packet, row, false); SetModifiedValues(request, packet, row); dataTable.Rows.Add(row); row.AcceptChanges(); row.SetModified(); if (request.ContinueUpdateOnError) rowMapping[row] = packet; break; case tgDataRowState.Deleted: SetOriginalValues(request, packet, row, true); dataTable.Rows.Add(row); row.AcceptChanges(); row.Delete(); if (request.ContinueUpdateOnError) rowMapping[row] = packet; break; } } if (Shared.HasUpdates(dataTable.Rows, out needToInsert, out needToUpdate, out needToDelete)) { using (SADataAdapter da = new SADataAdapter()) { da.AcceptChangesDuringUpdate = false; da.ContinueUpdateOnError = request.ContinueUpdateOnError; SACommand cmd = null; if (needToInsert) da.InsertCommand = cmd = Shared.BuildStoredProcInsertCommand(request); if (needToUpdate) da.UpdateCommand = cmd = Shared.BuildStoredProcUpdateCommand(request); if (needToDelete) da.DeleteCommand = cmd = Shared.BuildStoredProcDeleteCommand(request); using (tgTransactionScope scope = new tgTransactionScope()) { if (needToInsert) tgTransactionScope.Enlist(da.InsertCommand, request.ConnectionString, CreateIDbConnectionDelegate); if (needToUpdate) tgTransactionScope.Enlist(da.UpdateCommand, request.ConnectionString, CreateIDbConnectionDelegate); if (needToDelete) tgTransactionScope.Enlist(da.DeleteCommand, request.ConnectionString, CreateIDbConnectionDelegate); try { #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "SaveCollectionStoredProcedure", System.Environment.StackTrace)) { try { da.Update(dataTable); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Update(dataTable); } } finally { if (needToInsert) tgTransactionScope.DeEnlist(da.InsertCommand); if (needToUpdate) tgTransactionScope.DeEnlist(da.UpdateCommand); if (needToDelete) tgTransactionScope.DeEnlist(da.DeleteCommand); } scope.Complete(); } } if (request.ContinueUpdateOnError && dataTable.HasErrors) { DataRow[] errors = dataTable.GetErrors(); foreach (DataRow rowWithError in errors) { request.FireOnError(rowMapping[rowWithError], rowWithError.RowError); } } } return request.Table; } static private DataTable SaveStoredProcEntity(tgDataRequest request) { bool needToDelete = request.EntitySavePacket.RowState == tgDataRowState.Deleted; DataTable dataTable = CreateDataTable(request); using (SADataAdapter da = new SADataAdapter()) { da.AcceptChangesDuringUpdate = false; DataRow row = dataTable.NewRow(); dataTable.Rows.Add(row); SACommand cmd = null; switch (request.EntitySavePacket.RowState) { case tgDataRowState.Added: cmd = da.InsertCommand = Shared.BuildStoredProcInsertCommand(request); SetModifiedValues(request, request.EntitySavePacket, row); break; case tgDataRowState.Modified: cmd = da.UpdateCommand = Shared.BuildStoredProcUpdateCommand(request); SetOriginalValues(request, request.EntitySavePacket, row, false); SetModifiedValues(request, request.EntitySavePacket, row); row.AcceptChanges(); row.SetModified(); break; case tgDataRowState.Deleted: cmd = da.DeleteCommand = Shared.BuildStoredProcDeleteCommand(request); SetOriginalValues(request, request.EntitySavePacket, row, true); row.AcceptChanges(); row.Delete(); break; } DataRow[] singleRow = new DataRow[1]; singleRow[0] = row; try { tgTransactionScope.Enlist(cmd, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "SaveEntityStoredProcedure", System.Environment.StackTrace)) { try { da.Update(singleRow); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Update(singleRow); } } finally { tgTransactionScope.DeEnlist(cmd); } if (cmd.Parameters != null) { foreach (SAParameter param in cmd.Parameters) { switch (param.Direction) { case ParameterDirection.Output: case ParameterDirection.InputOutput: request.EntitySavePacket.CurrentValues[param.SourceColumn] = param.Value; break; } } } } return dataTable; } static private DataTable SaveDynamicCollection(tgDataRequest request) { tgEntitySavePacket pkt = request.CollectionSavePacket[0]; if (pkt.RowState == tgDataRowState.Deleted) { //============================================================================ // We do all our deletes at once, so if the first one is a delete they all are //============================================================================ return SaveDynamicCollection_Deletes(request); } else { //============================================================================ // We do all our Inserts and Updates at once //============================================================================ return SaveDynamicCollection_InsertsUpdates(request); } } static private DataTable SaveDynamicCollection_InsertsUpdates(tgDataRequest request) { DataTable dataTable = CreateDataTable(request); using (tgTransactionScope scope = new tgTransactionScope()) { using (SADataAdapter da = new SADataAdapter()) { da.AcceptChangesDuringUpdate = false; da.ContinueUpdateOnError = request.ContinueUpdateOnError; SACommand cmd = null; if (!request.IgnoreComputedColumns) { da.RowUpdated += new SARowUpdatedEventHandler(OnRowUpdated); } foreach (tgEntitySavePacket packet in request.CollectionSavePacket) { if (packet.RowState != tgDataRowState.Added && packet.RowState != tgDataRowState.Modified) continue; DataRow row = dataTable.NewRow(); dataTable.Rows.Add(row); switch (packet.RowState) { case tgDataRowState.Added: cmd = da.InsertCommand = Shared.BuildDynamicInsertCommand(request, packet.ModifiedColumns); SetModifiedValues(request, packet, row); break; case tgDataRowState.Modified: cmd = da.UpdateCommand = Shared.BuildDynamicUpdateCommand(request, packet.ModifiedColumns); SetOriginalValues(request, packet, row, false); SetModifiedValues(request, packet, row); row.AcceptChanges(); row.SetModified(); break; } request.Properties["tgDataRequest"] = request; request.Properties["esEntityData"] = packet; dataTable.ExtendedProperties["props"] = request.Properties; DataRow[] singleRow = new DataRow[1]; singleRow[0] = row; try { tgTransactionScope.Enlist(cmd, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, packet, "SaveCollectionDynamic", System.Environment.StackTrace)) { try { da.Update(singleRow); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Update(singleRow); } if (row.HasErrors) { request.FireOnError(packet, row.RowError); } } finally { tgTransactionScope.DeEnlist(cmd); dataTable.Rows.Clear(); } } } scope.Complete(); } return dataTable; } static private DataTable SaveDynamicCollection_Deletes(tgDataRequest request) { SACommand cmd = null; DataTable dataTable = CreateDataTable(request); using (tgTransactionScope scope = new tgTransactionScope()) { using (SADataAdapter da = new SADataAdapter()) { da.AcceptChangesDuringUpdate = false; da.ContinueUpdateOnError = request.ContinueUpdateOnError; try { da.ContinueUpdateOnError = request.ContinueUpdateOnError; cmd = da.DeleteCommand = Shared.BuildDynamicDeleteCommand(request, request.CollectionSavePacket[0]); tgTransactionScope.Enlist(cmd, request.ConnectionString, CreateIDbConnectionDelegate); DataRow[] singleRow = new DataRow[1]; // Delete each record foreach (tgEntitySavePacket packet in request.CollectionSavePacket) { DataRow row = dataTable.NewRow(); dataTable.Rows.Add(row); SetOriginalValues(request, packet, row, true); row.AcceptChanges(); row.Delete(); singleRow[0] = row; #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, packet, "SaveCollectionDynamic", System.Environment.StackTrace)) { try { da.Update(singleRow); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Update(singleRow); } if (row.HasErrors) { request.FireOnError(packet, row.RowError); } dataTable.Rows.Clear(); // ADO.NET won't let us reuse the same DataRow } } finally { tgTransactionScope.DeEnlist(cmd); } } scope.Complete(); } return request.Table; } static private DataTable SaveDynamicEntity(tgDataRequest request) { bool needToDelete = request.EntitySavePacket.RowState == tgDataRowState.Deleted; DataTable dataTable = CreateDataTable(request); using (SADataAdapter da = new SADataAdapter()) { da.AcceptChangesDuringUpdate = false; DataRow row = dataTable.NewRow(); dataTable.Rows.Add(row); SACommand cmd = null; switch (request.EntitySavePacket.RowState) { case tgDataRowState.Added: cmd = da.InsertCommand = Shared.BuildDynamicInsertCommand(request, request.EntitySavePacket.ModifiedColumns); SetModifiedValues(request, request.EntitySavePacket, row); break; case tgDataRowState.Modified: cmd = da.UpdateCommand = Shared.BuildDynamicUpdateCommand(request, request.EntitySavePacket.ModifiedColumns); SetOriginalValues(request, request.EntitySavePacket, row, false); SetModifiedValues(request, request.EntitySavePacket, row); row.AcceptChanges(); row.SetModified(); break; case tgDataRowState.Deleted: cmd = da.DeleteCommand = Shared.BuildDynamicDeleteCommand(request, request.EntitySavePacket); SetOriginalValues(request, request.EntitySavePacket, row, true); row.AcceptChanges(); row.Delete(); break; } if (!needToDelete && request.Properties != null) { request.Properties["tgDataRequest"] = request; request.Properties["esEntityData"] = request.EntitySavePacket; dataTable.ExtendedProperties["props"] = request.Properties; } DataRow[] singleRow = new DataRow[1]; singleRow[0] = row; try { if (!request.IgnoreComputedColumns) { da.RowUpdated += new SARowUpdatedEventHandler(OnRowUpdated); } tgTransactionScope.Enlist(cmd, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, request.EntitySavePacket, "SaveEntityDynamic", System.Environment.StackTrace)) { try { da.Update(singleRow); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Update(singleRow); } } finally { tgTransactionScope.DeEnlist(cmd); } } return dataTable; } static private DataTable CreateDataTable(tgDataRequest request) { DataTable dataTable = new DataTable(); DataColumnCollection dataColumns = dataTable.Columns; tgColumnMetadataCollection cols = request.Columns; if (request.SelectedColumns == null) { tgColumnMetadata col; for (int i = 0; i < cols.Count; i++) { col = cols[i]; dataColumns.Add(new DataColumn(col.Name, col.Type)); } } else { foreach (string col in request.SelectedColumns.Keys) { dataColumns.Add(new DataColumn(col, cols[col].Type)); } } return dataTable; } private static void SetOriginalValues(tgDataRequest request, tgEntitySavePacket packet, DataRow row, bool primaryKeysAndConcurrencyOnly) { foreach (tgColumnMetadata col in request.Columns) { if (primaryKeysAndConcurrencyOnly && (!col.IsInPrimaryKey && !col.IsConcurrency && !col.IsTiraggoConcurrency)) continue; string columnName = col.Name; if (packet.OriginalValues.ContainsKey(columnName)) { row[columnName] = packet.OriginalValues[columnName]; } } } private static void SetModifiedValues(tgDataRequest request, tgEntitySavePacket packet, DataRow row) { foreach (string column in packet.ModifiedColumns) { if (request.Columns.FindByColumnName(column) != null) { row[column] = packet.CurrentValues[column]; } } } // If it's an Insert we fetch the @@Identity value and stuff it in the proper column protected static void OnRowUpdated(object sender, SARowUpdatedEventArgs e) { try { PropertyCollection props = e.Row.Table.ExtendedProperties; if (props.ContainsKey("props")) { props = (PropertyCollection)props["props"]; } if (e.Status == UpdateStatus.Continue && (e.StatementType == StatementType.Insert || e.StatementType == StatementType.Update)) { tgDataRequest request = props["tgDataRequest"] as tgDataRequest; tgEntitySavePacket packet = (tgEntitySavePacket)props["esEntityData"]; if (e.StatementType == StatementType.Insert) { if (props.Contains("AutoInc")) { string autoInc = props["AutoInc"] as string; SACommand cmd = new SACommand(); cmd.Connection = e.Command.Connection; cmd.Transaction = e.Command.Transaction; cmd.CommandText = "SELECT @@IDENTITY;"; cmd.CommandType = CommandType.Text; object o = null; #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "OnRowUpdated", System.Environment.StackTrace)) { try { o = cmd.ExecuteScalar(); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { o = cmd.ExecuteScalar(); } if (o != null) { packet.CurrentValues[autoInc] = o; e.Row[autoInc] = o; } } if (props.Contains("EntitySpacesConcurrency")) { string esConcurrencyColumn = props["EntitySpacesConcurrency"] as string; packet.CurrentValues[esConcurrencyColumn] = 1; } } //------------------------------------------------------------------------------------------------- // Fetch any defaults, SQLite doesn't support output parameters so we gotta do this the hard way //------------------------------------------------------------------------------------------------- if (props.Contains("Defaults")) { // Build the Where parameter and parameters SACommand cmd = new SACommand(); cmd.Connection = e.Command.Connection; cmd.Transaction = e.Command.Transaction; string select = (string)props["Defaults"]; string[] whereParameters = ((string)props["Where"]).Split(','); string comma = String.Empty; string where = String.Empty; int i = 1; foreach (string parameter in whereParameters) { SAParameter p = new SAParameter(":p" + i++.ToString(), e.Row[parameter]); cmd.Parameters.Add(p); where += comma + "[" + parameter + "]=" + p.ParameterName; comma = " AND "; } // Okay, now we can execute the sql and get any values that have defaults that were // null at the time of the insert and/or our timestamp cmd.CommandText = "SELECT " + select + " FROM [" + request.ProviderMetadata.Source + "] WHERE " + where + ";"; SADataReader rdr = null; try { #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "OnRowUpdated", System.Environment.StackTrace)) { try { rdr = cmd.ExecuteReader(CommandBehavior.SingleResult); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { rdr = cmd.ExecuteReader(CommandBehavior.SingleResult); } if (rdr.Read()) { select = select.Replace("[", String.Empty).Replace("]", String.Empty); string[] selectCols = select.Split(','); for (int k = 0; k < selectCols.Length; k++) { packet.CurrentValues[selectCols[k]] = rdr.GetValue(k); } } } finally { // Make sure we close the reader no matter what if (rdr != null) rdr.Close(); } } if (e.StatementType == StatementType.Update) { string colName = props["EntitySpacesConcurrency"] as string; object o = e.Row[colName]; switch (Type.GetTypeCode(o.GetType())) { case TypeCode.Int16: packet.CurrentValues[colName] = ((System.Int16)o) + 1; break; case TypeCode.Int32: packet.CurrentValues[colName] = ((System.Int32)o) + 1; break; case TypeCode.Int64: packet.CurrentValues[colName] = ((System.Int64)o) + 1; break; case TypeCode.UInt16: packet.CurrentValues[colName] = ((System.UInt16)o) + 1; break; case TypeCode.UInt32: packet.CurrentValues[colName] = ((System.UInt32)o) + 1; break; case TypeCode.UInt64: packet.CurrentValues[colName] = ((System.UInt64)o) + 1; break; } } } } catch { } } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using DotSpatial.NTSExtension; using DotSpatial.Serialization; namespace DotSpatial.Symbology { /// <summary> /// PointCategory. /// </summary> [Serializable] public class PointCategory : FeatureCategory, IPointCategory { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="PointCategory"/> class. /// </summary> public PointCategory() { Symbolizer = new PointSymbolizer(); SelectionSymbolizer = new PointSymbolizer(true); } /// <summary> /// Initializes a new instance of the <see cref="PointCategory"/> class where the geographic symbol size has been /// scaled to the specified extent. /// </summary> /// <param name="extent">The geographic extent that is 100 times wider than the geographic size of the points.</param> public PointCategory(IRectangle extent) { Symbolizer = new PointSymbolizer(false, extent); SelectionSymbolizer = new PointSymbolizer(true, extent); } /// <summary> /// Initializes a new instance of the <see cref="PointCategory"/> class based on a symbolizer. /// This uses the same symbolizer, but with a fill and border color of light cyan /// for the selection symbolizer. /// </summary> /// <param name="pointSymbolizer">The symbolizer to use in order to create a category.</param> public PointCategory(IPointSymbolizer pointSymbolizer) { Symbolizer = pointSymbolizer; SelectionSymbolizer = pointSymbolizer.Copy(); SelectionSymbolizer.SetFillColor(Color.Cyan); } /// <summary> /// Initializes a new instance of the <see cref="PointCategory"/> class where the symbolizer is based on the simple characteristics. /// The selection symbolizer has the same shape and size, but will be colored cyan. /// </summary> /// <param name="color">The color of the regular symbolizer.</param> /// <param name="shape">The shape of the regular symbolizer.</param> /// <param name="size">the size of the regular symbolizer.</param> public PointCategory(Color color, PointShape shape, double size) { Symbolizer = new PointSymbolizer(color, shape, size); SelectionSymbolizer = new PointSymbolizer(Color.Cyan, shape, size); } /// <summary> /// Initializes a new instance of the <see cref="PointCategory"/> class based on the specified character. /// </summary> /// <param name="character">The character to use for the symbol.</param> /// <param name="fontFamilyName">The font family name to use as the font.</param> /// <param name="color">The color of the character.</param> /// <param name="size">The size of the symbol.</param> public PointCategory(char character, string fontFamilyName, Color color, double size) { Symbolizer = new PointSymbolizer(character, fontFamilyName, color, size); SelectionSymbolizer = new PointSymbolizer(character, fontFamilyName, Color.Cyan, size); } /// <summary> /// Initializes a new instance of the <see cref="PointCategory"/> class where the picture is used for the symbol, /// and a selected symbol is created as the same symbol but with a cyan border. /// </summary> /// <param name="picture">The image to use.</param> /// <param name="size">The size of the symbol.</param> public PointCategory(Image picture, double size) { Symbolizer = new PointSymbolizer(picture, size); PictureSymbol ps = new PictureSymbol(picture, size) { OutlineColor = Color.Cyan, OutlineWidth = 2, OutlineOpacity = 1f }; SelectionSymbolizer = new PointSymbolizer(ps); } /// <summary> /// Initializes a new instance of the <see cref="PointCategory"/> class from the single symbol specified. /// If the symbol is colorable, the color of the selection symbol will be duplicated, but set to cyan. /// </summary> /// <param name="symbol">Symbol used for the category.</param> public PointCategory(ISymbol symbol) { Symbolizer = new PointSymbolizer(symbol); ISymbol copy = symbol.Copy(); IColorable c = copy as IColorable; if (c != null) { c.Color = Color.Cyan; } SelectionSymbolizer = new PointSymbolizer(copy); } /// <summary> /// Initializes a new instance of the <see cref="PointCategory"/> class from the list of symbols. /// </summary> /// <param name="symbols">Symbols used for this category.</param> public PointCategory(IEnumerable<ISymbol> symbols) { var symb = symbols as IList<ISymbol> ?? symbols.ToList(); Symbolizer = new PointSymbolizer(symb); List<ISymbol> copy = symb.CloneList(); if (copy.Any()) { IColorable c = symb.Last() as IColorable; if (c != null) { c.Color = Color.Cyan; } } SelectionSymbolizer = new PointSymbolizer(copy); } #endregion #region Properties /// <summary> /// Gets or sets the symbolizer to use to draw selected features from this category. /// </summary> [Description("Gets or sets the symbolizer to use to draw selected features from this category.")] public new IPointSymbolizer SelectionSymbolizer { get { return base.SelectionSymbolizer as IPointSymbolizer; } set { base.SelectionSymbolizer = value; } } /// <summary> /// Gets or sets the symbolizer for this category. /// </summary> [Description("Gets or sets the symbolizer for this category")] public new IPointSymbolizer Symbolizer { get { return base.Symbolizer as IPointSymbolizer; } set { base.Symbolizer = value; } } #endregion #region Methods /// <summary> /// This gets a single color that attempts to represent the specified /// category. For polygons, for example, this is the fill color (or central fill color) /// of the top pattern. If an image is being used, the color will be gray. /// </summary> /// <returns>The System.Color that can be used as an approximation to represent this category.</returns> public override Color GetColor() { if (Symbolizer?.Symbols == null || Symbolizer.Symbols.Count == 0) return Color.Gray; ISymbol p = Symbolizer.Symbols[0]; return p.GetColor(); } /// <summary> /// Gets the legend symbol size of the symbolizer for this category. /// </summary> /// <returns>The legend symbol size.</returns> public override Size GetLegendSymbolSize() { return Symbolizer.GetLegendSymbolSize(); } /// <summary> /// Sets the Color of the top symbol in the symbols. /// </summary> /// <param name="color">The color to set the point.</param> public override void SetColor(Color color) { Symbolizer?.SetFillColor(color); } #endregion } }
// Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Microsoft.Data.OData { #region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Xml; using Microsoft.Data.Edm; using Microsoft.Data.Edm.Csdl; using Microsoft.Data.Edm.Validation; using Microsoft.Data.OData.Atom; #endregion Namespaces /// <summary> /// RAW format output context. /// </summary> internal sealed class ODataMetadataOutputContext : ODataOutputContext { /// <summary>The message output stream.</summary> private Stream messageOutputStream; /// <summary>The XmlWriter to write to.</summary> private XmlWriter xmlWriter; /// <summary> /// Constructor. /// </summary> /// <param name="format">The format for this output context.</param> /// <param name="messageStream">The message stream to write the payload to.</param> /// <param name="encoding">The encoding to use for the payload.</param> /// <param name="messageWriterSettings">Configuration settings of the OData writer.</param> /// <param name="writingResponse">true if writing a response message; otherwise false.</param> /// <param name="synchronous">true if the output should be written synchronously; false if it should be written asynchronously.</param> /// <param name="model">The model to use.</param> /// <param name="urlResolver">The optional URL resolver to perform custom URL resolution for URLs written to the payload.</param> private ODataMetadataOutputContext( ODataFormat format, Stream messageStream, Encoding encoding, ODataMessageWriterSettings messageWriterSettings, bool writingResponse, bool synchronous, IEdmModel model, IODataUrlResolver urlResolver) : base(format, messageWriterSettings, writingResponse, synchronous, model, urlResolver) { Debug.Assert(synchronous, "Metadata output context is only supported in synchronous operations."); try { this.messageOutputStream = messageStream; this.xmlWriter = ODataAtomWriterUtils.CreateXmlWriter(messageStream, messageWriterSettings, encoding); } catch (Exception e) { // Dispose the message stream if we failed to create the output context. if (ExceptionUtils.IsCatchableExceptionType(e) && messageStream != null) { messageStream.Dispose(); } throw; } } /// <summary> /// Create metadata output context. /// </summary> /// <param name="format">The format to create the output context for.</param> /// <param name="message">The message to use.</param> /// <param name="encoding">The encoding to use.</param> /// <param name="messageWriterSettings">Configuration settings of the OData writer.</param> /// <param name="writingResponse">true if writing a response message; otherwise false.</param> /// <param name="model">The model to use.</param> /// <param name="urlResolver">The optional URL resolver to perform custom URL resolution for URLs written to the payload.</param> /// <returns>The newly created output context.</returns> internal static ODataOutputContext Create( ODataFormat format, ODataMessage message, Encoding encoding, ODataMessageWriterSettings messageWriterSettings, bool writingResponse, IEdmModel model, IODataUrlResolver urlResolver) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(format == ODataFormat.Metadata, "This method only supports the Metadata format."); Debug.Assert(message != null, "message != null"); Debug.Assert(messageWriterSettings != null, "messageWriterSettings != null"); Stream messageStream = message.GetStream(); return new ODataMetadataOutputContext( format, messageStream, encoding, messageWriterSettings, writingResponse, true, model, urlResolver); } /// <summary> /// Synchronously flush the writer. /// </summary> internal void Flush() { DebugUtils.CheckNoExternalCallers(); this.AssertSynchronous(); // XmlWriter.Flush will call the underlying Stream.Flush. // In the synchronous case the underlying stream is the message stream itself, which will then Flush as well. this.xmlWriter.Flush(); } /// <summary> /// Writes an <see cref="ODataError"/> into the message payload. /// </summary> /// <param name="error">The error to write.</param> /// <param name="includeDebugInformation"> /// A flag indicating whether debug information (e.g., the inner error from the <paramref name="error"/>) should /// be included in the payload. This should only be used in debug scenarios. /// </param> /// <remarks> /// This method is called if the ODataMessageWriter.WriteError is called once some other /// write operation has already started. /// The method should write the in-stream error representation for the specific format into the current payload. /// Before the method is called no flush is performed on the output context or any active writer. /// It is the responsibility of this method to flush the output before the method returns. /// </remarks> internal override void WriteInStreamError(ODataError error, bool includeDebugInformation) { DebugUtils.CheckNoExternalCallers(); this.AssertSynchronous(); ODataAtomWriterUtils.WriteError(this.xmlWriter, error, includeDebugInformation, this.MessageWriterSettings.MessageQuotas.MaxNestingDepth); this.Flush(); } /// <summary> /// Writes the metadata document as the message body. /// </summary> /// <remarks>It is the responsibility of this method to flush the output before the method returns.</remarks> internal override void WriteMetadataDocument() { DebugUtils.CheckNoExternalCallers(); this.AssertSynchronous(); // Save the in-memory OData annotations to the model (i.e., turn them into serializable ones) this.Model.SaveODataAnnotations(); IEnumerable<EdmError> errors; if (!EdmxWriter.TryWriteEdmx(this.Model, this.xmlWriter, EdmxTarget.OData, out errors)) { Debug.Assert(errors != null, "errors != null"); StringBuilder builder = new StringBuilder(); foreach (EdmError error in errors) { builder.AppendLine(error.ToString()); } throw new ODataException(Strings.ODataMetadataOutputContext_ErrorWritingMetadata(builder.ToString())); } this.Flush(); } /// <summary> /// Perform the actual cleanup work. /// </summary> /// <param name="disposing">If 'true' this method is called from user code; if 'false' it is called by the runtime.</param> protected override void Dispose(bool disposing) { base.Dispose(disposing); try { if (this.xmlWriter != null) { // Note that the this.xmlWriter might be one of the XML customization writers, but since we don't own those // we won't be flushing or disposing them. We just own the root writer which we created. // XmlWriter.Flush will call the underlying Stream.Flush. this.xmlWriter.Flush(); // XmlWriter.Dispose calls XmlWriter.Close which writes missing end elements. // Thus we can't dispose the XmlWriter since that might end up writing more data into the stream right here // and thus callers would have no way to prevent us from writing synchronously into the underlying stream. // Also in case of in-stream error we intentionally want to not write the end elements to keep the payload invalid. // In the async case the underlying stream is the async buffered stream, so we have to flush that explicitely. // Dipose the message stream (note that we OWN this stream, so we always dispose it). this.messageOutputStream.Dispose(); } } finally { this.messageOutputStream = null; this.xmlWriter = null; } } } }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; using System.Drawing; using System.Text; namespace Scientia.HtmlRenderer.Demo.Common { /// <summary> /// HTML syntax highlighting using Rich-Text formatting.<br/> /// - Handle plain input or already in RTF format.<br/> /// - Handle if input already contains RTF color table.<br/> /// - Rich coloring adjusted to Visual Studio HTML coloring.<br/> /// - Support to provide custom colors.<br/> /// - High performance (as much as RTF format allows).<br/> /// </summary> /// <remarks> /// The MIT License (MIT) Copyright (c) 2014 Arthur Teplitzki.<br/> /// Based on work by Alun Evans 2006 (http://www.codeproject.com/Articles/15038/C-Formatting-Text-in-a-RichTextBox-by-Parsing-the). /// </remarks> public static class HtmlSyntaxHighlighter { #region Fields/Consts /// <summary> /// RTF header field /// </summary> private const string Header = "\\rtf"; /// <summary> /// RTF color table /// </summary> private const string ColorTbl = "\\colortbl"; /// <summary> /// cf0 = default /// cf1 = dark red /// cf2 = bright red /// cf3 = green /// cf4 = blue /// cf5 = blue /// cf6 = purple /// </summary> private const string DefaultColorScheme = "\\red128\\green0\\blue0;\\red240\\green0\\blue0;\\red0\\green128\\blue0;\\red0\\green0\\blue255;\\red0\\green0\\blue255;\\red128\\green0\\blue171;"; /// <summary> /// Used to test if a char requires more than 1 byte /// </summary> private static readonly char[] UnicodeTest = new char[1]; #endregion /// <summary> /// Process the given text to create RTF text with HTML syntax highlighting using default Visual Studio colors.<br/> /// The given text can be plain HTML or already parsed RTF format. /// </summary> /// <param name="text">the text to create color RTF text from</param> /// <returns>text with RTF formatting for HTML syntax</returns> public static string Process(string text) { return Process(text, DefaultColorScheme); } /// <summary> /// Process the given text to create RTF text with HTML syntax highlighting using custom colors.<br/> /// The given text can be plain HTML or already parsed RTF format. /// </summary> /// <param name="text">the text to create color RTF text from</param> /// <param name="element">the color for HTML elements</param> /// <param name="attribute">the color for HTML attributes</param> /// <param name="comment">the color for HTML comments</param> /// <param name="chars">the color for HTML special chars: (<![CDATA[<,>,",',=,:]]>)</param> /// <param name="values">the color for HTML attribute or styles values</param> /// <param name="style">the color for HTML style attribute</param> /// <returns>text with RTF formatting for HTML syntax</returns> public static string Process(string text, Color element, Color attribute, Color comment, Color chars, Color values, Color style) { return Process(text, CreateColorScheme(element, attribute, comment, chars, values, style)); } #region Private/Protected methods /// <summary> /// Process the given text to create RTF text with HTML syntax highlighting. /// </summary> /// <param name="text">the text to create color RTF text from</param> /// <param name="colorScheme">the color scheme to add to RTF color table</param> /// <returns>text with RTF formatting for HTML syntax</returns> private static string Process(string text, string colorScheme) { var sb = new StringBuilder(text.Length * 2); // add color table used to set color in RTL formatted text bool rtfFormated; int i = AddColorTable(sb, text, colorScheme, out rtfFormated); // Scan through RTF data adding RTF color tags bool inComment = false; bool inHtmlTag = false; bool inAttributeVal = false; for (; i < text.Length; i++) { var c = text[i]; var c2 = text.Length > i + 1 ? text[i + 1] : (char)0; if (!inComment && c == '<') { if (text.Length > i + 3 && c2 == '!' && text[i + 2] == '-' && text[i + 3] == '-') { // Comments tag sb.Append("\\cf3").Append(c); inComment = true; } else { // Html start/end tag sb.Append("\\cf4").Append(c); if (c2 == '/') { sb.Append(c2); i++; } sb.Append("\\cf1 "); inHtmlTag = true; } } else if (c == '>') { // Check for comments tags if (inComment && text[i - 1] == '-' && text[i - 2] == '-') { sb.Append(c).Append("\\cf0 "); inComment = false; } else if (!inComment) { sb.Append("\\cf4").Append(c).Append("\\cf0 "); inHtmlTag = false; inAttributeVal = false; } } else if (inHtmlTag && !inComment && c == '/' && c2 == '>') { sb.Append("\\cf4").Append(c).Append(c2).Append("\\cf0 "); inHtmlTag = false; i++; } else if (inHtmlTag && !inComment && !inAttributeVal && c == ' ') { sb.Append(c).Append("\\cf2 "); } else if (inHtmlTag && !inComment && c == '=') { sb.Append("\\cf4").Append(c).Append("\\cf6 "); } else if (inHtmlTag && !inComment && inAttributeVal && c == ':') { sb.Append("\\cf0").Append(c).Append("\\cf5 "); } else if (inHtmlTag && !inComment && inAttributeVal && c == ';') { sb.Append("\\cf0").Append(c).Append("\\cf6 "); } else if (inHtmlTag && !inComment && (c == '"' || c == '\'')) { sb.Append("\\cf4").Append(c).Append("\\cf6 "); inAttributeVal = !inAttributeVal; } else if (!rtfFormated && c == '\n') { sb.Append(c).Append("\\par "); } else if (!rtfFormated && (c == '{' || c == '}')) { sb.Append('\\').Append(c); } else if (!rtfFormated) { UnicodeTest[0] = c; if (Encoding.UTF8.GetByteCount(UnicodeTest, 0, 1) > 1) { sb.Append("\\u" + Convert.ToUInt32(c) + "?"); } else { sb.Append(c); } } else { sb.Append(c); } } // close the RTF if we added the header ourselves if (!rtfFormated) { sb.Append('}'); } // return the created colored RTF return sb.ToString(); } /// <summary> /// Add color table used to set color in RTL formatted text. /// </summary> /// <param name="sb">the builder to add the RTF string to</param> /// <param name="text">the original RTF text to build color RTF from</param> /// <param name="colorScheme">the color scheme to add to RTF color table</param> /// <param name="rtfFormated">return if the given text is already in RTF format</param> /// <returns>the index in the given RTF text to start scan from</returns> private static int AddColorTable(StringBuilder sb, string text, string colorScheme, out bool rtfFormated) { // Search for color table, if exists replace it, otherwise add our rtfFormated = true; int idx = text.IndexOf(ColorTbl, StringComparison.OrdinalIgnoreCase); if (idx != -1) { sb.Append(text, 0, idx); // insert our color table at our chosen location sb.Append(ColorTbl).Append(";").Append(colorScheme).Append("}"); // skip the existing color table idx = text.IndexOf('}', idx); } else { // find index of start of header if exists idx = text.IndexOf(Header, StringComparison.OrdinalIgnoreCase); if (idx != -1) { // append the existing header idx += Header.Length; sb.Append(text, 0, idx); while (text[idx] != '\\' && text[idx] != '{' && text[idx] != '}') { sb.Append(text[idx++]); } } else { // not RTF text, add the RTF header as well idx = 0; sb.Append("{").Append(Header); rtfFormated = false; } // insert the color table at our chosen location sb.Append("{").Append(ColorTbl).Append(";").Append(colorScheme).Append("}"); } return idx; } /// <summary> /// Create RTF colortbl formatted string for the given colors. /// </summary> private static string CreateColorScheme(Color element, Color attribute, Color comment, Color chars, Color values, Color style) { var sb = new StringBuilder(DefaultColorScheme.Length); AppendColorValue(sb, element); AppendColorValue(sb, attribute); AppendColorValue(sb, comment); AppendColorValue(sb, chars); AppendColorValue(sb, values); AppendColorValue(sb, style); return sb.ToString(); } /// <summary> /// Append single color in RTF colortbl format. /// </summary> private static void AppendColorValue(StringBuilder sb, Color color) { sb.Append("\\red").Append(color.R) .Append("\\green").Append(color.R) .Append("\\blue").Append(color.R) .Append(';'); } #endregion } }
using System; using System.Collections.Generic; using System.Text; using Technisient; namespace JobsNS { //Ref: http://stackoverflow.com/a/592025/233431 class CalculatePi : TaskBase { public override object Run(object input) { BigNumber x = new BigNumber(piLength); BigNumber y = new BigNumber(piLength); x.ArcTan(16, 5); y.ArcTan(4, 239); x.Subtract(y); LogInfo("Test Logging Info: " + x.PrintAsTable()); return true; } int piLength; [SamayParameter(LabelText="Pi Length", Help = "Length of Pi to be calculated", DefaultValue="300" ,IsRequired=true)] public int PiLength { get { return piLength; } set { piLength = value; } } } public class BigNumber { private UInt32[] number; private int size; private int maxDigits; public BigNumber(int maxDigits) { this.maxDigits = maxDigits; this.size = (int)Math.Ceiling((float)maxDigits * 0.104) + 2; number = new UInt32[size]; } public BigNumber(int maxDigits, UInt32 intPart) : this(maxDigits) { number[0] = intPart; for (int i = 1; i < size; i++) { number[i] = 0; } } public string PrintAsTable() { BigNumber temp = new BigNumber(maxDigits); temp.Assign(this); StringBuilder sb = new StringBuilder(); sb.Append(temp.number[0]); sb.Append(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator); int digitCount = 0; while (digitCount < maxDigits) { temp.number[0] = 0; temp.Multiply(100000); sb.AppendFormat("{0:D5}", temp.number[0]); digitCount += 5; } return sb.ToString(); } public bool IsZero() { foreach (UInt32 item in number) { if (item != 0) return false; } return true; } public void ArcTan(UInt32 multiplicand, UInt32 reciprocal) { BigNumber X = new BigNumber(maxDigits, multiplicand); X.Divide(reciprocal); reciprocal *= reciprocal; this.Assign(X); BigNumber term = new BigNumber(maxDigits); UInt32 divisor = 1; bool subtractTerm = true; while (true) { X.Divide(reciprocal); term.Assign(X); divisor += 2; term.Divide(divisor); if (term.IsZero()) break; if (subtractTerm) this.Subtract(term); else this.Add(term); subtractTerm = !subtractTerm; } } private void VerifySameSize(BigNumber value) { if (Object.ReferenceEquals(this, value)) throw new Exception("BigNumbers cannot operate on themselves"); if (value.size != this.size) throw new Exception("BigNumbers must have the same size"); } public void Assign(BigNumber value) { VerifySameSize(value); for (int i = 0; i < size; i++) { number[i] = value.number[i]; } } public void Add(BigNumber value) { VerifySameSize(value); int index = size - 1; while (index >= 0 && value.number[index] == 0) index--; UInt32 carry = 0; while (index >= 0) { UInt64 result = (UInt64)number[index] + value.number[index] + carry; number[index] = (UInt32)result; if (result >= 0x100000000U) carry = 1; else carry = 0; index--; } } public void Subtract(BigNumber value) { VerifySameSize(value); int index = size - 1; while (index >= 0 && value.number[index] == 0) index--; UInt32 borrow = 0; while (index >= 0) { UInt64 result = 0x100000000U + (UInt64)number[index] - value.number[index] - borrow; number[index] = (UInt32)result; if (result >= 0x100000000U) borrow = 0; else borrow = 1; index--; } } public void Multiply(UInt32 value) { int index = size - 1; while (index >= 0 && number[index] == 0) index--; UInt32 carry = 0; while (index >= 0) { UInt64 result = (UInt64)number[index] * value + carry; number[index] = (UInt32)result; carry = (UInt32)(result >> 32); index--; } } public void Divide(UInt32 value) { int index = 0; while (index < size && number[index] == 0) index++; UInt32 carry = 0; while (index < size) { UInt64 result = number[index] + ((UInt64)carry << 32); number[index] = (UInt32)(result / (UInt64)value); carry = (UInt32)(result % (UInt64)value); index++; } } } }
// NumberFormatInfo.cs // Script#/Libraries/CoreLib // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Runtime.CompilerServices; namespace System.Globalization { [ScriptIgnoreNamespace] [ScriptImport] public sealed class NumberFormatInfo { private NumberFormatInfo() { } [ScriptField] [ScriptName("nan")] public string NaNSymbol { get { return null; } } [ScriptField] [ScriptName("neg")] public string NegativeSign { get { return null; } } [ScriptField] [ScriptName("pos")] public string PositiveSign { get { return null; } } [ScriptField] [ScriptName("negInf")] public string NegativeInfinityText { get { return null; } } [ScriptField] [ScriptName("posInf")] public string PositiveInfinityText { get { return null; } } [ScriptField] [ScriptName("per")] public string PercentSymbol { get { return null; } } [ScriptField] [ScriptName("perGW")] public int[] PercentGroupSizes { get { return null; } } [ScriptField] [ScriptName("perDD")] public int PercentDecimalDigits { get { return 0; } } [ScriptField] [ScriptName("perDS")] public string PercentDecimalSeparator { get { return null; } } [ScriptField] [ScriptName("perGS")] public string PercentGroupSeparator { get { return null; } } [ScriptField] [ScriptName("perNP")] public string PercentNegativePattern { get { return null; } } [ScriptField] [ScriptName("perPP")] public string PercentPositivePattern { get { return null; } } [ScriptField] [ScriptName("cur")] public string CurrencySymbol { get { return null; } } [ScriptField] [ScriptName("curGW")] public int[] CurrencyGroupSizes { get { return null; } } [ScriptField] [ScriptName("curDD")] public int CurrencyDecimalDigits { get { return 0; } } [ScriptField] [ScriptName("curDS")] public string CurrencyDecimalSeparator { get { return null; } } [ScriptField] [ScriptName("curGS")] public string CurrencyGroupSeparator { get { return null; } } [ScriptField] [ScriptName("curNP")] public string CurrencyNegativePattern { get { return null; } } [ScriptField] [ScriptName("curPP")] public string CurrencyPositivePattern { get { return null; } } [ScriptField] [ScriptName("gw")] public int[] NumberGroupSizes { get { return null; } } [ScriptField] [ScriptName("dd")] public int NumberDecimalDigits { get { return 0; } } [ScriptField] [ScriptName("ds")] public string NumberDecimalSeparator { get { return null; } } [ScriptField] [ScriptName("gs")] public string NumberGroupSeparator { get { return null; } } } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="CustomerManagerLinkServiceClient"/> instances.</summary> public sealed partial class CustomerManagerLinkServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="CustomerManagerLinkServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="CustomerManagerLinkServiceSettings"/>.</returns> public static CustomerManagerLinkServiceSettings GetDefault() => new CustomerManagerLinkServiceSettings(); /// <summary> /// Constructs a new <see cref="CustomerManagerLinkServiceSettings"/> object with default settings. /// </summary> public CustomerManagerLinkServiceSettings() { } private CustomerManagerLinkServiceSettings(CustomerManagerLinkServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetCustomerManagerLinkSettings = existing.GetCustomerManagerLinkSettings; MutateCustomerManagerLinkSettings = existing.MutateCustomerManagerLinkSettings; MoveManagerLinkSettings = existing.MoveManagerLinkSettings; OnCopy(existing); } partial void OnCopy(CustomerManagerLinkServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>CustomerManagerLinkServiceClient.GetCustomerManagerLink</c> and /// <c>CustomerManagerLinkServiceClient.GetCustomerManagerLinkAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetCustomerManagerLinkSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>CustomerManagerLinkServiceClient.MutateCustomerManagerLink</c> and /// <c>CustomerManagerLinkServiceClient.MutateCustomerManagerLinkAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateCustomerManagerLinkSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>CustomerManagerLinkServiceClient.MoveManagerLink</c> and /// <c>CustomerManagerLinkServiceClient.MoveManagerLinkAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MoveManagerLinkSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="CustomerManagerLinkServiceSettings"/> object.</returns> public CustomerManagerLinkServiceSettings Clone() => new CustomerManagerLinkServiceSettings(this); } /// <summary> /// Builder class for <see cref="CustomerManagerLinkServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class CustomerManagerLinkServiceClientBuilder : gaxgrpc::ClientBuilderBase<CustomerManagerLinkServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public CustomerManagerLinkServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public CustomerManagerLinkServiceClientBuilder() { UseJwtAccessWithScopes = CustomerManagerLinkServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref CustomerManagerLinkServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CustomerManagerLinkServiceClient> task); /// <summary>Builds the resulting client.</summary> public override CustomerManagerLinkServiceClient Build() { CustomerManagerLinkServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<CustomerManagerLinkServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<CustomerManagerLinkServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private CustomerManagerLinkServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return CustomerManagerLinkServiceClient.Create(callInvoker, Settings); } private async stt::Task<CustomerManagerLinkServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return CustomerManagerLinkServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => CustomerManagerLinkServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => CustomerManagerLinkServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => CustomerManagerLinkServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>CustomerManagerLinkService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage customer-manager links. /// </remarks> public abstract partial class CustomerManagerLinkServiceClient { /// <summary> /// The default endpoint for the CustomerManagerLinkService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default CustomerManagerLinkService scopes.</summary> /// <remarks> /// The default CustomerManagerLinkService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="CustomerManagerLinkServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="CustomerManagerLinkServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="CustomerManagerLinkServiceClient"/>.</returns> public static stt::Task<CustomerManagerLinkServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new CustomerManagerLinkServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="CustomerManagerLinkServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="CustomerManagerLinkServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="CustomerManagerLinkServiceClient"/>.</returns> public static CustomerManagerLinkServiceClient Create() => new CustomerManagerLinkServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="CustomerManagerLinkServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="CustomerManagerLinkServiceSettings"/>.</param> /// <returns>The created <see cref="CustomerManagerLinkServiceClient"/>.</returns> internal static CustomerManagerLinkServiceClient Create(grpccore::CallInvoker callInvoker, CustomerManagerLinkServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } CustomerManagerLinkService.CustomerManagerLinkServiceClient grpcClient = new CustomerManagerLinkService.CustomerManagerLinkServiceClient(callInvoker); return new CustomerManagerLinkServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC CustomerManagerLinkService client</summary> public virtual CustomerManagerLinkService.CustomerManagerLinkServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested CustomerManagerLink in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::CustomerManagerLink GetCustomerManagerLink(GetCustomerManagerLinkRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested CustomerManagerLink in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CustomerManagerLink> GetCustomerManagerLinkAsync(GetCustomerManagerLinkRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested CustomerManagerLink in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CustomerManagerLink> GetCustomerManagerLinkAsync(GetCustomerManagerLinkRequest request, st::CancellationToken cancellationToken) => GetCustomerManagerLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested CustomerManagerLink in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the CustomerManagerLink to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::CustomerManagerLink GetCustomerManagerLink(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetCustomerManagerLink(new GetCustomerManagerLinkRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested CustomerManagerLink in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the CustomerManagerLink to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CustomerManagerLink> GetCustomerManagerLinkAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetCustomerManagerLinkAsync(new GetCustomerManagerLinkRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested CustomerManagerLink in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the CustomerManagerLink to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CustomerManagerLink> GetCustomerManagerLinkAsync(string resourceName, st::CancellationToken cancellationToken) => GetCustomerManagerLinkAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested CustomerManagerLink in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the CustomerManagerLink to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::CustomerManagerLink GetCustomerManagerLink(gagvr::CustomerManagerLinkName resourceName, gaxgrpc::CallSettings callSettings = null) => GetCustomerManagerLink(new GetCustomerManagerLinkRequest { ResourceNameAsCustomerManagerLinkName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested CustomerManagerLink in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the CustomerManagerLink to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CustomerManagerLink> GetCustomerManagerLinkAsync(gagvr::CustomerManagerLinkName resourceName, gaxgrpc::CallSettings callSettings = null) => GetCustomerManagerLinkAsync(new GetCustomerManagerLinkRequest { ResourceNameAsCustomerManagerLinkName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested CustomerManagerLink in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the CustomerManagerLink to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::CustomerManagerLink> GetCustomerManagerLinkAsync(gagvr::CustomerManagerLinkName resourceName, st::CancellationToken cancellationToken) => GetCustomerManagerLinkAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates or updates customer manager links. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [ManagerLinkError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateCustomerManagerLinkResponse MutateCustomerManagerLink(MutateCustomerManagerLinkRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates or updates customer manager links. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [ManagerLinkError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCustomerManagerLinkResponse> MutateCustomerManagerLinkAsync(MutateCustomerManagerLinkRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates or updates customer manager links. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [ManagerLinkError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCustomerManagerLinkResponse> MutateCustomerManagerLinkAsync(MutateCustomerManagerLinkRequest request, st::CancellationToken cancellationToken) => MutateCustomerManagerLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates or updates customer manager links. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [ManagerLinkError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose customer manager links are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual customer manager links. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateCustomerManagerLinkResponse MutateCustomerManagerLink(string customerId, scg::IEnumerable<CustomerManagerLinkOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateCustomerManagerLink(new MutateCustomerManagerLinkRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates or updates customer manager links. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [ManagerLinkError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose customer manager links are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual customer manager links. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCustomerManagerLinkResponse> MutateCustomerManagerLinkAsync(string customerId, scg::IEnumerable<CustomerManagerLinkOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateCustomerManagerLinkAsync(new MutateCustomerManagerLinkRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates or updates customer manager links. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [ManagerLinkError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose customer manager links are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual customer manager links. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCustomerManagerLinkResponse> MutateCustomerManagerLinkAsync(string customerId, scg::IEnumerable<CustomerManagerLinkOperation> operations, st::CancellationToken cancellationToken) => MutateCustomerManagerLinkAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Moves a client customer to a new manager customer. /// This simplifies the complex request that requires two operations to move /// a client customer to a new manager. i.e: /// 1. Update operation with Status INACTIVE (previous manager) and, /// 2. Update operation with Status ACTIVE (new manager). /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MoveManagerLinkResponse MoveManagerLink(MoveManagerLinkRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Moves a client customer to a new manager customer. /// This simplifies the complex request that requires two operations to move /// a client customer to a new manager. i.e: /// 1. Update operation with Status INACTIVE (previous manager) and, /// 2. Update operation with Status ACTIVE (new manager). /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MoveManagerLinkResponse> MoveManagerLinkAsync(MoveManagerLinkRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Moves a client customer to a new manager customer. /// This simplifies the complex request that requires two operations to move /// a client customer to a new manager. i.e: /// 1. Update operation with Status INACTIVE (previous manager) and, /// 2. Update operation with Status ACTIVE (new manager). /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MoveManagerLinkResponse> MoveManagerLinkAsync(MoveManagerLinkRequest request, st::CancellationToken cancellationToken) => MoveManagerLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Moves a client customer to a new manager customer. /// This simplifies the complex request that requires two operations to move /// a client customer to a new manager. i.e: /// 1. Update operation with Status INACTIVE (previous manager) and, /// 2. Update operation with Status ACTIVE (new manager). /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the client customer that is being moved. /// </param> /// <param name="previousCustomerManagerLink"> /// Required. The resource name of the previous CustomerManagerLink. /// The resource name has the form: /// `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` /// </param> /// <param name="newManager"> /// Required. The resource name of the new manager customer that the client wants to move /// to. Customer resource names have the format: "customers/{customer_id}" /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MoveManagerLinkResponse MoveManagerLink(string customerId, string previousCustomerManagerLink, string newManager, gaxgrpc::CallSettings callSettings = null) => MoveManagerLink(new MoveManagerLinkRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), PreviousCustomerManagerLink = gax::GaxPreconditions.CheckNotNullOrEmpty(previousCustomerManagerLink, nameof(previousCustomerManagerLink)), NewManager = gax::GaxPreconditions.CheckNotNullOrEmpty(newManager, nameof(newManager)), }, callSettings); /// <summary> /// Moves a client customer to a new manager customer. /// This simplifies the complex request that requires two operations to move /// a client customer to a new manager. i.e: /// 1. Update operation with Status INACTIVE (previous manager) and, /// 2. Update operation with Status ACTIVE (new manager). /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the client customer that is being moved. /// </param> /// <param name="previousCustomerManagerLink"> /// Required. The resource name of the previous CustomerManagerLink. /// The resource name has the form: /// `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` /// </param> /// <param name="newManager"> /// Required. The resource name of the new manager customer that the client wants to move /// to. Customer resource names have the format: "customers/{customer_id}" /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MoveManagerLinkResponse> MoveManagerLinkAsync(string customerId, string previousCustomerManagerLink, string newManager, gaxgrpc::CallSettings callSettings = null) => MoveManagerLinkAsync(new MoveManagerLinkRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), PreviousCustomerManagerLink = gax::GaxPreconditions.CheckNotNullOrEmpty(previousCustomerManagerLink, nameof(previousCustomerManagerLink)), NewManager = gax::GaxPreconditions.CheckNotNullOrEmpty(newManager, nameof(newManager)), }, callSettings); /// <summary> /// Moves a client customer to a new manager customer. /// This simplifies the complex request that requires two operations to move /// a client customer to a new manager. i.e: /// 1. Update operation with Status INACTIVE (previous manager) and, /// 2. Update operation with Status ACTIVE (new manager). /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the client customer that is being moved. /// </param> /// <param name="previousCustomerManagerLink"> /// Required. The resource name of the previous CustomerManagerLink. /// The resource name has the form: /// `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` /// </param> /// <param name="newManager"> /// Required. The resource name of the new manager customer that the client wants to move /// to. Customer resource names have the format: "customers/{customer_id}" /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MoveManagerLinkResponse> MoveManagerLinkAsync(string customerId, string previousCustomerManagerLink, string newManager, st::CancellationToken cancellationToken) => MoveManagerLinkAsync(customerId, previousCustomerManagerLink, newManager, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>CustomerManagerLinkService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage customer-manager links. /// </remarks> public sealed partial class CustomerManagerLinkServiceClientImpl : CustomerManagerLinkServiceClient { private readonly gaxgrpc::ApiCall<GetCustomerManagerLinkRequest, gagvr::CustomerManagerLink> _callGetCustomerManagerLink; private readonly gaxgrpc::ApiCall<MutateCustomerManagerLinkRequest, MutateCustomerManagerLinkResponse> _callMutateCustomerManagerLink; private readonly gaxgrpc::ApiCall<MoveManagerLinkRequest, MoveManagerLinkResponse> _callMoveManagerLink; /// <summary> /// Constructs a client wrapper for the CustomerManagerLinkService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="CustomerManagerLinkServiceSettings"/> used within this client. /// </param> public CustomerManagerLinkServiceClientImpl(CustomerManagerLinkService.CustomerManagerLinkServiceClient grpcClient, CustomerManagerLinkServiceSettings settings) { GrpcClient = grpcClient; CustomerManagerLinkServiceSettings effectiveSettings = settings ?? CustomerManagerLinkServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetCustomerManagerLink = clientHelper.BuildApiCall<GetCustomerManagerLinkRequest, gagvr::CustomerManagerLink>(grpcClient.GetCustomerManagerLinkAsync, grpcClient.GetCustomerManagerLink, effectiveSettings.GetCustomerManagerLinkSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetCustomerManagerLink); Modify_GetCustomerManagerLinkApiCall(ref _callGetCustomerManagerLink); _callMutateCustomerManagerLink = clientHelper.BuildApiCall<MutateCustomerManagerLinkRequest, MutateCustomerManagerLinkResponse>(grpcClient.MutateCustomerManagerLinkAsync, grpcClient.MutateCustomerManagerLink, effectiveSettings.MutateCustomerManagerLinkSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateCustomerManagerLink); Modify_MutateCustomerManagerLinkApiCall(ref _callMutateCustomerManagerLink); _callMoveManagerLink = clientHelper.BuildApiCall<MoveManagerLinkRequest, MoveManagerLinkResponse>(grpcClient.MoveManagerLinkAsync, grpcClient.MoveManagerLink, effectiveSettings.MoveManagerLinkSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMoveManagerLink); Modify_MoveManagerLinkApiCall(ref _callMoveManagerLink); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetCustomerManagerLinkApiCall(ref gaxgrpc::ApiCall<GetCustomerManagerLinkRequest, gagvr::CustomerManagerLink> call); partial void Modify_MutateCustomerManagerLinkApiCall(ref gaxgrpc::ApiCall<MutateCustomerManagerLinkRequest, MutateCustomerManagerLinkResponse> call); partial void Modify_MoveManagerLinkApiCall(ref gaxgrpc::ApiCall<MoveManagerLinkRequest, MoveManagerLinkResponse> call); partial void OnConstruction(CustomerManagerLinkService.CustomerManagerLinkServiceClient grpcClient, CustomerManagerLinkServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC CustomerManagerLinkService client</summary> public override CustomerManagerLinkService.CustomerManagerLinkServiceClient GrpcClient { get; } partial void Modify_GetCustomerManagerLinkRequest(ref GetCustomerManagerLinkRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateCustomerManagerLinkRequest(ref MutateCustomerManagerLinkRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MoveManagerLinkRequest(ref MoveManagerLinkRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested CustomerManagerLink in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::CustomerManagerLink GetCustomerManagerLink(GetCustomerManagerLinkRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetCustomerManagerLinkRequest(ref request, ref callSettings); return _callGetCustomerManagerLink.Sync(request, callSettings); } /// <summary> /// Returns the requested CustomerManagerLink in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::CustomerManagerLink> GetCustomerManagerLinkAsync(GetCustomerManagerLinkRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetCustomerManagerLinkRequest(ref request, ref callSettings); return _callGetCustomerManagerLink.Async(request, callSettings); } /// <summary> /// Creates or updates customer manager links. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [ManagerLinkError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateCustomerManagerLinkResponse MutateCustomerManagerLink(MutateCustomerManagerLinkRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateCustomerManagerLinkRequest(ref request, ref callSettings); return _callMutateCustomerManagerLink.Sync(request, callSettings); } /// <summary> /// Creates or updates customer manager links. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [ManagerLinkError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateCustomerManagerLinkResponse> MutateCustomerManagerLinkAsync(MutateCustomerManagerLinkRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateCustomerManagerLinkRequest(ref request, ref callSettings); return _callMutateCustomerManagerLink.Async(request, callSettings); } /// <summary> /// Moves a client customer to a new manager customer. /// This simplifies the complex request that requires two operations to move /// a client customer to a new manager. i.e: /// 1. Update operation with Status INACTIVE (previous manager) and, /// 2. Update operation with Status ACTIVE (new manager). /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MoveManagerLinkResponse MoveManagerLink(MoveManagerLinkRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MoveManagerLinkRequest(ref request, ref callSettings); return _callMoveManagerLink.Sync(request, callSettings); } /// <summary> /// Moves a client customer to a new manager customer. /// This simplifies the complex request that requires two operations to move /// a client customer to a new manager. i.e: /// 1. Update operation with Status INACTIVE (previous manager) and, /// 2. Update operation with Status ACTIVE (new manager). /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MoveManagerLinkResponse> MoveManagerLinkAsync(MoveManagerLinkRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MoveManagerLinkRequest(ref request, ref callSettings); return _callMoveManagerLink.Async(request, callSettings); } } }
//------------------------------------------------------------------------------ // <copyright file="DLFileEntryService.cs"> // Copyright (c) 2014-present Andrea Di Giorgi // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // </copyright> // <author>Andrea Di Giorgi</author> // <website>https://github.com/Ithildir/liferay-sdk-builder-windows</website> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Liferay.SDK.Service.V62.DLFileEntry { public class DLFileEntryService : ServiceBase { public DLFileEntryService(ISession session) : base(session) { } public async Task<dynamic> CancelCheckOutAsync(long fileEntryId) { var _parameters = new JsonObject(); _parameters.Add("fileEntryId", fileEntryId); var _command = new JsonObject() { { "/dlfileentry/cancel-check-out", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task CheckInFileEntryAsync(long fileEntryId, string lockUuid) { var _parameters = new JsonObject(); _parameters.Add("fileEntryId", fileEntryId); _parameters.Add("lockUuid", lockUuid); var _command = new JsonObject() { { "/dlfileentry/check-in-file-entry", _parameters } }; await this.Session.InvokeAsync(_command); } public async Task CheckInFileEntryAsync(long fileEntryId, string lockUuid, JsonObjectWrapper serviceContext) { var _parameters = new JsonObject(); _parameters.Add("fileEntryId", fileEntryId); _parameters.Add("lockUuid", lockUuid); this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext); var _command = new JsonObject() { { "/dlfileentry/check-in-file-entry", _parameters } }; await this.Session.InvokeAsync(_command); } public async Task CheckInFileEntryAsync(long fileEntryId, bool major, string changeLog, JsonObjectWrapper serviceContext) { var _parameters = new JsonObject(); _parameters.Add("fileEntryId", fileEntryId); _parameters.Add("major", major); _parameters.Add("changeLog", changeLog); this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext); var _command = new JsonObject() { { "/dlfileentry/check-in-file-entry", _parameters } }; await this.Session.InvokeAsync(_command); } public async Task<dynamic> CheckOutFileEntryAsync(long fileEntryId) { var _parameters = new JsonObject(); _parameters.Add("fileEntryId", fileEntryId); var _command = new JsonObject() { { "/dlfileentry/check-out-file-entry", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> CheckOutFileEntryAsync(long fileEntryId, JsonObjectWrapper serviceContext) { var _parameters = new JsonObject(); _parameters.Add("fileEntryId", fileEntryId); this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext); var _command = new JsonObject() { { "/dlfileentry/check-out-file-entry", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> CheckOutFileEntryAsync(long fileEntryId, string owner, long expirationTime) { var _parameters = new JsonObject(); _parameters.Add("fileEntryId", fileEntryId); _parameters.Add("owner", owner); _parameters.Add("expirationTime", expirationTime); var _command = new JsonObject() { { "/dlfileentry/check-out-file-entry", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> CheckOutFileEntryAsync(long fileEntryId, string owner, long expirationTime, JsonObjectWrapper serviceContext) { var _parameters = new JsonObject(); _parameters.Add("fileEntryId", fileEntryId); _parameters.Add("owner", owner); _parameters.Add("expirationTime", expirationTime); this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext); var _command = new JsonObject() { { "/dlfileentry/check-out-file-entry", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> CopyFileEntryAsync(long groupId, long repositoryId, long fileEntryId, long destFolderId, JsonObjectWrapper serviceContext) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("repositoryId", repositoryId); _parameters.Add("fileEntryId", fileEntryId); _parameters.Add("destFolderId", destFolderId); this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext); var _command = new JsonObject() { { "/dlfileentry/copy-file-entry", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task DeleteFileEntryAsync(long fileEntryId) { var _parameters = new JsonObject(); _parameters.Add("fileEntryId", fileEntryId); var _command = new JsonObject() { { "/dlfileentry/delete-file-entry", _parameters } }; await this.Session.InvokeAsync(_command); } public async Task DeleteFileEntryAsync(long groupId, long folderId, string title) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("folderId", folderId); _parameters.Add("title", title); var _command = new JsonObject() { { "/dlfileentry/delete-file-entry", _parameters } }; await this.Session.InvokeAsync(_command); } public async Task DeleteFileVersionAsync(long fileEntryId, string version) { var _parameters = new JsonObject(); _parameters.Add("fileEntryId", fileEntryId); _parameters.Add("version", version); var _command = new JsonObject() { { "/dlfileentry/delete-file-version", _parameters } }; await this.Session.InvokeAsync(_command); } public async Task<dynamic> FetchFileEntryByImageIdAsync(long imageId) { var _parameters = new JsonObject(); _parameters.Add("imageId", imageId); var _command = new JsonObject() { { "/dlfileentry/fetch-file-entry-by-image-id", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<IEnumerable<dynamic>> GetFileEntriesAsync(long groupId, long folderId, int start, int end, JsonObjectWrapper obc) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("folderId", folderId); _parameters.Add("start", start); _parameters.Add("end", end); this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc); var _command = new JsonObject() { { "/dlfileentry/get-file-entries", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (IEnumerable<dynamic>)_obj; } public async Task<IEnumerable<dynamic>> GetFileEntriesAsync(long groupId, long folderId, long fileEntryTypeId, int start, int end, JsonObjectWrapper obc) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("folderId", folderId); _parameters.Add("fileEntryTypeId", fileEntryTypeId); _parameters.Add("start", start); _parameters.Add("end", end); this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc); var _command = new JsonObject() { { "/dlfileentry/get-file-entries", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (IEnumerable<dynamic>)_obj; } public async Task<IEnumerable<dynamic>> GetFileEntriesAsync(long groupId, long folderId, IEnumerable<string> mimeTypes, int start, int end, JsonObjectWrapper obc) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("folderId", folderId); _parameters.Add("mimeTypes", mimeTypes); _parameters.Add("start", start); _parameters.Add("end", end); this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc); var _command = new JsonObject() { { "/dlfileentry/get-file-entries", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (IEnumerable<dynamic>)_obj; } public async Task<IEnumerable<dynamic>> GetFileEntriesAsync(long groupId, long folderId, int status, int start, int end, JsonObjectWrapper obc) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("folderId", folderId); _parameters.Add("status", status); _parameters.Add("start", start); _parameters.Add("end", end); this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc); var _command = new JsonObject() { { "/dlfileentry/get-file-entries", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (IEnumerable<dynamic>)_obj; } public async Task<long> GetFileEntriesCountAsync(long groupId, long folderId) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("folderId", folderId); var _command = new JsonObject() { { "/dlfileentry/get-file-entries-count", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (long)_obj; } public async Task<long> GetFileEntriesCountAsync(long groupId, long folderId, long fileEntryTypeId) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("folderId", folderId); _parameters.Add("fileEntryTypeId", fileEntryTypeId); var _command = new JsonObject() { { "/dlfileentry/get-file-entries-count", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (long)_obj; } public async Task<long> GetFileEntriesCountAsync(long groupId, long folderId, IEnumerable<string> mimeTypes) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("folderId", folderId); _parameters.Add("mimeTypes", mimeTypes); var _command = new JsonObject() { { "/dlfileentry/get-file-entries-count", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (long)_obj; } public async Task<long> GetFileEntriesCountAsync(long groupId, long folderId, int status) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("folderId", folderId); _parameters.Add("status", status); var _command = new JsonObject() { { "/dlfileentry/get-file-entries-count", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (long)_obj; } public async Task<dynamic> GetFileEntryAsync(long fileEntryId) { var _parameters = new JsonObject(); _parameters.Add("fileEntryId", fileEntryId); var _command = new JsonObject() { { "/dlfileentry/get-file-entry", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> GetFileEntryAsync(long groupId, long folderId, string title) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("folderId", folderId); _parameters.Add("title", title); var _command = new JsonObject() { { "/dlfileentry/get-file-entry", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> GetFileEntryByUuidAndGroupIdAsync(string uuid, long groupId) { var _parameters = new JsonObject(); _parameters.Add("uuid", uuid); _parameters.Add("groupId", groupId); var _command = new JsonObject() { { "/dlfileentry/get-file-entry-by-uuid-and-group-id", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> GetFileEntryLockAsync(long fileEntryId) { var _parameters = new JsonObject(); _parameters.Add("fileEntryId", fileEntryId); var _command = new JsonObject() { { "/dlfileentry/get-file-entry-lock", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<long> GetFoldersFileEntriesCountAsync(long groupId, IEnumerable<object> folderIds, int status) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("folderIds", folderIds); _parameters.Add("status", status); var _command = new JsonObject() { { "/dlfileentry/get-folders-file-entries-count", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (long)_obj; } public async Task<IEnumerable<dynamic>> GetGroupFileEntriesAsync(long groupId, long userId, long rootFolderId, int start, int end, JsonObjectWrapper obc) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("userId", userId); _parameters.Add("rootFolderId", rootFolderId); _parameters.Add("start", start); _parameters.Add("end", end); this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc); var _command = new JsonObject() { { "/dlfileentry/get-group-file-entries", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (IEnumerable<dynamic>)_obj; } public async Task<IEnumerable<dynamic>> GetGroupFileEntriesAsync(long groupId, long userId, long rootFolderId, IEnumerable<string> mimeTypes, int status, int start, int end, JsonObjectWrapper obc) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("userId", userId); _parameters.Add("rootFolderId", rootFolderId); _parameters.Add("mimeTypes", mimeTypes); _parameters.Add("status", status); _parameters.Add("start", start); _parameters.Add("end", end); this.MangleWrapper(_parameters, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc); var _command = new JsonObject() { { "/dlfileentry/get-group-file-entries", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (IEnumerable<dynamic>)_obj; } public async Task<long> GetGroupFileEntriesCountAsync(long groupId, long userId, long rootFolderId) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("userId", userId); _parameters.Add("rootFolderId", rootFolderId); var _command = new JsonObject() { { "/dlfileentry/get-group-file-entries-count", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (long)_obj; } public async Task<long> GetGroupFileEntriesCountAsync(long groupId, long userId, long rootFolderId, IEnumerable<string> mimeTypes, int status) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("userId", userId); _parameters.Add("rootFolderId", rootFolderId); _parameters.Add("mimeTypes", mimeTypes); _parameters.Add("status", status); var _command = new JsonObject() { { "/dlfileentry/get-group-file-entries-count", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (long)_obj; } public async Task<bool> HasFileEntryLockAsync(long fileEntryId) { var _parameters = new JsonObject(); _parameters.Add("fileEntryId", fileEntryId); var _command = new JsonObject() { { "/dlfileentry/has-file-entry-lock", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (bool)_obj; } public async Task<bool> IsFileEntryCheckedOutAsync(long fileEntryId) { var _parameters = new JsonObject(); _parameters.Add("fileEntryId", fileEntryId); var _command = new JsonObject() { { "/dlfileentry/is-file-entry-checked-out", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (bool)_obj; } public async Task<dynamic> MoveFileEntryAsync(long fileEntryId, long newFolderId, JsonObjectWrapper serviceContext) { var _parameters = new JsonObject(); _parameters.Add("fileEntryId", fileEntryId); _parameters.Add("newFolderId", newFolderId); this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext); var _command = new JsonObject() { { "/dlfileentry/move-file-entry", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> RefreshFileEntryLockAsync(string lockUuid, long companyId, long expirationTime) { var _parameters = new JsonObject(); _parameters.Add("lockUuid", lockUuid); _parameters.Add("companyId", companyId); _parameters.Add("expirationTime", expirationTime); var _command = new JsonObject() { { "/dlfileentry/refresh-file-entry-lock", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task RevertFileEntryAsync(long fileEntryId, string version, JsonObjectWrapper serviceContext) { var _parameters = new JsonObject(); _parameters.Add("fileEntryId", fileEntryId); _parameters.Add("version", version); this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext); var _command = new JsonObject() { { "/dlfileentry/revert-file-entry", _parameters } }; await this.Session.InvokeAsync(_command); } public async Task<dynamic> SearchAsync(long groupId, long creatorUserId, int status, int start, int end) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("creatorUserId", creatorUserId); _parameters.Add("status", status); _parameters.Add("start", start); _parameters.Add("end", end); var _command = new JsonObject() { { "/dlfileentry/search", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> SearchAsync(long groupId, long creatorUserId, long folderId, IEnumerable<string> mimeTypes, int status, int start, int end) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("creatorUserId", creatorUserId); _parameters.Add("folderId", folderId); _parameters.Add("mimeTypes", mimeTypes); _parameters.Add("status", status); _parameters.Add("start", start); _parameters.Add("end", end); var _command = new JsonObject() { { "/dlfileentry/search", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<bool> VerifyFileEntryCheckOutAsync(long fileEntryId, string lockUuid) { var _parameters = new JsonObject(); _parameters.Add("fileEntryId", fileEntryId); _parameters.Add("lockUuid", lockUuid); var _command = new JsonObject() { { "/dlfileentry/verify-file-entry-check-out", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (bool)_obj; } public async Task<bool> VerifyFileEntryLockAsync(long fileEntryId, string lockUuid) { var _parameters = new JsonObject(); _parameters.Add("fileEntryId", fileEntryId); _parameters.Add("lockUuid", lockUuid); var _command = new JsonObject() { { "/dlfileentry/verify-file-entry-lock", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (bool)_obj; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace StudentWebApiCorsLab.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using Baseline; using LamarCodeGeneration; using LamarCodeGeneration.Frames; using LamarCodeGeneration.Model; using LamarCompiler; using Marten.Events.CodeGeneration; using Marten.Events.Daemon; using Marten.Events.Projections; using Marten.Exceptions; using Marten.Internal; using Marten.Internal.CodeGeneration; using Marten.Internal.Storage; using Marten.Linq.SqlGeneration; using Marten.Schema; using Marten.Storage; namespace Marten.Events.Aggregation { public partial class AggregateProjection<T> : ProjectionSource, ILiveAggregatorSource<T> { private GeneratedType _liveType; private GeneratedType _inlineType; private DocumentMapping _aggregateMapping; private readonly CreateMethodCollection _createMethods; private readonly ApplyMethodCollection _applyMethods; private readonly ShouldDeleteMethodCollection _shouldDeleteMethods; private bool _isAsync; private GeneratedAssembly _assembly; private Type _storageType; private readonly Lazy<Type[]> _allEventTypes; private IAggregationRuntime _runtime; public AggregateProjection() : base(typeof(T).NameInCode()) { _createMethods = new CreateMethodCollection(GetType(), typeof(T)); _applyMethods = new ApplyMethodCollection(GetType(), typeof(T)); _shouldDeleteMethods = new ShouldDeleteMethodCollection(GetType(), typeof(T)); ProjectionName = typeof(T).Name; Options.DeleteViewTypeOnTeardown<T>(); _allEventTypes = new Lazy<Type[]>(() => { return _createMethods.Methods.Concat(_applyMethods.Methods).Concat(_shouldDeleteMethods.Methods) .Select(x => x.EventType).Concat(DeleteEvents).Distinct().ToArray(); }); } public override Type ProjectionType => GetType(); public bool AppliesTo(IEnumerable<Type> eventTypes) { return eventTypes .Intersect(AllEventTypes).Any() || eventTypes.Any(type => AllEventTypes.Any(type.CanBeCastTo)); } public Type[] AllEventTypes => _allEventTypes.Value; Type IAggregateProjection.AggregateType => typeof(T); internal override IProjection Build(DocumentStore store) { if (_inlineType == null) { Compile(store.Options); } // This will have to change when we introduce 1st class support for tenancy by // separate databases store.Tenancy.Default.EnsureStorageExists(typeof(T)); return BuildRuntime(store); } internal ILiveAggregator<T> BuildLiveAggregator() { var aggregator = (ILiveAggregator<T>)Activator.CreateInstance(_liveType.CompiledType, this); _liveType.ApplySetterValues(aggregator); return aggregator; } internal IAggregationRuntime BuildRuntime(DocumentStore store) { if (_liveType == null) { Compile(store.Options); } var storage = store.Options.Providers.StorageFor<T>().Lightweight; var slicer = buildEventSlicer(); var ctor = _inlineType.CompiledType.GetConstructors().Single(); foreach (var parameter in ctor.GetParameters()) { Debug.WriteLine(parameter.ParameterType.NameInCode()); } var inline = (IAggregationRuntime)Activator.CreateInstance(_inlineType.CompiledType, store, this, slicer, store.Options.Tenancy, storage, this); _inlineType.ApplySetterValues(inline); return inline; } protected virtual object buildEventSlicer() { Type slicerType = null; if (_aggregateMapping.IdType == typeof(Guid)) { slicerType = typeof(ByStreamId<>).MakeGenericType(_aggregateMapping.DocumentType); } else if (_aggregateMapping.IdType != typeof(string)) { throw new ArgumentOutOfRangeException( $"{_aggregateMapping.IdType.FullNameInCode()} is not a supported stream id type for aggregate {_aggregateMapping.DocumentType.FullNameInCode()}"); } else { slicerType = typeof(ByStreamKey<>).MakeGenericType(_aggregateMapping.DocumentType); } return Activator.CreateInstance(slicerType); } internal string SourceCode() { var writer = new StringWriter(); writer.WriteLine(_liveType.SourceCode); writer.WriteLine(); writer.WriteLine(_inlineType.SourceCode); writer.WriteLine(); return writer.ToString(); } internal GeneratedAssembly Compile(StoreOptions options) { _assembly = new GeneratedAssembly(new GenerationRules("Marten.Generated")); _assembly.Generation.Assemblies.Add(GetType().Assembly); _assembly.Generation.Assemblies.Add(typeof(T).Assembly); _assembly.Generation.Assemblies.AddRange(_applyMethods.ReferencedAssemblies()); _assembly.Generation.Assemblies.AddRange(_createMethods.ReferencedAssemblies()); _assembly.Generation.Assemblies.AddRange(_shouldDeleteMethods.ReferencedAssemblies()); _assembly.Namespaces.Add("System"); _assembly.Namespaces.Add("System.Linq"); _isAsync = _createMethods.IsAsync || _applyMethods.IsAsync; _aggregateMapping = options.Storage.MappingFor(typeof(T)); if (_aggregateMapping.IdMember == null) { // TODO -- possibly try to relax this!!! throw new InvalidDocumentException( $"No identity property or field can be determined for the aggregate '{typeof(T).FullNameInCode()}', but one is required to be used as an aggregate in projections"); } _storageType = typeof(IDocumentStorage<,>).MakeGenericType(typeof(T), _aggregateMapping.IdType); // TODO -- Validate the id strategy for the mapping // against the aggregation setup buildLiveAggregationType(); buildInlineAggregationType(); var assemblyGenerator = new AssemblyGenerator(); assemblyGenerator.ReferenceAssembly(typeof(IMartenSession).Assembly); assemblyGenerator.Compile(_assembly); Debug.WriteLine(_liveType.SourceCode); return _assembly; } private void buildInlineAggregationType() { var inlineBaseType = typeof(AggregationRuntime<,>).MakeGenericType(typeof(T), _aggregateMapping.IdType); _inlineType = _assembly.AddType(GetType().NameInCode().Sanitize() + "InlineHandler", inlineBaseType); _createMethods.BuildCreateMethod(_inlineType, _aggregateMapping); _inlineType.AllInjectedFields.Add(new InjectedField(GetType())); buildApplyEventMethod(); _inlineType.Setters.AddRange(_applyMethods.Setters()); _inlineType.Setters.AddRange(_createMethods.Setters()); _inlineType.Setters.AddRange(_shouldDeleteMethods.Setters()); } private GeneratedMethod buildApplyEventMethod() { var method = _inlineType.MethodFor(nameof(AggregationRuntime<string, string>.ApplyEvent)); // This gets you the EventSlice aggregate Id method.DerivedVariables.Add(new Variable(_aggregateMapping.IdType, $"slice.{nameof(EventSlice<string, string>.Id)}")); method.DerivedVariables.Add(Variable.For<ITenant>($"slice.{nameof(EventSlice<string, string>.Tenant)}")); method.DerivedVariables.Add(Variable.For<ITenant>($"slice.{nameof(EventSlice<string, string>.Tenant)}")); method.DerivedVariables.Add(Variable.For<IEvent>("@event")); method.DerivedVariables.Add(Variable.For<IMartenSession>($"({typeof(IMartenSession).FullNameInCode()})session")); method.DerivedVariables.Add(Variable.For<IQuerySession>("session")); method.DerivedVariables.Add( Variable.For<IAggregateProjection>(nameof(AggregationRuntime<string, string>.Projection))); var eventHandlers = new LightweightCache<Type, AggregateEventProcessingFrame>( eventType => new AggregateEventProcessingFrame(typeof(T), eventType)); foreach (var deleteEvent in DeleteEvents) { eventHandlers[deleteEvent].AlwaysDeletes = true; } foreach (var slot in _applyMethods.Methods) { eventHandlers[slot.EventType].Apply = new ApplyMethodCall(slot); } foreach (var slot in _createMethods.Methods) { eventHandlers[slot.EventType].CreationFrame = slot.Method is ConstructorInfo ? (Frame)new AggregateConstructorFrame(slot) : new CreateAggregateFrame(slot); } foreach (var slot in _shouldDeleteMethods.Methods) { eventHandlers[slot.EventType].Deletion = new MaybeDeleteFrame(slot); } var patternMatching = new EventTypePatternMatchFrame(eventHandlers.OfType<EventProcessingFrame>().ToList()); method.Frames.Add(patternMatching); method.Frames.Code($"return aggregate;"); return method; } private void buildLiveAggregationType() { var liveBaseType = _isAsync ? typeof(AsyncLiveAggregatorBase<>) : typeof(SyncLiveAggregatorBase<>); liveBaseType = liveBaseType.MakeGenericType(typeof(T)); _liveType = _assembly.AddType(GetType().NameInCode().Sanitize() + "LiveAggregation", liveBaseType); var overrideMethodName = _isAsync ? "BuildAsync" : "Build"; var buildMethod = _liveType.MethodFor(overrideMethodName); buildMethod.DerivedVariables.Add(Variable.For<IQuerySession>("(IQuerySession)session")); buildMethod.Frames.Code("if (!events.Any()) return null;"); buildMethod.Frames.Add(new DeclareAggregateFrame(typeof(T))); var callCreateAggregateFrame = new CallCreateAggregateFrame(_createMethods); // This is the existing snapshot passed into the LiveAggregator var snapshot = buildMethod.Arguments.Single(x => x.VariableType == typeof(T)); callCreateAggregateFrame.CoalesceAssignTo(snapshot); buildMethod.Frames.Add(callCreateAggregateFrame); buildMethod.Frames.Add(new CallApplyAggregateFrame(_applyMethods){InsideForEach = true}); buildMethod.Frames.Return(typeof(T)); _liveType.AllInjectedFields.Add(new InjectedField(GetType())); _createMethods.BuildCreateMethod(_liveType, _aggregateMapping); _applyMethods.BuildApplyMethod(_liveType, _aggregateMapping); _liveType.Setters.AddRange(_applyMethods.Setters()); _liveType.Setters.AddRange(_createMethods.Setters()); _liveType.Setters.AddRange(_shouldDeleteMethods.Setters()); } public ILiveAggregator<T> Build(StoreOptions options) { if (_liveType == null) { Compile(options); } return BuildLiveAggregator(); } internal override void AssertValidity() { if (_applyMethods.IsEmpty() && _createMethods.IsEmpty()) { throw new InvalidProjectionException( $"AggregateProjection for {typeof(T).FullNameInCode()} has no valid create or apply operations"); } var invalidMethods = MethodCollection.FindInvalidMethods(GetType(), _applyMethods, _createMethods, _shouldDeleteMethods); if (invalidMethods.Any()) { throw new InvalidProjectionException(this, invalidMethods); } specialAssertValid(); } protected virtual void specialAssertValid() { } internal override IEnumerable<string> ValidateConfiguration(StoreOptions options) { var mapping = options.Storage.MappingFor(typeof(T)); foreach (var p in validateDocumentIdentity(options, mapping)) yield return p; if (options.Events.TenancyStyle != mapping.TenancyStyle) { yield return $"Tenancy storage style mismatch between the events ({options.Events.TenancyStyle}) and the aggregate type {typeof(T).FullNameInCode()} ({mapping.TenancyStyle})"; } } protected virtual IEnumerable<string> validateDocumentIdentity(StoreOptions options, DocumentMapping mapping) { if (options.Events.StreamIdentity == StreamIdentity.AsGuid) { if (mapping.IdType != typeof(Guid)) { yield return $"Id type mismatch. The stream identity type is System.Guid, but the aggregate document {typeof(T).FullNameInCode()} id type is {mapping.IdType.NameInCode()}"; } } if (options.Events.StreamIdentity == StreamIdentity.AsString) { if (mapping.IdType != typeof(string)) { yield return $"Id type mismatch. The stream identity type is string, but the aggregate document {typeof(T).FullNameInCode()} id type is {mapping.IdType.NameInCode()}"; } } } internal override IReadOnlyList<AsyncProjectionShard> AsyncProjectionShards(DocumentStore store) { // TODO -- support sharding _runtime = BuildRuntime(store); var eventTypes = determineEventTypes(); var baseFilters = new ISqlFragment[0]; if (!eventTypes.Any(x => x.IsAbstract || x.IsInterface)) { baseFilters = new ISqlFragment[] {new Marten.Events.Daemon.EventTypeFilter(store.Events, eventTypes)}; } return new List<AsyncProjectionShard> {new(this, baseFilters)}; } protected virtual Type[] determineEventTypes() { var eventTypes = MethodCollection.AllEventTypes(_applyMethods, _createMethods, _shouldDeleteMethods) .Concat(DeleteEvents).Distinct().ToArray(); return eventTypes; } internal override EventRangeGroup GroupEvents(DocumentStore store, EventRange range, CancellationToken cancellationToken) { _runtime ??= BuildRuntime(store); return _runtime.GroupEvents(store, range, cancellationToken); } } }
// // SourceManager.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2005-2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Mono.Unix; using Mono.Addins; using Hyena; using Banshee.ServiceStack; using Banshee.Library; namespace Banshee.Sources { public delegate void SourceEventHandler(SourceEventArgs args); public delegate void SourceAddedHandler(SourceAddedArgs args); public class SourceEventArgs : EventArgs { public Source Source; } public class SourceAddedArgs : SourceEventArgs { public int Position; } public class SourceManager : /*ISourceManager,*/ IInitializeService, IRequiredService, IDBusExportable, IDisposable { private List<Source> sources = new List<Source>(); private List<GroupSource> group_sources = new List<GroupSource> (); private Dictionary<string, Source> extension_sources = new Dictionary<string, Source> (); private Source active_source; private Source default_source; private MusicLibrarySource music_library; private VideoLibrarySource video_library; public event SourceEventHandler SourceUpdated; public event SourceAddedHandler SourceAdded; public event SourceEventHandler SourceRemoved; public event SourceEventHandler ActiveSourceChanged; public class GroupSource : Source { public GroupSource (string name, int order) : base (name, name, order) { } } public void Initialize () { // TODO should add library sources here, but requires changing quite a few // things that depend on being loaded before the music library is added. //AddSource (music_library = new MusicLibrarySource (), true); //AddSource (video_library = new VideoLibrarySource (), false); group_sources.Add (new GroupSource (Catalog.GetString ("Online Media"), 60)); group_sources.Add (new GroupSource (Catalog.GetString ("Libraries"), 39)); } internal void LoadExtensionSources () { lock (this) { AddinManager.AddExtensionNodeHandler ("/Banshee/SourceManager/Source", OnExtensionChanged); } } public void Dispose () { lock (this) { try { AddinManager.RemoveExtensionNodeHandler ("/Banshee/SourceManager/Source", OnExtensionChanged); } catch {} active_source = null; default_source = null; music_library = null; video_library = null; // Do dispose extension sources foreach (Source source in extension_sources.Values) { RemoveSource (source, true); } // But do not dispose non-extension sources while (sources.Count > 0) { RemoveSource (sources[0], false); } sources.Clear (); extension_sources.Clear (); } } private void OnExtensionChanged (object o, ExtensionNodeEventArgs args) { lock (this) { TypeExtensionNode node = (TypeExtensionNode)args.ExtensionNode; if (args.Change == ExtensionChange.Add && !extension_sources.ContainsKey (node.Id)) { try { Source source = (Source)node.CreateInstance (); extension_sources.Add (node.Id, source); if (source.Properties.Get<bool> ("AutoAddSource", true)) { AddSource (source); } Log.DebugFormat ("Extension source loaded: {0}", source.Name); } catch {} } else if (args.Change == ExtensionChange.Remove && extension_sources.ContainsKey (node.Id)) { Source source = extension_sources[node.Id]; extension_sources.Remove (node.Id); RemoveSource (source, true); Log.DebugFormat ("Extension source unloaded: {0}", source.Name); } } } public void AddSource(Source source) { AddSource(source, false); } public void AddSource(Source source, bool isDefault) { ThreadAssist.AssertInMainThread (); if(source == null || ContainsSource (source)) { return; } GroupSource group_source = source as GroupSource; if (group_source != null && !group_sources.Contains (group_source)) { group_sources.Add (group_source); return; } AddSource (FindAssociatedGroupSource (source.Order)); int position = FindSourceInsertPosition(source); sources.Insert(position, source); if(isDefault) { default_source = source; } source.Updated += OnSourceUpdated; source.ChildSourceAdded += OnChildSourceAdded; source.ChildSourceRemoved += OnChildSourceRemoved; if (source is MusicLibrarySource) { music_library = source as MusicLibrarySource; } else if (source is VideoLibrarySource) { video_library = source as VideoLibrarySource; } SourceAdded.SafeInvoke (new SourceAddedArgs () { Position = position, Source = source }); IDBusExportable exportable = source as IDBusExportable; if (exportable != null) { ServiceManager.DBusServiceManager.RegisterObject (exportable); } List<Source> children = new List<Source> (source.Children); foreach(Source child_source in children) { AddSource (child_source, false); } if(isDefault && ActiveSource == null) { SetActiveSource(source); } } public void RemoveSource (Source source) { RemoveSource (source, false); } public void RemoveSource (Source source, bool recursivelyDispose) { if(source == null || !ContainsSource (source)) { return; } if(source == default_source) { default_source = null; } source.Updated -= OnSourceUpdated; source.ChildSourceAdded -= OnChildSourceAdded; source.ChildSourceRemoved -= OnChildSourceRemoved; sources.Remove(source); GroupSource associated_groupsource = FindAssociatedGroupSource (source.Order); if (!GroupSourceHasMembers (associated_groupsource)) { RemoveSource (associated_groupsource, recursivelyDispose); } foreach(Source child_source in source.Children) { RemoveSource (child_source, recursivelyDispose); } IDBusExportable exportable = source as IDBusExportable; if (exportable != null) { ServiceManager.DBusServiceManager.UnregisterObject (exportable); } if (recursivelyDispose) { IDisposable disposable = source as IDisposable; if (disposable != null) { disposable.Dispose (); } } ThreadAssist.ProxyToMain (delegate { if(source == active_source) { if (source.Parent != null && source.Parent.CanActivate) { SetActiveSource(source.Parent); } else { SetActiveSource(default_source); } } SourceEventHandler handler = SourceRemoved; if(handler != null) { SourceEventArgs args = new SourceEventArgs(); args.Source = source; handler(args); } }); } public void RemoveSource(Type type) { Queue<Source> remove_queue = new Queue<Source>(); foreach(Source source in Sources) { if(source.GetType() == type) { remove_queue.Enqueue(source); } } while(remove_queue.Count > 0) { RemoveSource(remove_queue.Dequeue()); } } public bool ContainsSource(Source source) { return sources.Contains(source); } private void OnSourceUpdated(object o, EventArgs args) { ThreadAssist.ProxyToMain (delegate { SourceEventHandler handler = SourceUpdated; if(handler != null) { SourceEventArgs evargs = new SourceEventArgs(); evargs.Source = o as Source; handler(evargs); } }); } private void OnChildSourceAdded(SourceEventArgs args) { AddSource (args.Source); } private void OnChildSourceRemoved(SourceEventArgs args) { RemoveSource (args.Source); } private GroupSource FindAssociatedGroupSource (int order) { int current_order = -1; GroupSource associated_groupsource = null; foreach (GroupSource source in group_sources){ if (order == source.Order) { return null; } if (order > source.Order && current_order < source.Order) { associated_groupsource = source; current_order = source.Order; } } return associated_groupsource; } private bool GroupSourceHasMembers (GroupSource group_source) { Source source = group_source as Source; if (group_source == null || !sources.Contains (source)) { return false; } int source_index = FindSourceInsertPosition (source); if (source_index < sources.Count - 1) { Source next_source = sources[source_index + 1]; GroupSource associated_groupsource = FindAssociatedGroupSource (next_source.Order); return group_source.Equals (associated_groupsource); } else { return false; } } private int FindSourceInsertPosition(Source source) { for(int i = sources.Count - 1; i >= 0; i--) { if((sources[i] as Source).Order == source.Order) { return i; } } for(int i = 0; i < sources.Count; i++) { if((sources[i] as Source).Order >= source.Order) { return i; } } return sources.Count; } public Source DefaultSource { get { return default_source; } set { default_source = value; } } public MusicLibrarySource MusicLibrary { get { return music_library; } } public VideoLibrarySource VideoLibrary { get { return video_library; } } public Source ActiveSource { get { return active_source; } } /*ISource ISourceManager.DefaultSource { get { return DefaultSource; } } ISource ISourceManager.ActiveSource { get { return ActiveSource; } set { value.Activate (); } }*/ public void SetActiveSource(Source source) { SetActiveSource(source, true); } public void SetActiveSource(Source source, bool notify) { ThreadAssist.AssertInMainThread (); if(source == null || !source.CanActivate || active_source == source) { return; } if(active_source != null) { active_source.Deactivate(); } active_source = source; if (source.Parent != null) { source.Parent.Expanded = true; } if(!notify) { source.Activate(); return; } SourceEventHandler handler = ActiveSourceChanged; if(handler != null) { SourceEventArgs args = new SourceEventArgs(); args.Source = active_source; handler(args); } source.Activate(); } public IEnumerable<T> FindSources<T> () where T : Source { foreach (Source source in Sources) { T t_source = source as T; if (t_source != null) { yield return t_source; } } } public ICollection<Source> Sources { get { return sources; } } /*string [] ISourceManager.Sources { get { return DBusServiceManager.MakeObjectPathArray<Source>(sources); } }*/ IDBusExportable IDBusExportable.Parent { get { return null; } } string Banshee.ServiceStack.IService.ServiceName { get { return "SourceManager"; } } } }
using System; using System.Globalization; using System.Net; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using Abp.Application.Features; using Abp.Authorization; using Abp.Configuration; using Abp.Domain.Entities; using Abp.Domain.Uow; using Abp.Events.Bus; using Abp.Events.Bus.Exceptions; using Abp.Localization; using Abp.Localization.Sources; using Abp.Logging; using Abp.Reflection; using Abp.Runtime.Session; using Abp.Web.Models; using Abp.Web.Mvc.Configuration; using Abp.Web.Mvc.Controllers.Results; using Abp.Web.Mvc.Extensions; using Abp.Web.Mvc.Helpers; using Abp.Web.Mvc.Models; using Castle.Core.Logging; namespace Abp.Web.Mvc.Controllers { /// <summary> /// Base class for all MVC Controllers in Abp system. /// </summary> public abstract class AbpController : Controller { /// <summary> /// Gets current session information. /// </summary> public IAbpSession AbpSession { get; set; } /// <summary> /// Gets the event bus. /// </summary> public IEventBus EventBus { get; set; } /// <summary> /// Reference to the permission manager. /// </summary> public IPermissionManager PermissionManager { get; set; } /// <summary> /// Reference to the setting manager. /// </summary> public ISettingManager SettingManager { get; set; } /// <summary> /// Reference to the permission checker. /// </summary> public IPermissionChecker PermissionChecker { protected get; set; } /// <summary> /// Reference to the feature manager. /// </summary> public IFeatureManager FeatureManager { protected get; set; } /// <summary> /// Reference to the permission checker. /// </summary> public IFeatureChecker FeatureChecker { protected get; set; } /// <summary> /// Reference to the localization manager. /// </summary> public ILocalizationManager LocalizationManager { protected get; set; } /// <summary> /// Reference to the error info builder. /// </summary> public IErrorInfoBuilder ErrorInfoBuilder { protected get; set; } /// <summary> /// Gets/sets name of the localization source that is used in this application service. /// It must be set in order to use <see cref="L(string)"/> and <see cref="L(string,CultureInfo)"/> methods. /// </summary> protected string LocalizationSourceName { get; set; } /// <summary> /// Gets localization source. /// It's valid if <see cref="LocalizationSourceName"/> is set. /// </summary> protected ILocalizationSource LocalizationSource { get { if (LocalizationSourceName == null) { throw new AbpException("Must set LocalizationSourceName before, in order to get LocalizationSource"); } if (_localizationSource == null || _localizationSource.Name != LocalizationSourceName) { _localizationSource = LocalizationManager.GetSource(LocalizationSourceName); } return _localizationSource; } } private ILocalizationSource _localizationSource; /// <summary> /// Reference to the logger to write logs. /// </summary> public ILogger Logger { get; set; } /// <summary> /// Reference to <see cref="IUnitOfWorkManager"/>. /// </summary> public IUnitOfWorkManager UnitOfWorkManager { get { if (_unitOfWorkManager == null) { throw new AbpException("Must set UnitOfWorkManager before use it."); } return _unitOfWorkManager; } set { _unitOfWorkManager = value; } } private IUnitOfWorkManager _unitOfWorkManager; /// <summary> /// Gets current unit of work. /// </summary> protected IActiveUnitOfWork CurrentUnitOfWork { get { return UnitOfWorkManager.Current; } } public IAbpMvcConfiguration AbpMvcConfiguration { get; set; } /// <summary> /// MethodInfo for currently executing action. /// </summary> private MethodInfo _currentMethodInfo; /// <summary> /// WrapResultAttribute for currently executing action. /// </summary> private WrapResultAttribute _wrapResultAttribute; /// <summary> /// Constructor. /// </summary> protected AbpController() { AbpSession = NullAbpSession.Instance; Logger = NullLogger.Instance; LocalizationManager = NullLocalizationManager.Instance; PermissionChecker = NullPermissionChecker.Instance; EventBus = NullEventBus.Instance; } /// <summary> /// Gets localized string for given key name and current language. /// </summary> /// <param name="name">Key name</param> /// <returns>Localized string</returns> protected virtual string L(string name) { return LocalizationSource.GetString(name); } /// <summary> /// Gets localized string for given key name and current language with formatting strings. /// </summary> /// <param name="name">Key name</param> /// <param name="args">Format arguments</param> /// <returns>Localized string</returns> protected string L(string name, params object[] args) { return LocalizationSource.GetString(name, args); } /// <summary> /// Gets localized string for given key name and specified culture information. /// </summary> /// <param name="name">Key name</param> /// <param name="culture">culture information</param> /// <returns>Localized string</returns> protected virtual string L(string name, CultureInfo culture) { return LocalizationSource.GetString(name, culture); } /// <summary> /// Gets localized string for given key name and current language with formatting strings. /// </summary> /// <param name="name">Key name</param> /// <param name="culture">culture information</param> /// <param name="args">Format arguments</param> /// <returns>Localized string</returns> protected string L(string name, CultureInfo culture, params object[] args) { return LocalizationSource.GetString(name, culture, args); } /// <summary> /// Checks if current user is granted for a permission. /// </summary> /// <param name="permissionName">Name of the permission</param> protected Task<bool> IsGrantedAsync(string permissionName) { return PermissionChecker.IsGrantedAsync(permissionName); } /// <summary> /// Checks if current user is granted for a permission. /// </summary> /// <param name="permissionName">Name of the permission</param> protected bool IsGranted(string permissionName) { return PermissionChecker.IsGranted(permissionName); } /// <summary> /// Checks if given feature is enabled for current tenant. /// </summary> /// <param name="featureName">Name of the feature</param> /// <returns></returns> protected virtual Task<bool> IsEnabledAsync(string featureName) { return FeatureChecker.IsEnabledAsync(featureName); } /// <summary> /// Checks if given feature is enabled for current tenant. /// </summary> /// <param name="featureName">Name of the feature</param> /// <returns></returns> protected virtual bool IsEnabled(string featureName) { return FeatureChecker.IsEnabled(featureName); } /// <summary> /// Json the specified data, contentType, contentEncoding and behavior. /// </summary> /// <param name="data">Data.</param> /// <param name="contentType">Content type.</param> /// <param name="contentEncoding">Content encoding.</param> /// <param name="behavior">Behavior.</param> protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior) { if (_wrapResultAttribute != null && !_wrapResultAttribute.WrapOnSuccess) { return base.Json(data, contentType, contentEncoding, behavior); } return AbpJson(data, contentType, contentEncoding, behavior); } protected virtual AbpJsonResult AbpJson( object data, string contentType = null, Encoding contentEncoding = null, JsonRequestBehavior behavior = JsonRequestBehavior.DenyGet, bool wrapResult = true, bool camelCase = true, bool indented = false) { if (wrapResult) { if (data == null) { data = new AjaxResponse(); } else if (!(data is AjaxResponseBase)) { data = new AjaxResponse(data); } } return new AbpJsonResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior, CamelCase = camelCase, Indented = indented }; } #region OnActionExecuting / OnActionExecuted protected override void OnActionExecuting(ActionExecutingContext filterContext) { SetCurrentMethodInfoAndWrapResultAttribute(filterContext); base.OnActionExecuting(filterContext); } private void SetCurrentMethodInfoAndWrapResultAttribute(ActionExecutingContext filterContext) { //Prevent overriding for child actions if (_currentMethodInfo != null) { return; } _currentMethodInfo = filterContext.ActionDescriptor.GetMethodInfoOrNull(); _wrapResultAttribute = ReflectionHelper.GetSingleAttributeOfMemberOrDeclaringTypeOrDefault( _currentMethodInfo, AbpMvcConfiguration.DefaultWrapResultAttribute ); } #endregion #region Exception handling protected override void OnException(ExceptionContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } //If exception handled before, do nothing. //If this is child action, exception should be handled by main action. if (context.ExceptionHandled || context.IsChildAction) { base.OnException(context); return; } //Log exception if (_wrapResultAttribute == null || _wrapResultAttribute.LogError) { LogHelper.LogException(Logger, context.Exception); } // If custom errors are disabled, we need to let the normal ASP.NET exception handler // execute so that the user can see useful debugging information. if (!context.HttpContext.IsCustomErrorEnabled) { base.OnException(context); return; } // If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method), // ignore it. if (new HttpException(null, context.Exception).GetHttpCode() != 500) { base.OnException(context); return; } //Check WrapResultAttribute if (_wrapResultAttribute == null || !_wrapResultAttribute.WrapOnError) { base.OnException(context); return; } //We handled the exception! context.ExceptionHandled = true; //Return an error response to the client. context.HttpContext.Response.Clear(); context.HttpContext.Response.StatusCode = GetStatusCodeForException(context); context.Result = MethodInfoHelper.IsJsonResult(_currentMethodInfo) ? GenerateJsonExceptionResult(context) : GenerateNonJsonExceptionResult(context); // Certain versions of IIS will sometimes use their own error page when // they detect a server error. Setting this property indicates that we // want it to try to render ASP.NET MVC's error page instead. context.HttpContext.Response.TrySkipIisCustomErrors = true; //Trigger an event, so we can register it. EventBus.Trigger(this, new AbpHandledExceptionData(context.Exception)); } protected virtual int GetStatusCodeForException(ExceptionContext context) { if (context.Exception is AbpAuthorizationException) { return context.HttpContext.User.Identity.IsAuthenticated ? (int)HttpStatusCode.Forbidden : (int)HttpStatusCode.Unauthorized; } if (context.Exception is EntityNotFoundException) { return (int)HttpStatusCode.NotFound; } return (int)HttpStatusCode.InternalServerError; } protected virtual ActionResult GenerateJsonExceptionResult(ExceptionContext context) { context.HttpContext.Items.Add("IgnoreJsonRequestBehaviorDenyGet", "true"); return new AbpJsonResult( new AjaxResponse( ErrorInfoBuilder.BuildForException(context.Exception), context.Exception is AbpAuthorizationException ) ); } protected virtual ActionResult GenerateNonJsonExceptionResult(ExceptionContext context) { return new ViewResult { ViewName = "Error", MasterName = string.Empty, ViewData = new ViewDataDictionary<ErrorViewModel>(new ErrorViewModel(ErrorInfoBuilder.BuildForException(context.Exception), context.Exception)), TempData = context.Controller.TempData }; } #endregion } }
#region Proprietary Notice // **************************************************************************** // Copyright 2014 Vadim Zabavnov // // 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. // // **************************************************************************** // File Name: BindableProperty.cs. // Created: 2014/05/30/4:59 PM. // Modified: 2014/06/06/2:14 PM. // **************************************************************************** #endregion #region Usings using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Linq.Expressions; using System.Reflection; #endregion namespace Zabavnov.MVVM { /// <summary> /// Implements <see cref="IBindableProperty{TControl,TProperty}" /> where type of control property and value property /// is not the same /// </summary> /// <typeparam name="TControl"> /// The control type to bind to /// </typeparam> /// <typeparam name="TControlProperty"> /// The type of control property /// </typeparam> /// <typeparam name="TValueProperty"> /// The type of value property /// </typeparam> public class BindableProperty<TControl, TControlProperty, TValueProperty> : IBindableProperty<TControl, TValueProperty> where TControl : class { #region Fields /// <summary> /// </summary> private readonly IDataConverter<TControlProperty, TValueProperty> _converter; /// <summary> /// </summary> private readonly PropertyChangedEventArgs _eventArg; /// <summary> /// </summary> private readonly Func<TControl, TControlProperty> _getter; /// <summary> /// </summary> private readonly Action<TControl, TControlProperty> _setter; /// <summary> /// </summary> private IEqualityComparer<TValueProperty> _comparer; /// <summary> /// </summary> private bool _notificationEnabled = true; #endregion #region Constructors and Destructors /// <summary> /// create new instance of bindable property /// </summary> /// <param name="control"> /// The control to bind to /// </param> /// <param name="propertyName"> /// The name of property. this name will be used to raise event on /// <see cref="INotifyPropertyChanged" /> /// </param> /// <param name="getter"> /// The method to get value from control's property /// </param> /// <param name="setter"> /// The method to set value to control's property /// </param> /// <param name="controlNotificationActionSetter"> /// The delegate to setup notification action when control. this parameter is /// optional /// </param> /// <param name="converter"> /// The converter between control's property and value /// </param> /// <param name="comparer"> /// The comparer for /// <typeparam name="TValueProperty"></typeparam> /// </param> public BindableProperty( TControl control, string propertyName, Func<TControl, TControlProperty> getter, Action<TControl, TControlProperty> setter, Action<TControl, Action> controlNotificationActionSetter, IDataConverter<TControlProperty, TValueProperty> converter, IEqualityComparer<TValueProperty> comparer = null) { Contract.Requires(propertyName != null); Contract.Requires(!ReferenceEquals(control, null)); Contract.Requires(getter != null); Contract.Requires(converter != null); Control = control; _getter = getter; _setter = setter; _converter = converter; _comparer = comparer ?? EqualityComparer<TValueProperty>.Default; _eventArg = new PropertyChangedEventArgs(propertyName); controlNotificationActionSetter?.Invoke(control, OnControlPropertyChanged); } /// <param name="control"> /// The control to bind to /// </param> /// <param name="propertyLambda"> /// The lambda expression for property to assign /// <see cref="IBindableProperty{TControl,TProperty}" /> to. /// </param> /// <param name="propertyName"> /// The name of property. this name will be used to raise event on <see cref="INotifyPropertyChanged" />. /// If it is <b>null</b> then <paramref name="propertyLambda"/>'s name will be used instead. /// </param> /// <param name="controlNotificationActionSetter"> /// The delegate to setup notification action when control. this parameter is /// optional /// </param> /// <param name="converter"> /// The converter between control's property and value /// </param> /// <param name="comparer"> /// The comparer for /// <typeparam name="TValueProperty"></typeparam> /// </param> public BindableProperty( TControl control, Expression<Func<TControl, TControlProperty>> propertyLambda, string propertyName, Action<TControl, Action> controlNotificationActionSetter, IDataConverter<TControlProperty, TValueProperty> converter, IEqualityComparer<TValueProperty> comparer = null) { Contract.Requires(control != null); Contract.Requires(propertyLambda != null); Contract.Requires(controlNotificationActionSetter != null); Contract.Requires(converter != null); Control = control; var propInfo = (PropertyInfo)propertyLambda.GetMemberInfo(); if(propertyName == null) propertyName = propInfo.Name; if(propInfo.CanRead) _getter = propertyLambda.Compile(); if(propInfo.CanWrite) _setter = propertyLambda.GetPropertySetter(); _converter = converter; _comparer = comparer ?? EqualityComparer<TValueProperty>.Default; _eventArg = new PropertyChangedEventArgs(propertyName); controlNotificationActionSetter?.Invoke(control, OnControlPropertyChanged); } /// <summary> /// create new instance of bindable property /// </summary> /// <param name="control"> /// The control to bind to /// </param> /// <param name="propertyLambda"> /// The lambda expression for property to assign /// <see cref="IBindableProperty{TControl,TProperty}" /> to. /// </param> /// <param name="controlNotificationActionSetter"> /// The delegate to setup notification action when control. this parameter is /// optional /// </param> /// <param name="converter"> /// The converter between control's property and value /// </param> /// <param name="comparer"> /// The comparer for /// <typeparam name="TValueProperty"></typeparam> /// </param> public BindableProperty( TControl control, Expression<Func<TControl, TControlProperty>> propertyLambda, Action<TControl, Action> controlNotificationActionSetter, IDataConverter<TControlProperty, TValueProperty> converter, IEqualityComparer<TValueProperty> comparer = null) : this(control, propertyLambda, null, controlNotificationActionSetter, converter, comparer) { Contract.Requires(control != null); Contract.Requires(propertyLambda != null); Contract.Requires(converter != null); } #endregion #region Public Events /// <summary> /// </summary> public event PropertyChangedEventHandler PropertyChanged; #endregion #region Public Properties /// <summary> /// The property of control is readable /// </summary> [Pure] public bool CanRead => this._getter != null; /// <summary> /// The property of control is writable /// </summary> [Pure] public bool CanWrite => this._setter != null; /// <summary> /// </summary> public IEqualityComparer<TValueProperty> Comparer { get { return _comparer; } set { _comparer = value ?? EqualityComparer<TValueProperty>.Default; } } /// <summary> /// the control that property bound to /// </summary> public TControl Control { get; } /// <summary> /// use this value when <see cref="BindingMode" /> is equal to default /// </summary> public BindingMode DefaultBindingMode { get { if(CanRead && CanWrite) return BindingMode.TwoWay; if(CanRead) return BindingMode.OneWayToSource; if(CanWrite) return BindingMode.OneWay; throw new Exception("Something wrong is here"); } } /// <summary> /// The name of property /// </summary> public string PropertyName { get { Contract.Assume(!string.IsNullOrEmpty(_eventArg.PropertyName)); return _eventArg.PropertyName; } } /// <summary> /// The value of property. it uses converter to get or set value to the control /// </summary> public TValueProperty Value { get { return _converter.ConvertTo(_getter(Control)); } set { Contract.Assume(CanRead); Contract.Assume(Comparer != null); if(!Comparer.Equals(Value, value)) { _notificationEnabled = false; _setter(Control, _converter.ConvertFrom(value)); _notificationEnabled = true; NotifyPropertyChanged(); } } } #endregion #region Public Methods and Operators /// <summary> /// </summary> public virtual void NotifyPropertyChanged() { if(_notificationEnabled) { PropertyChangedEventHandler handler = PropertyChanged; handler?.Invoke(this.Control, this._eventArg); } } #endregion #region Methods [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(_eventArg != null); Contract.Invariant(_getter != null); Contract.Invariant(_converter != null); } private void OnControlPropertyChanged() { if(_notificationEnabled) NotifyPropertyChanged(); } #endregion } /// <summary> /// Implements <see cref="IBindableProperty{TControl,TProperty}" /> /// </summary> /// <typeparam name="TControl"> /// </typeparam> /// <typeparam name="TControlProperty"> /// </typeparam> [DebuggerStepThrough] public class BindableProperty<TControl, TControlProperty> : BindableProperty<TControl, TControlProperty, TControlProperty> where TControl : class { #region Constructors and Destructors /// <summary> /// create new instance of bindable property /// </summary> /// <param name="control"> /// The control to bind to /// </param> /// <param name="propertyName"> /// The name of property. this name will be used to raise event on /// <see cref="INotifyPropertyChanged" /> /// </param> /// <param name="getter"> /// The method to get value from control's property /// </param> /// <param name="setter"> /// The method to set value to control's property /// </param> /// <param name="controlNotificationActionSetter"> /// The delegate to setup notification action when control. this parameter is /// optional /// </param> /// <param name="comparer"> /// The comparer for /// <typeparam name="TControlProperty"></typeparam> /// </param> public BindableProperty( TControl control, string propertyName, Func<TControl, TControlProperty> getter, Action<TControl, TControlProperty> setter, Action<TControl, Action> controlNotificationActionSetter, IEqualityComparer<TControlProperty> comparer = null) : base(control, propertyName, getter, setter, controlNotificationActionSetter, DataConverter<TControlProperty>.EmptyConverter, comparer) { Contract.Requires(control != null); Contract.Requires(!String.IsNullOrEmpty(propertyName)); Contract.Requires(getter != null); } /// <summary> /// create new instance of bindable property /// </summary> /// <param name="control"> /// The control to bind to /// </param> /// <param name="propertyLambda"> /// The lambda expression for property to assign /// <see cref="IBindableProperty{TControl,TProperty}" /> to. /// </param> /// <param name="controlNotificationActionSetter"> /// The delegate to setup notification action when control. this parameter is /// optional /// </param> /// <param name="comparer"> /// The comparer for /// <typeparam name="TControlProperty"></typeparam> /// </param> public BindableProperty( TControl control, Expression<Func<TControl, TControlProperty>> propertyLambda, Action<TControl, Action> controlNotificationActionSetter, IEqualityComparer<TControlProperty> comparer = null) : base(control, propertyLambda, controlNotificationActionSetter, DataConverter<TControlProperty>.EmptyConverter, comparer) { Contract.Requires(control != null); Contract.Requires(propertyLambda != null); } #endregion } }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using RestSharp; using Xunit; using Org.OpenAPITools.Client; using Org.OpenAPITools.Api; // uncomment below to import models //using Org.OpenAPITools.Model; namespace Org.OpenAPITools.Test.Api { /// <summary> /// Class for testing BlueOceanApi /// </summary> /// <remarks> /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the API endpoint. /// </remarks> public class BlueOceanApiTests : IDisposable { private BlueOceanApi instance; public BlueOceanApiTests() { instance = new BlueOceanApi(); } public void Dispose() { // Cleanup when everything is done. } /// <summary> /// Test an instance of BlueOceanApi /// </summary> [Fact] public void InstanceTest() { // TODO uncomment below to test 'IsType' BlueOceanApi //Assert.IsType<BlueOceanApi>(instance); } /// <summary> /// Test DeletePipelineQueueItem /// </summary> [Fact] public void DeletePipelineQueueItemTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string queue = null; //instance.DeletePipelineQueueItem(organization, pipeline, queue); } /// <summary> /// Test GetAuthenticatedUser /// </summary> [Fact] public void GetAuthenticatedUserTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //var response = instance.GetAuthenticatedUser(organization); //Assert.IsType<User>(response); } /// <summary> /// Test GetClasses /// </summary> [Fact] public void GetClassesTest() { // TODO uncomment below to test the method and replace null with proper value //string _class = null; //var response = instance.GetClasses(_class); //Assert.IsType<string>(response); } /// <summary> /// Test GetJsonWebKey /// </summary> [Fact] public void GetJsonWebKeyTest() { // TODO uncomment below to test the method and replace null with proper value //int key = null; //var response = instance.GetJsonWebKey(key); //Assert.IsType<string>(response); } /// <summary> /// Test GetJsonWebToken /// </summary> [Fact] public void GetJsonWebTokenTest() { // TODO uncomment below to test the method and replace null with proper value //int? expiryTimeInMins = null; //int? maxExpiryTimeInMins = null; //var response = instance.GetJsonWebToken(expiryTimeInMins, maxExpiryTimeInMins); //Assert.IsType<string>(response); } /// <summary> /// Test GetOrganisation /// </summary> [Fact] public void GetOrganisationTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //var response = instance.GetOrganisation(organization); //Assert.IsType<Organisation>(response); } /// <summary> /// Test GetOrganisations /// </summary> [Fact] public void GetOrganisationsTest() { // TODO uncomment below to test the method and replace null with proper value //var response = instance.GetOrganisations(); //Assert.IsType<List<Organisation>>(response); } /// <summary> /// Test GetPipeline /// </summary> [Fact] public void GetPipelineTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //var response = instance.GetPipeline(organization, pipeline); //Assert.IsType<Pipeline>(response); } /// <summary> /// Test GetPipelineActivities /// </summary> [Fact] public void GetPipelineActivitiesTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //var response = instance.GetPipelineActivities(organization, pipeline); //Assert.IsType<List<PipelineActivity>>(response); } /// <summary> /// Test GetPipelineBranch /// </summary> [Fact] public void GetPipelineBranchTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string branch = null; //var response = instance.GetPipelineBranch(organization, pipeline, branch); //Assert.IsType<BranchImpl>(response); } /// <summary> /// Test GetPipelineBranchRun /// </summary> [Fact] public void GetPipelineBranchRunTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string branch = null; //string run = null; //var response = instance.GetPipelineBranchRun(organization, pipeline, branch, run); //Assert.IsType<PipelineRun>(response); } /// <summary> /// Test GetPipelineBranches /// </summary> [Fact] public void GetPipelineBranchesTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //var response = instance.GetPipelineBranches(organization, pipeline); //Assert.IsType<MultibranchPipeline>(response); } /// <summary> /// Test GetPipelineFolder /// </summary> [Fact] public void GetPipelineFolderTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string folder = null; //var response = instance.GetPipelineFolder(organization, folder); //Assert.IsType<PipelineFolderImpl>(response); } /// <summary> /// Test GetPipelineFolderPipeline /// </summary> [Fact] public void GetPipelineFolderPipelineTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string folder = null; //var response = instance.GetPipelineFolderPipeline(organization, pipeline, folder); //Assert.IsType<PipelineImpl>(response); } /// <summary> /// Test GetPipelineQueue /// </summary> [Fact] public void GetPipelineQueueTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //var response = instance.GetPipelineQueue(organization, pipeline); //Assert.IsType<List<QueueItemImpl>>(response); } /// <summary> /// Test GetPipelineRun /// </summary> [Fact] public void GetPipelineRunTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string run = null; //var response = instance.GetPipelineRun(organization, pipeline, run); //Assert.IsType<PipelineRun>(response); } /// <summary> /// Test GetPipelineRunLog /// </summary> [Fact] public void GetPipelineRunLogTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string run = null; //int? start = null; //bool? download = null; //var response = instance.GetPipelineRunLog(organization, pipeline, run, start, download); //Assert.IsType<string>(response); } /// <summary> /// Test GetPipelineRunNode /// </summary> [Fact] public void GetPipelineRunNodeTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string run = null; //string node = null; //var response = instance.GetPipelineRunNode(organization, pipeline, run, node); //Assert.IsType<PipelineRunNode>(response); } /// <summary> /// Test GetPipelineRunNodeStep /// </summary> [Fact] public void GetPipelineRunNodeStepTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string run = null; //string node = null; //string step = null; //var response = instance.GetPipelineRunNodeStep(organization, pipeline, run, node, step); //Assert.IsType<PipelineStepImpl>(response); } /// <summary> /// Test GetPipelineRunNodeStepLog /// </summary> [Fact] public void GetPipelineRunNodeStepLogTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string run = null; //string node = null; //string step = null; //var response = instance.GetPipelineRunNodeStepLog(organization, pipeline, run, node, step); //Assert.IsType<string>(response); } /// <summary> /// Test GetPipelineRunNodeSteps /// </summary> [Fact] public void GetPipelineRunNodeStepsTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string run = null; //string node = null; //var response = instance.GetPipelineRunNodeSteps(organization, pipeline, run, node); //Assert.IsType<List<PipelineStepImpl>>(response); } /// <summary> /// Test GetPipelineRunNodes /// </summary> [Fact] public void GetPipelineRunNodesTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string run = null; //var response = instance.GetPipelineRunNodes(organization, pipeline, run); //Assert.IsType<List<PipelineRunNode>>(response); } /// <summary> /// Test GetPipelineRuns /// </summary> [Fact] public void GetPipelineRunsTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //var response = instance.GetPipelineRuns(organization, pipeline); //Assert.IsType<List<PipelineRun>>(response); } /// <summary> /// Test GetPipelines /// </summary> [Fact] public void GetPipelinesTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //var response = instance.GetPipelines(organization); //Assert.IsType<List<Pipeline>>(response); } /// <summary> /// Test GetSCM /// </summary> [Fact] public void GetSCMTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string scm = null; //var response = instance.GetSCM(organization, scm); //Assert.IsType<GithubScm>(response); } /// <summary> /// Test GetSCMOrganisationRepositories /// </summary> [Fact] public void GetSCMOrganisationRepositoriesTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string scm = null; //string scmOrganisation = null; //string credentialId = null; //int? pageSize = null; //int? pageNumber = null; //var response = instance.GetSCMOrganisationRepositories(organization, scm, scmOrganisation, credentialId, pageSize, pageNumber); //Assert.IsType<List<GithubOrganization>>(response); } /// <summary> /// Test GetSCMOrganisationRepository /// </summary> [Fact] public void GetSCMOrganisationRepositoryTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string scm = null; //string scmOrganisation = null; //string repository = null; //string credentialId = null; //var response = instance.GetSCMOrganisationRepository(organization, scm, scmOrganisation, repository, credentialId); //Assert.IsType<List<GithubOrganization>>(response); } /// <summary> /// Test GetSCMOrganisations /// </summary> [Fact] public void GetSCMOrganisationsTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string scm = null; //string credentialId = null; //var response = instance.GetSCMOrganisations(organization, scm, credentialId); //Assert.IsType<List<GithubOrganization>>(response); } /// <summary> /// Test GetUser /// </summary> [Fact] public void GetUserTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string user = null; //var response = instance.GetUser(organization, user); //Assert.IsType<User>(response); } /// <summary> /// Test GetUserFavorites /// </summary> [Fact] public void GetUserFavoritesTest() { // TODO uncomment below to test the method and replace null with proper value //string user = null; //var response = instance.GetUserFavorites(user); //Assert.IsType<List<FavoriteImpl>>(response); } /// <summary> /// Test GetUsers /// </summary> [Fact] public void GetUsersTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //var response = instance.GetUsers(organization); //Assert.IsType<User>(response); } /// <summary> /// Test PostPipelineRun /// </summary> [Fact] public void PostPipelineRunTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string run = null; //var response = instance.PostPipelineRun(organization, pipeline, run); //Assert.IsType<QueueItemImpl>(response); } /// <summary> /// Test PostPipelineRuns /// </summary> [Fact] public void PostPipelineRunsTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //var response = instance.PostPipelineRuns(organization, pipeline); //Assert.IsType<QueueItemImpl>(response); } /// <summary> /// Test PutPipelineFavorite /// </summary> [Fact] public void PutPipelineFavoriteTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //bool body = null; //var response = instance.PutPipelineFavorite(organization, pipeline, body); //Assert.IsType<FavoriteImpl>(response); } /// <summary> /// Test PutPipelineRun /// </summary> [Fact] public void PutPipelineRunTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string run = null; //string blocking = null; //int? timeOutInSecs = null; //var response = instance.PutPipelineRun(organization, pipeline, run, blocking, timeOutInSecs); //Assert.IsType<PipelineRun>(response); } /// <summary> /// Test Search /// </summary> [Fact] public void SearchTest() { // TODO uncomment below to test the method and replace null with proper value //string q = null; //var response = instance.Search(q); //Assert.IsType<string>(response); } /// <summary> /// Test SearchClasses /// </summary> [Fact] public void SearchClassesTest() { // TODO uncomment below to test the method and replace null with proper value //string q = null; //var response = instance.SearchClasses(q); //Assert.IsType<string>(response); } } }
using System; using System.Collections.Generic; using System.Text; using System.Linq; namespace NoraGrace.Engine { [System.Diagnostics.DebuggerDisplay(@"{NoraGrace.Engine.MoveUtil.DebugDescription(this),nq}")] public enum Move { EMPTY = 0 } public static partial class MoveUtil { public enum NotationType { Coord, San, Detailed } public static Move Create(Position from, Position to, Piece piece, Piece captured) { System.Diagnostics.Debug.Assert((int)from >= 0 && (int)from <= 63); System.Diagnostics.Debug.Assert((int)to >= 0 && (int)to <= 63); System.Diagnostics.Debug.Assert((int)piece == ((int)piece & 0xF)); System.Diagnostics.Debug.Assert((int)captured == ((int)captured & 0xF)); System.Diagnostics.Debug.Assert(captured == Piece.EMPTY || (piece.PieceToPlayer() != captured.PieceToPlayer())); //if capture is opposite color System.Diagnostics.Debug.Assert(piece.ToPieceType() != PieceType.Pawn || !(Bitboard.Rank1 | Bitboard.Rank8).Contains(to)); //is not pawn to 8th return (Move)( (int)from | ((int)to << 6) | ((int)piece << 12) | ((int)captured << 16) ); } public static Move Create(Position from, Position to, Piece piece, Piece captured, PieceType promoteType) { System.Diagnostics.Debug.Assert((int)from >= 0 && (int)from <= 63); System.Diagnostics.Debug.Assert((int)to >= 0 && (int)to <= 63); System.Diagnostics.Debug.Assert((int)piece == ((int)piece & 0xF)); System.Diagnostics.Debug.Assert((int)captured == ((int)captured & 0xF)); System.Diagnostics.Debug.Assert(captured == Piece.EMPTY || (piece.PieceToPlayer() != captured.PieceToPlayer())); //if capture is opposite color System.Diagnostics.Debug.Assert(promoteType == PieceType.Knight || promoteType == PieceType.Bishop || promoteType == PieceType.Rook || promoteType == PieceType.Queen); System.Diagnostics.Debug.Assert(piece.ToPieceType() == PieceType.Pawn); //is pawn System.Diagnostics.Debug.Assert((Bitboard.Rank1 | Bitboard.Rank8).Contains(to)); //to 8th System.Diagnostics.Debug.Assert((Bitboard.Rank2 | Bitboard.Rank7).Contains(from)); //from 7th return (Move)( (int)from | ((int)to << 6) | ((int)piece << 12) | ((int)captured << 16) | ((int)promoteType << 20) ); } public static Position From(this Move move) { return (Position)((int)move & 0x3F); } public static Position To(this Move move) { return (Position)((int)move >> 6 & 0x3F); } public static Piece MovingPiece(this Move move) { return (Piece)((int)move >> 12 & 0xF); } public static PieceType MovingPieceType(this Move move) { return (PieceType)((int)move >> 12 & 0x7); } public static Player MovingPlayer(this Move move) { System.Diagnostics.Debug.Assert(move != Move.EMPTY); return (Player)((int)move >> 15 & 0x1); // shift of the moving piece to player bit. } public static bool IsCapture(this Move move) { return ((int)move >> 16 & 0xF) != 0; } public static Piece CapturedPiece(this Move move) { return (Piece)((int)move >> 16 & 0xF); } public static PieceType CapturedPieceType(this Move move) { return (PieceType)((int)move >> 16 & 0x7); } public static bool IsPromotion(this Move move) { return ((int)move >> 20 & 0x7) != 0; } public static Piece Promote(this Move move) { return move.PromoteType() == PieceType.EMPTY ? Piece.EMPTY : move.PromoteType().ForPlayer(move.MovingPlayer()); } public static PieceType PromoteType(this Move move) { return (PieceType)((int)move >> 20 & 0x7); } public static bool IsEnPassant(this Move move) { return move.MovingPieceType() == PieceType.Pawn && !move.IsCapture() && move.From().ToFile() != move.To().ToFile(); } public static bool IsCastle(this Move move) { return move.MovingPieceType() == PieceType.King && Math.Abs((int)move.From() - (int)move.To()) == 2; } public static bool IsPawnDoubleJump(this Move move) { return move.MovingPieceType() == PieceType.Pawn && Math.Abs((int)move.From() - (int)move.To()) == 16; } public static bool IsLegal(this Move move, Board board) { List<Move> legalmoves = new List<Move>(MoveUtil.GenMovesLegal(board)); foreach (Move legalmove in legalmoves) { if (legalmove == move) { return true; } } return false; } public static bool IsLegalPsuedoMove(this Move move, Board board, AttackInfo opponentAttackInfo, CheckInfo myCheckInfo) { System.Diagnostics.Debug.Assert(opponentAttackInfo.IsInitialized(board)); System.Diagnostics.Debug.Assert(myCheckInfo.IsInitialized(board)); System.Diagnostics.Debug.Assert(move.MovingPlayer() == myCheckInfo.Player); System.Diagnostics.Debug.Assert(move.MovingPlayer().PlayerOther() == opponentAttackInfo.Player); if (myCheckInfo.IsCheck) { Bitboard checkers = myCheckInfo.Checkers; if (move.MovingPieceType() == PieceType.King) { //in check, king evasions if (opponentAttackInfo.All.Contains(move.To())) { return false; } else { Bitboard adjustedAttacks = Bitboard.Empty; while (checkers != Bitboard.Empty) { //we could be moving to/from a sliding attack. var checkerPos = BitboardUtil.PopFirst(ref checkers); var checkerType = board.PieceAt(checkerPos).ToPieceType(); switch (checkerType) { case PieceType.Bishop: adjustedAttacks |= Attacks.BishopAttacks(checkerPos, board.PieceLocationsAll ^ move.From().ToBitboard()); break; case PieceType.Rook: adjustedAttacks |= Attacks.RookAttacks(checkerPos, board.PieceLocationsAll ^ move.From().ToBitboard()); break; case PieceType.Queen: adjustedAttacks |= Attacks.QueenAttacks(checkerPos, board.PieceLocationsAll ^ move.From().ToBitboard()); break; } } return !adjustedAttacks.Contains(move.To()); } } else { //in check, non king move. //find position of first checker var checkerPos = BitboardUtil.PopFirst(ref checkers); if (checkers != Bitboard.Empty) { //there are two attackers, no sense moving a non-king return false; } if (myCheckInfo.PinnedOrDiscovered.Contains(move.From())) { // this piece is pinned, no sense moving it return false; } //find squares between king and checker (or checker itself) Bitboard targets = checkerPos.Between(board.KingPosition(board.WhosTurn)) | checkerPos.ToBitboard(); return targets.Contains(move.To()) || move.IsEnPassant();//if enpassant is available and we are in check, then must be enpassant check } } else { //not currently in check if(move.MovingPieceType() == PieceType.King) { return !opponentAttackInfo.All.Contains(move.To()); } else if(myCheckInfo.PinnedOrDiscovered.Contains(move.From())) { //pinned piece var dirToKing = move.From().DirectionTo(board.KingPosition(move.MovingPlayer())); var dirMoving = move.From().DirectionTo(move.To()); return dirMoving == dirToKing || dirMoving == dirToKing.Opposite(); } else { //normal piece, not pinned, not king return true; } } } public static bool IsPsuedoLegal(this Move move, Board board) { if (move == Move.EMPTY) { return false; } var from = move.From(); var to = move.To(); if (move.MovingPiece() != board.PieceAt(from)) { return false; } if (move.CapturedPiece() != board.PieceAt(to)) { return false; } var piece = move.MovingPiece(); if (piece == Piece.EMPTY) { return false; } var pieceType = piece.ToPieceType(); var me = piece.PieceToPlayer(); if (board.WhosTurn != me) { return false; } if (board[me].Contains(to)) { return false; } if (move.IsPromotion()) { //these should be verified in move constructor, but put check here just in case. System.Diagnostics.Debug.Assert(pieceType == PieceType.Pawn); System.Diagnostics.Debug.Assert(to.ToRank() == me.MyRank(Rank.Rank8)); } var targets = ~board[me]; switch (pieceType) { case PieceType.Knight: return (Attacks.KnightAttacks(from) & targets).Contains(to); case PieceType.Bishop: return (Attacks.BishopAttacks(from, board.PieceLocationsAll) & targets).Contains(to); case PieceType.Rook: return (Attacks.RookAttacks(from, board.PieceLocationsAll) & targets).Contains(to); case PieceType.Queen: return (Attacks.QueenAttacks(from, board.PieceLocationsAll) & targets).Contains(to); case PieceType.King: if (move.IsCastle()) { if (me == Player.White && from == Position.E1 && to == Position.G1 && board.PieceAt(Position.F1) == Piece.EMPTY && board.PieceAt(Position.G1) == Piece.EMPTY && board.PieceAt(Position.H1) == Piece.WRook && (board.CastleRights & CastleFlags.WhiteShort) == CastleFlags.WhiteShort && !board.IsCheck() && !board.AttacksTo(Position.F1).Contains(targets) && !board.AttacksTo(Position.G1).Contains(targets)) { return true; } else if (me == Player.White && from == Position.E1 && to == Position.C1 && board.PieceAt(Position.B1) == Piece.EMPTY && board.PieceAt(Position.C1) == Piece.EMPTY && board.PieceAt(Position.D1) == Piece.EMPTY && board.PieceAt(Position.A1) == Piece.WRook && (board.CastleRights & CastleFlags.WhiteLong) == CastleFlags.WhiteLong && !board.IsCheck() && !board.AttacksTo(Position.D1).Contains(targets) && !board.AttacksTo(Position.C1).Contains(targets)) { return true; } else if (me == Player.Black && from == Position.E8 && to == Position.G8 && board.PieceAt(Position.F8) == Piece.EMPTY && board.PieceAt(Position.G8) == Piece.EMPTY && board.PieceAt(Position.H8) == Piece.BRook && (board.CastleRights & CastleFlags.BlackShort) == CastleFlags.BlackShort && !board.IsCheck() && !board.AttacksTo(Position.F8).Contains(targets) && !board.AttacksTo(Position.G8).Contains(targets)) { return true; } else if (me == Player.Black && from == Position.E8 && to == Position.C8 && board.PieceAt(Position.B8) == Piece.EMPTY && board.PieceAt(Position.C8) == Piece.EMPTY && board.PieceAt(Position.D8) == Piece.EMPTY && board.PieceAt(Position.A8) == Piece.BRook && (board.CastleRights & CastleFlags.BlackLong) == CastleFlags.BlackLong && !board.IsCheck() && !board.AttacksTo(Position.D8).Contains(targets) && !board.AttacksTo(Position.C8).Contains(targets)) { return true; } else { return false; } } else if ((Attacks.KingAttacks(from) & targets).Contains(to)) { return true; } else { return false; } case PieceType.Pawn: //check moves to last rank have promotion if pawn. if (me == Player.White && to.ToRank() == Rank.Rank8 && move.Promote() == Piece.EMPTY) { return false; } else if (me == Player.Black && to.ToRank() == Rank.Rank1 && move.Promote() == Piece.EMPTY) { return false; } if(move.IsEnPassant()) { return to == board.EnPassant; } else if(move.IsCapture()) { //already verified that attacking spot correct return Attacks.PawnAttacks(from, me).Contains(to); } else if(move.IsPawnDoubleJump()) { //already verified start and end spot validity. return board.PieceAt(move.From().PositionInDirectionUnsafe(me.MyNorth())) == Piece.EMPTY; } else { return true; } default: return false; } } public static bool MakesThreat(this Move move, Board board) { Position from = move.From(); Position to = move.To(); Player player = board.WhosTurn; Player opponent = player.PlayerOther(); Bitboard them = board[opponent]; PieceType pieceType = move.MovingPieceType(); switch (pieceType) { case PieceType.Pawn: return (Attacks.PawnAttacks(to, player) & them & ~board[PieceType.Pawn]) != Bitboard.Empty; case PieceType.Knight: return (Attacks.KnightAttacks(to) & them & board.RookSliders) != Bitboard.Empty; case PieceType.Bishop: return (Attacks.BishopAttacks(to, board.PieceLocationsAll) & them & board.RookSliders) != Bitboard.Empty; case PieceType.Rook: return (Attacks.RookAttacks(to, board.PieceLocationsAll) & them & board[PieceType.Queen]) != Bitboard.Empty; default: return false; } } public static bool CausesCheck(this Move move, Board board, CheckInfo oppenentCheckInfo) { System.Diagnostics.Debug.Assert(oppenentCheckInfo.IsInitialized(board)); System.Diagnostics.Debug.Assert(move.MovingPlayer().PlayerOther() == oppenentCheckInfo.Player); Position from = move.From(); Position to = move.To(); PieceType pieceType = move.MovingPieceType(); if (move.IsPromotion()) { PieceType pieceTypeAfter = move.IsPromotion() ? move.PromoteType() : pieceType; //in case of promotion Bitboard promoteAttacks = Bitboard.Empty; Bitboard allPiecesAfter = board.PieceLocationsAll ^ move.From().ToBitboard() ^ move.To().ToBitboard(); switch (pieceTypeAfter) { case PieceType.Knight: promoteAttacks = Attacks.KnightAttacks(to); break; case PieceType.Bishop: promoteAttacks = Attacks.BishopAttacks(to, allPiecesAfter); break; case PieceType.Rook: promoteAttacks = Attacks.RookAttacks(to, allPiecesAfter); break; case PieceType.Queen: promoteAttacks = Attacks.QueenAttacks(to, allPiecesAfter); break; } if (promoteAttacks.Contains(board.KingPosition(board.WhosTurn.PlayerOther()))) { return true; } } if (oppenentCheckInfo.DirectAll.Contains(to)) { bool direct = false; switch (pieceType) { case PieceType.Pawn: direct = oppenentCheckInfo.PawnDirect.Contains(to); break; case PieceType.Knight: direct = oppenentCheckInfo.KnightDirect.Contains(to); break; case PieceType.Bishop: direct = oppenentCheckInfo.BishopDirect.Contains(to); break; case PieceType.Rook: direct = oppenentCheckInfo.RookDirect.Contains(to); break; case PieceType.Queen: direct = oppenentCheckInfo.BishopDirect.Contains(to) || oppenentCheckInfo.RookDirect.Contains(to); break; } if (direct) { return true; } } if (oppenentCheckInfo.PinnedOrDiscovered.Contains(from) || move.IsEnPassant()) { Bitboard allAfterMove = (board.PieceLocationsAll & ~from.ToBitboard()) | to.ToBitboard(); if (move.IsEnPassant()) { Position enpassantCapturedSq = board.WhosTurn.MyRank(Rank.Rank5).ToPosition(board.EnPassant.ToFile()); allAfterMove &= ~enpassantCapturedSq.ToBitboard(); } Bitboard stmAll = board[board.WhosTurn]; Bitboard revealed = (Attacks.BishopAttacks(oppenentCheckInfo.KingPosition, allAfterMove) & stmAll & board.BishopSliders) | (Attacks.RookAttacks(oppenentCheckInfo.KingPosition, allAfterMove) & stmAll & board.RookSliders); if (revealed != Bitboard.Empty) { return true; } } //check if castling reveals check via rook if (move.IsCastle()) { if (from == Position.E1 && to == Position.G1 && oppenentCheckInfo.RookDirect.Contains(Position.F1)) { return true; } if (from == Position.E1 && to == Position.C1 && oppenentCheckInfo.RookDirect.Contains(Position.D1)) { return true; } if (from == Position.E8 && to == Position.G8 && oppenentCheckInfo.RookDirect.Contains(Position.F8)) { return true; } if (from == Position.E8 && to == Position.C8 && oppenentCheckInfo.RookDirect.Contains(Position.D8)) { return true; } } return false; } public static int MVVLVA(this Move move) { System.Diagnostics.Debug.Assert(move.IsCapture() || move.IsEnPassant()); var pieceval = (int)move.MovingPieceType(); var capval = move.IsEnPassant() ? (int)PieceType.Pawn : (int)move.CapturedPieceType(); return (capval << 3) | (6 - pieceval); } public static bool IsSafeQuiet(this Move move, Board board, StaticExchange see, AttackInfo myAttacks, AttackInfo hisAttacks) { System.Diagnostics.Debug.Assert(myAttacks.IsInitialized(board)); System.Diagnostics.Debug.Assert(hisAttacks.IsInitialized(board)); System.Diagnostics.Debug.Assert(myAttacks.Player == move.MovingPlayer()); System.Diagnostics.Debug.Assert(hisAttacks.Player == move.MovingPlayer().PlayerOther()); System.Diagnostics.Debug.Assert(!move.IsCapture() && !move.IsEnPassant()); //return see.CalculateScore(board, move) >= 0; var piece = move.MovingPieceType(); var from = move.From().ToBitboard(); var to = move.To().ToBitboard(); //Bitboard hisPieces = board[board.WhosTurn.PlayerOther()]; //if(piece.IsSliderDiag() //i am a bishop/queen // && hisAttacks.BySliderBishop.Contains(from) //currently attacked by bishop // && !myAttacks.ByCount(2).Contains(to) // no extra backup where moving to // && Attacks.BishopAttacks(move.To(), board.PieceLocationsAll ^ from).Contains(board.BishopSliders & hisPieces)) //{ // return false; //} //if (piece.IsSliderHorizontal() //i am a rook/queen // && hisAttacks.BySliderRook.Contains(from) //currently attacked by rook // && !myAttacks.ByCount(2).Contains(to) // no extra backup where moving to // && Attacks.RookAttacks(move.To(), board.PieceLocationsAll ^ from).Contains(board.RookSliders & hisPieces)) //{ // return false; //} if (!hisAttacks.All.Contains(to)) { return true; } if (hisAttacks.LessThan(piece).Contains(to)) { return false; } if (myAttacks.ByCount(2).Contains(to) && !hisAttacks.ByCount(2).Contains(to)) { return true; } //or maybe SEE here return see.CalculateScore(board, move) >= 0; } public static bool IsGoodCapture(this Move move, Board board, StaticExchange see, AttackInfo myAttacks, AttackInfo hisAttacks) { System.Diagnostics.Debug.Assert(myAttacks.IsInitialized(board)); System.Diagnostics.Debug.Assert(hisAttacks.IsInitialized(board)); System.Diagnostics.Debug.Assert(myAttacks.Player == move.MovingPlayer()); System.Diagnostics.Debug.Assert(hisAttacks.Player == move.MovingPlayer().PlayerOther()); System.Diagnostics.Debug.Assert(move.IsCapture() || move.IsEnPassant()); return see.CalculateScore(board, move) >= 0; var piece = move.MovingPieceType(); var cap = move.IsEnPassant() ? PieceType.Pawn : move.CapturedPieceType(); if (cap.BasicVal() >= piece.BasicVal()) { return true; } var to = move.To().ToBitboard(); if (!hisAttacks.All.Contains(to)) { return true; } if (hisAttacks.LessThan(piece).Contains(to)) { return false; } if (myAttacks.ByCount(2).Contains(to)) { return see.CalculateScore(board, move) >= 0; } else { return false; } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using Newtonsoft.Json; using System.IO; using System.Xml; namespace Newtonsoft.Json.Tests { public class JsonTextReaderTest : TestFixtureBase { [Test] public void YahooFinance() { string input = @"{ ""matches"" : [ {""t"":""C"", ""n"":""Citigroup Inc."", ""e"":""NYSE"", ""id"":""662713""} ,{""t"":""CHL"", ""n"":""China Mobile Ltd. (ADR)"", ""e"":""NYSE"", ""id"":""660998""} ,{""t"":""PTR"", ""n"":""PetroChina Company Limited (ADR)"", ""e"":""NYSE"", ""id"":""664536""} ,{""t"":""RIO"", ""n"":""Companhia Vale do Rio Doce (ADR)"", ""e"":""NYSE"", ""id"":""671472""} ,{""t"":""RIOPR"", ""n"":""Companhia Vale do Rio Doce (ADR)"", ""e"":""NYSE"", ""id"":""3512643""} ,{""t"":""CSCO"", ""n"":""Cisco Systems, Inc."", ""e"":""NASDAQ"", ""id"":""99624""} ,{""t"":""CVX"", ""n"":""Chevron Corporation"", ""e"":""NYSE"", ""id"":""667226""} ,{""t"":""TM"", ""n"":""Toyota Motor Corporation (ADR)"", ""e"":""NYSE"", ""id"":""655880""} ,{""t"":""JPM"", ""n"":""JPMorgan Chase \\x26 Co."", ""e"":""NYSE"", ""id"":""665639""} ,{""t"":""COP"", ""n"":""ConocoPhillips"", ""e"":""NYSE"", ""id"":""1691168""} ,{""t"":""LFC"", ""n"":""China Life Insurance Company Ltd. (ADR)"", ""e"":""NYSE"", ""id"":""688679""} ,{""t"":""NOK"", ""n"":""Nokia Corporation (ADR)"", ""e"":""NYSE"", ""id"":""657729""} ,{""t"":""KO"", ""n"":""The Coca-Cola Company"", ""e"":""NYSE"", ""id"":""6550""} ,{""t"":""VZ"", ""n"":""Verizon Communications Inc."", ""e"":""NYSE"", ""id"":""664887""} ,{""t"":""AMX"", ""n"":""America Movil S.A.B de C.V. (ADR)"", ""e"":""NYSE"", ""id"":""665834""}], ""all"" : false } "; using (JsonReader jsonReader = new JsonTextReader(new StringReader(input))) { while (jsonReader.Read()) { Console.WriteLine(jsonReader.Value); } } } [Test] public void ReadingIndented() { string input = @"{ CPU: 'Intel', Drives: [ 'DVD read/writer', ""500 gigabyte hard drive"" ] }"; StringReader sr = new StringReader(input); using (JsonTextReader jsonReader = new JsonTextReader(sr)) { Assert.AreEqual(jsonReader.TokenType, JsonToken.None); Assert.AreEqual(0, jsonReader.LineNumber); Assert.AreEqual(0, jsonReader.LinePosition); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.StartObject); Assert.AreEqual(1, jsonReader.LineNumber); Assert.AreEqual(1, jsonReader.LinePosition); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName); Assert.AreEqual(jsonReader.Value, "CPU"); Assert.AreEqual(2, jsonReader.LineNumber); Assert.AreEqual(6, jsonReader.LinePosition); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.String); Assert.AreEqual(jsonReader.Value, "Intel"); Assert.AreEqual(2, jsonReader.LineNumber); Assert.AreEqual(14, jsonReader.LinePosition); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName); Assert.AreEqual(jsonReader.Value, "Drives"); Assert.AreEqual(3, jsonReader.LineNumber); Assert.AreEqual(9, jsonReader.LinePosition); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.StartArray); Assert.AreEqual(3, jsonReader.LineNumber); Assert.AreEqual(11, jsonReader.LinePosition); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.String); Assert.AreEqual(jsonReader.Value, "DVD read/writer"); Assert.AreEqual(jsonReader.QuoteChar, '\''); Assert.AreEqual(4, jsonReader.LineNumber); Assert.AreEqual(21, jsonReader.LinePosition); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.String); Assert.AreEqual(jsonReader.Value, "500 gigabyte hard drive"); Assert.AreEqual(jsonReader.QuoteChar, '"'); Assert.AreEqual(5, jsonReader.LineNumber); Assert.AreEqual(29, jsonReader.LinePosition); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.EndArray); Assert.AreEqual(6, jsonReader.LineNumber); Assert.AreEqual(3, jsonReader.LinePosition); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.EndObject); Assert.AreEqual(7, jsonReader.LineNumber); Assert.AreEqual(1, jsonReader.LinePosition); Assert.IsFalse(jsonReader.Read()); } } [Test] public void Depth() { string input = "{value:'Purple\\r \\n monkey\\'s:\\tdishwasher',array:[1,2]}"; StringReader sr = new StringReader(input); using (JsonReader jsonReader = new JsonTextReader(sr)) { Assert.AreEqual(0, jsonReader.Depth); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.StartObject); Assert.AreEqual(0, jsonReader.Depth); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName); Assert.AreEqual(1, jsonReader.Depth); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.String); Assert.AreEqual(jsonReader.Value, "Purple\r \n monkey's:\tdishwasher"); Assert.AreEqual(jsonReader.QuoteChar, '\''); Assert.AreEqual(1, jsonReader.Depth); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName); Assert.AreEqual(1, jsonReader.Depth); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.StartArray); Assert.AreEqual(2, jsonReader.Depth); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.Integer); Assert.AreEqual(1, jsonReader.Value); Assert.AreEqual(3, jsonReader.Depth); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.Integer); Assert.AreEqual(2, jsonReader.Value); Assert.AreEqual(3, jsonReader.Depth); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.EndArray); Assert.AreEqual(1, jsonReader.Depth); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.EndObject); Assert.AreEqual(0, jsonReader.Depth); } } [Test] [ExpectedException(typeof(ArgumentNullException), ExpectedMessage = @"Value cannot be null. Parameter name: reader")] public void NullTextReader() { new JsonTextReader(null); } [Test] [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unterminated string. Expected delimiter: '. Line 1, position 3.")] public void UnexpectedEndOfString() { JsonReader reader = new JsonTextReader(new StringReader("'hi")); reader.Read(); } [Test] public void ReadNullTerminatorStrings() { JsonReader reader = new JsonTextReader(new StringReader("'h\0i'")); Assert.IsTrue(reader.Read()); Assert.AreEqual("h\0i", reader.Value); } [Test] [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end while parsing unicode character. Line 1, position 7.")] public void UnexpectedEndOfHex() { JsonReader reader = new JsonTextReader(new StringReader(@"'h\u006")); reader.Read(); } [Test] [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unterminated string. Expected delimiter: '. Line 1, position 3.")] public void UnexpectedEndOfControlCharacter() { JsonReader reader = new JsonTextReader(new StringReader(@"'h\")); reader.Read(); } [Test] [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected token when reading bytes: Boolean. Line 1, position 4.")] public void ReadBytesWithBadCharacter() { JsonReader reader = new JsonTextReader(new StringReader(@"true")); reader.ReadAsBytes(); } [Test] [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unterminated string. Expected delimiter: '. Line 1, position 17.")] public void ReadBytesWithUnexpectedEnd() { string helloWorld = "Hello world!"; byte[] helloWorldData = Encoding.UTF8.GetBytes(helloWorld); JsonReader reader = new JsonTextReader(new StringReader(@"'" + Convert.ToBase64String(helloWorldData))); reader.ReadAsBytes(); } [Test] [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end when reading bytes: Line 1, position 3.")] public void ReadBytesNoStartWithUnexpectedEnd() { JsonReader reader = new JsonTextReader(new StringReader(@"[ ")); Assert.IsTrue(reader.Read()); reader.ReadAsBytes(); } [Test] [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end when parsing unquoted property name. Line 1, position 4.")] public void UnexpectedEndWhenParsingUnquotedProperty() { JsonReader reader = new JsonTextReader(new StringReader(@"{aww")); Assert.IsTrue(reader.Read()); reader.Read(); } [Test] public void ParsingQuotedPropertyWithControlCharacters() { JsonReader reader = new JsonTextReader(new StringReader(@"{'hi\r\nbye':1}")); Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.AreEqual(@"hi bye", reader.Value); Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read()); Assert.IsFalse(reader.Read()); } [Test] public void ReadBytesFollowingNumberInArray() { string helloWorld = "Hello world!"; byte[] helloWorldData = Encoding.UTF8.GetBytes(helloWorld); JsonReader reader = new JsonTextReader(new StringReader(@"[1,'" + Convert.ToBase64String(helloWorldData) + @"']")); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartArray, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Integer, reader.TokenType); byte[] data = reader.ReadAsBytes(); Assert.AreEqual(helloWorldData, data); Assert.AreEqual(JsonToken.Bytes, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.EndArray, reader.TokenType); Assert.IsFalse(reader.Read()); } [Test] public void ReadBytesFollowingNumberInObject() { string helloWorld = "Hello world!"; byte[] helloWorldData = Encoding.UTF8.GetBytes(helloWorld); JsonReader reader = new JsonTextReader(new StringReader(@"{num:1,data:'" + Convert.ToBase64String(helloWorldData) + @"'}")); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Integer, reader.TokenType); Assert.IsTrue(reader.Read()); byte[] data = reader.ReadAsBytes(); Assert.AreEqual(helloWorldData, data); Assert.AreEqual(JsonToken.Bytes, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.EndObject, reader.TokenType); Assert.IsFalse(reader.Read()); } [Test] public void ReadingEscapedStrings() { string input = "{value:'Purple\\r \\n monkey\\'s:\\tdishwasher'}"; StringReader sr = new StringReader(input); using (JsonReader jsonReader = new JsonTextReader(sr)) { Assert.AreEqual(0, jsonReader.Depth); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.StartObject); Assert.AreEqual(0, jsonReader.Depth); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName); Assert.AreEqual(1, jsonReader.Depth); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.String); Assert.AreEqual(jsonReader.Value, "Purple\r \n monkey's:\tdishwasher"); Assert.AreEqual(jsonReader.QuoteChar, '\''); Assert.AreEqual(1, jsonReader.Depth); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.EndObject); Assert.AreEqual(0, jsonReader.Depth); } } [Test] public void ReadNewlineLastCharacter() { string input = @"{ CPU: 'Intel', Drives: [ /* Com*ment */ 'DVD read/writer', ""500 gigabyte hard drive"" ] }" + '\n'; object o = JsonConvert.DeserializeObject(input); } [Test] public void WriteReadWrite() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(true); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("integer"); jsonWriter.WriteValue(99); jsonWriter.WritePropertyName("string"); jsonWriter.WriteValue("how now brown cow?"); jsonWriter.WritePropertyName("array"); jsonWriter.WriteStartArray(); for (int i = 0; i < 5; i++) { jsonWriter.WriteValue(i); } jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("decimal"); jsonWriter.WriteValue(990.00990099m); jsonWriter.WriteEndObject(); jsonWriter.WriteValue(5); jsonWriter.WriteEndArray(); jsonWriter.WriteEndObject(); jsonWriter.WriteValue("This is a string."); jsonWriter.WriteNull(); jsonWriter.WriteNull(); jsonWriter.WriteEndArray(); } string json = sb.ToString(); JsonSerializer serializer = new JsonSerializer(); object jsonObject = serializer.Deserialize(new JsonTextReader(new StringReader(json))); sb = new StringBuilder(); sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { serializer.Serialize(sw, jsonObject); } Assert.AreEqual(json, sb.ToString()); } [Test] public void FloatingPointNonFiniteNumbers() { string input = @"[ NaN, Infinity, -Infinity ]"; StringReader sr = new StringReader(input); using (JsonReader jsonReader = new JsonTextReader(sr)) { jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.StartArray); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.Float); Assert.AreEqual(jsonReader.Value, double.NaN); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.Float); Assert.AreEqual(jsonReader.Value, double.PositiveInfinity); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.Float); Assert.AreEqual(jsonReader.Value, double.NegativeInfinity); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.EndArray); } } [Test] public void LongStringTest() { int length = 20000; string json = @"[""" + new string(' ', length) + @"""]"; JsonTextReader reader = new JsonTextReader(new StringReader(json)); reader.Read(); Assert.AreEqual(JsonToken.StartArray, reader.TokenType); reader.Read(); Assert.AreEqual(JsonToken.String, reader.TokenType); Assert.AreEqual(typeof(string), reader.ValueType); Assert.AreEqual(20000, reader.Value.ToString().Length); reader.Read(); Assert.AreEqual(JsonToken.EndArray, reader.TokenType); reader.Read(); Assert.AreEqual(JsonToken.EndArray, reader.TokenType); } [Test] public void EscapedUnicodeText() { string json = @"[""\u003c"",""\u5f20""]"; JsonTextReader reader = new JsonTextReader(new StringReader(json)); reader.Read(); Assert.AreEqual(JsonToken.StartArray, reader.TokenType); reader.Read(); Assert.AreEqual("<", reader.Value); reader.Read(); Assert.AreEqual(24352, Convert.ToInt32(Convert.ToChar((string)reader.Value))); reader.Read(); Assert.AreEqual(JsonToken.EndArray, reader.TokenType); } [Test] public void ReadFloatingPointNumber() { string json = @"[0.0,0.0,0.1,1.0,1.000001,1E-06,4.94065645841247E-324,Infinity,-Infinity,NaN,1.7976931348623157E+308,-1.7976931348623157E+308,Infinity,-Infinity,NaN]"; using (JsonReader jsonReader = new JsonTextReader(new StringReader(json))) { jsonReader.Read(); Assert.AreEqual(JsonToken.StartArray, jsonReader.TokenType); jsonReader.Read(); Assert.AreEqual(JsonToken.Float, jsonReader.TokenType); Assert.AreEqual(0.0, jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.Float, jsonReader.TokenType); Assert.AreEqual(0.0, jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.Float, jsonReader.TokenType); Assert.AreEqual(0.1, jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.Float, jsonReader.TokenType); Assert.AreEqual(1.0, jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.Float, jsonReader.TokenType); Assert.AreEqual(1.000001, jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.Float, jsonReader.TokenType); Assert.AreEqual(1E-06, jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.Float, jsonReader.TokenType); Assert.AreEqual(4.94065645841247E-324, jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.Float, jsonReader.TokenType); Assert.AreEqual(double.PositiveInfinity, jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.Float, jsonReader.TokenType); Assert.AreEqual(double.NegativeInfinity, jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.Float, jsonReader.TokenType); Assert.AreEqual(double.NaN, jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.Float, jsonReader.TokenType); Assert.AreEqual(double.MaxValue, jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.Float, jsonReader.TokenType); Assert.AreEqual(double.MinValue, jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.Float, jsonReader.TokenType); Assert.AreEqual(double.PositiveInfinity, jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.Float, jsonReader.TokenType); Assert.AreEqual(double.NegativeInfinity, jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.Float, jsonReader.TokenType); Assert.AreEqual(double.NaN, jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.EndArray, jsonReader.TokenType); } } [Test] [ExpectedException(typeof(JsonReaderException), ExpectedMessage = @"Invalid character after parsing property name. Expected ':' but got: "". Line 3, position 9.")] public void MissingColon() { string json = @"{ ""A"" : true, ""B"" ""hello"", // Notice the colon is missing ""C"" : ""bye"" }"; JsonTextReader reader = new JsonTextReader(new StringReader(json)); reader.Read(); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); reader.Read(); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); reader.Read(); Assert.AreEqual(JsonToken.Boolean, reader.TokenType); reader.Read(); } [Test] public void ReadSingleBytes() { StringReader s = new StringReader(@"""SGVsbG8gd29ybGQu"""); JsonTextReader reader = new JsonTextReader(s); byte[] data = reader.ReadAsBytes(); Assert.IsNotNull(data); string text = Encoding.UTF8.GetString(data, 0, data.Length); Assert.AreEqual("Hello world.", text); } [Test] public void ReadOctalNumber() { StringReader s = new StringReader(@"[0372, 0xFA, 0XFA]"); JsonTextReader jsonReader = new JsonTextReader(s); Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(JsonToken.StartArray, jsonReader.TokenType); Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(JsonToken.Integer, jsonReader.TokenType); Assert.AreEqual(250, jsonReader.Value); Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(JsonToken.Integer, jsonReader.TokenType); Assert.AreEqual(250, jsonReader.Value); Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(JsonToken.Integer, jsonReader.TokenType); Assert.AreEqual(250, jsonReader.Value); Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(JsonToken.EndArray, jsonReader.TokenType); Assert.IsFalse(jsonReader.Read()); } [Test] public void ReadUnicode() { string json = @"{""Message"":""Hi,I\u0092ve send you smth""}"; JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.AreEqual("Message", reader.Value); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.String, reader.TokenType); Assert.AreEqual(@"Hi,I" + '\u0092' + "ve send you smth", reader.Value); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.EndObject, reader.TokenType); Assert.IsFalse(reader.Read()); } [Test] public void ReadHexidecimalWithAllLetters() { string json = @"{""text"":0xabcdef12345}"; JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Integer, reader.TokenType); Assert.AreEqual(11806310474565, reader.Value); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.EndObject, reader.TokenType); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using Hyak.Common; using Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.Properties; using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models; namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery { /// <summary> /// Retrieves Azure Site Protectable Item. /// </summary> [Cmdlet( VerbsCommon.Get, "AzureRmRecoveryServicesAsrProtectableItem", DefaultParameterSetName = ASRParameterSets.ByObject)] [Alias("Get-ASRProtectableItem")] [OutputType(typeof(IEnumerable<ASRProtectableItem>))] public class GetAzureRmRecoveryServicesAsrProtectableItem : SiteRecoveryCmdletBase { /// <summary> /// Gets or sets Name of the Protectable Item. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.ByObjectWithName, Mandatory = true)] [ValidateNotNullOrEmpty] public string Name { get; set; } /// <summary> /// Gets or sets friendly name of the Protectable Item. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.ByObjectWithFriendlyName, Mandatory = true)] [ValidateNotNullOrEmpty] public string FriendlyName { get; set; } /// <summary> /// Gets or sets Server Object. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.ByObject, Mandatory = true, ValueFromPipeline = true)] [Parameter( ParameterSetName = ASRParameterSets.ByObjectWithName, Mandatory = true, ValueFromPipeline = true)] [Parameter( ParameterSetName = ASRParameterSets.ByObjectWithFriendlyName, Mandatory = true, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public ASRProtectionContainer ProtectionContainer { get; set; } /// <summary> /// ProcessRecord of the command. /// </summary> public override void ExecuteSiteRecoveryCmdlet() { base.ExecuteSiteRecoveryCmdlet(); switch (this.ParameterSetName) { case ASRParameterSets.ByObject: this.GetAll(); break; case ASRParameterSets.ByObjectWithName: this.GetByName(); break; case ASRParameterSets.ByObjectWithFriendlyName: this.GetByFriendlyName(); break; } } /// <summary> /// Queries all Protection Entities under given Protection Container. /// </summary> private void GetAll() { var protectableItemListResponse = this.RecoveryServicesClient .GetAzureSiteRecoveryProtectableItem( Utilities.GetValueFromArmId( this.ProtectionContainer.ID, ARMResourceTypeConstants.ReplicationFabrics), this.ProtectionContainer.Name); this.WriteProtectableItems(protectableItemListResponse); } /// <summary> /// Queries by friendly name. /// </summary> private void GetByFriendlyName() { var found = false; var protectableItemListResponse = this.RecoveryServicesClient .GetAzureSiteRecoveryProtectableItem( Utilities.GetValueFromArmId( this.ProtectionContainer.ID, ARMResourceTypeConstants.ReplicationFabrics), this.ProtectionContainer.Name); var friendlyNameListResponse = protectableItemListResponse.FindAll( t => string.Compare( t.Properties.FriendlyName, this.FriendlyName, StringComparison.OrdinalIgnoreCase) == 0); foreach (var protectableItem in friendlyNameListResponse) { var protectableItemResponse = this.RecoveryServicesClient .GetAzureSiteRecoveryProtectableItem( Utilities.GetValueFromArmId( this.ProtectionContainer.ID, ARMResourceTypeConstants.ReplicationFabrics), this.ProtectionContainer.Name, protectableItem.Name); this.WriteProtectableItem(protectableItemResponse); found = true; } if (!found) { throw new InvalidOperationException( string.Format( Resources.ProtectionEntityNotFound, this.FriendlyName, this.ProtectionContainer.FriendlyName)); } } /// <summary> /// Queries by Name. /// </summary> private void GetByName() { try { var protectableItemResponse = this.RecoveryServicesClient .GetAzureSiteRecoveryProtectableItem( Utilities.GetValueFromArmId( this.ProtectionContainer.ID, ARMResourceTypeConstants.ReplicationFabrics), this.ProtectionContainer.Name, this.Name); if (protectableItemResponse != null) { this.WriteProtectableItem(protectableItemResponse); } } catch (CloudException ex) { if (string.Compare( ex.Error.Code, "NotFound", StringComparison.OrdinalIgnoreCase) == 0) { throw new InvalidOperationException( string.Format( Resources.ProtectableItemNotFound, this.Name, this.ProtectionContainer.FriendlyName)); } throw; } } /// <summary> /// Write Protection Items /// </summary> /// <param name="protectableItem"></param> private void WriteProtectableItem( ProtectableItem protectableItem) { this.WriteObject(new ASRProtectableItem(protectableItem)); } /// <summary> /// Write Protection Items /// </summary> /// <param name="protectableItems">List of protectable items</param> private void WriteProtectableItems( IList<ProtectableItem> protectableItems) { this.WriteObject( protectableItems.Select(pi => new ASRProtectableItem(pi)), true); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Runtime.Remoting.Lifetime; using System.Threading; using System.Reflection; using System.Collections; using System.Collections.Generic; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ScriptEngine.Interfaces; using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces; using integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; using vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; using rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list; using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat; using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase { public partial class ScriptBaseClass : MarshalByRefObject { public IOSSL_Api m_OSSL_Functions; public void ApiTypeOSSL(IScriptApi api) { if (!(api is IOSSL_Api)) return; m_OSSL_Functions = (IOSSL_Api)api; Prim = new OSSLPrim(this); } public void osSetRegionWaterHeight(double height) { m_OSSL_Functions.osSetRegionWaterHeight(height); } public void osSetRegionSunSettings(bool useEstateSun, bool sunFixed, double sunHour) { m_OSSL_Functions.osSetRegionSunSettings(useEstateSun, sunFixed, sunHour); } public void osSetEstateSunSettings(bool sunFixed, double sunHour) { m_OSSL_Functions.osSetEstateSunSettings(sunFixed, sunHour); } public double osGetCurrentSunHour() { return m_OSSL_Functions.osGetCurrentSunHour(); } public double osSunGetParam(string param) { return m_OSSL_Functions.osSunGetParam(param); } public void osSunSetParam(string param, double value) { m_OSSL_Functions.osSunSetParam(param, value); } public string osWindActiveModelPluginName() { return m_OSSL_Functions.osWindActiveModelPluginName(); } // Not yet plugged in as available OSSL functions, so commented out // void osWindParamSet(string plugin, string param, float value) // { // m_OSSL_Functions.osWindParamSet(plugin, param, value); // } // // float osWindParamGet(string plugin, string param) // { // return m_OSSL_Functions.osWindParamGet(plugin, param); // } public void osParcelJoin(vector pos1, vector pos2) { m_OSSL_Functions.osParcelJoin(pos1,pos2); } public void osParcelSubdivide(vector pos1, vector pos2) { m_OSSL_Functions.osParcelSubdivide(pos1, pos2); } public void osParcelSetDetails(vector pos, LSL_List rules) { m_OSSL_Functions.osParcelSetDetails(pos,rules); } public double osList2Double(LSL_Types.list src, int index) { return m_OSSL_Functions.osList2Double(src, index); } public string osSetDynamicTextureURL(string dynamicID, string contentType, string url, string extraParams, int timer) { return m_OSSL_Functions.osSetDynamicTextureURL(dynamicID, contentType, url, extraParams, timer); } public string osSetDynamicTextureData(string dynamicID, string contentType, string data, string extraParams, int timer) { return m_OSSL_Functions.osSetDynamicTextureData(dynamicID, contentType, data, extraParams, timer); } public string osSetDynamicTextureURLBlend(string dynamicID, string contentType, string url, string extraParams, int timer, int alpha) { return m_OSSL_Functions.osSetDynamicTextureURLBlend(dynamicID, contentType, url, extraParams, timer, alpha); } public string osSetDynamicTextureDataBlend(string dynamicID, string contentType, string data, string extraParams, int timer, int alpha) { return m_OSSL_Functions.osSetDynamicTextureDataBlend(dynamicID, contentType, data, extraParams, timer, alpha); } public string osSetDynamicTextureURLBlendFace(string dynamicID, string contentType, string url, string extraParams, bool blend, int disp, int timer, int alpha, int face) { return m_OSSL_Functions.osSetDynamicTextureURLBlendFace(dynamicID, contentType, url, extraParams, blend, disp, timer, alpha, face); } public string osSetDynamicTextureDataBlendFace(string dynamicID, string contentType, string data, string extraParams, bool blend, int disp, int timer, int alpha, int face) { return m_OSSL_Functions.osSetDynamicTextureDataBlendFace(dynamicID, contentType, data, extraParams, blend, disp, timer, alpha, face); } public LSL_Float osTerrainGetHeight(int x, int y) { return m_OSSL_Functions.osTerrainGetHeight(x, y); } public LSL_Integer osTerrainSetHeight(int x, int y, double val) { return m_OSSL_Functions.osTerrainSetHeight(x, y, val); } public void osTerrainFlush() { m_OSSL_Functions.osTerrainFlush(); } public int osRegionRestart(double seconds) { return m_OSSL_Functions.osRegionRestart(seconds); } public void osRegionNotice(string msg) { m_OSSL_Functions.osRegionNotice(msg); } public bool osConsoleCommand(string Command) { return m_OSSL_Functions.osConsoleCommand(Command); } public void osSetParcelMediaURL(string url) { m_OSSL_Functions.osSetParcelMediaURL(url); } public void osSetParcelSIPAddress(string SIPAddress) { m_OSSL_Functions.osSetParcelSIPAddress(SIPAddress); } public void osSetPrimFloatOnWater(int floatYN) { m_OSSL_Functions.osSetPrimFloatOnWater(floatYN); } // Teleport Functions public void osTeleportAgent(string agent, string regionName, vector position, vector lookat) { m_OSSL_Functions.osTeleportAgent(agent, regionName, position, lookat); } public void osTeleportAgent(string agent, int regionX, int regionY, vector position, vector lookat) { m_OSSL_Functions.osTeleportAgent(agent, regionX, regionY, position, lookat); } public void osTeleportAgent(string agent, vector position, vector lookat) { m_OSSL_Functions.osTeleportAgent(agent, position, lookat); } // Avatar info functions public string osGetAgentIP(string agent) { return m_OSSL_Functions.osGetAgentIP(agent); } public LSL_List osGetAgents() { return m_OSSL_Functions.osGetAgents(); } // Animation Functions public void osAvatarPlayAnimation(string avatar, string animation) { m_OSSL_Functions.osAvatarPlayAnimation(avatar, animation); } public void osAvatarStopAnimation(string avatar, string animation) { m_OSSL_Functions.osAvatarStopAnimation(avatar, animation); } //Texture Draw functions public string osMovePen(string drawList, int x, int y) { return m_OSSL_Functions.osMovePen(drawList, x, y); } public string osDrawLine(string drawList, int startX, int startY, int endX, int endY) { return m_OSSL_Functions.osDrawLine(drawList, startX, startY, endX, endY); } public string osDrawLine(string drawList, int endX, int endY) { return m_OSSL_Functions.osDrawLine(drawList, endX, endY); } public string osDrawText(string drawList, string text) { return m_OSSL_Functions.osDrawText(drawList, text); } public string osDrawEllipse(string drawList, int width, int height) { return m_OSSL_Functions.osDrawEllipse(drawList, width, height); } public string osDrawRectangle(string drawList, int width, int height) { return m_OSSL_Functions.osDrawRectangle(drawList, width, height); } public string osDrawFilledRectangle(string drawList, int width, int height) { return m_OSSL_Functions.osDrawFilledRectangle(drawList, width, height); } public string osDrawPolygon(string drawList, LSL_List x, LSL_List y) { return m_OSSL_Functions.osDrawPolygon(drawList, x, y); } public string osDrawFilledPolygon(string drawList, LSL_List x, LSL_List y) { return m_OSSL_Functions.osDrawFilledPolygon(drawList, x, y); } public string osSetFontSize(string drawList, int fontSize) { return m_OSSL_Functions.osSetFontSize(drawList, fontSize); } public string osSetFontName(string drawList, string fontName) { return m_OSSL_Functions.osSetFontName(drawList, fontName); } public string osSetPenSize(string drawList, int penSize) { return m_OSSL_Functions.osSetPenSize(drawList, penSize); } public string osSetPenCap(string drawList, string direction, string type) { return m_OSSL_Functions.osSetPenCap(drawList, direction, type); } public string osSetPenColour(string drawList, string colour) { return m_OSSL_Functions.osSetPenColour(drawList, colour); } public string osDrawImage(string drawList, int width, int height, string imageUrl) { return m_OSSL_Functions.osDrawImage(drawList, width, height, imageUrl); } public vector osGetDrawStringSize(string contentType, string text, string fontName, int fontSize) { return m_OSSL_Functions.osGetDrawStringSize(contentType, text, fontName, fontSize); } public void osSetStateEvents(int events) { m_OSSL_Functions.osSetStateEvents(events); } public string osGetScriptEngineName() { return m_OSSL_Functions.osGetScriptEngineName(); } public string osGetSimulatorVersion() { return m_OSSL_Functions.osGetSimulatorVersion(); } public Hashtable osParseJSON(string JSON) { return m_OSSL_Functions.osParseJSON(JSON); } public void osMessageObject(key objectUUID,string message) { m_OSSL_Functions.osMessageObject(objectUUID,message); } public void osMakeNotecard(string notecardName, LSL_Types.list contents) { m_OSSL_Functions.osMakeNotecard(notecardName, contents); } public string osGetNotecardLine(string name, int line) { return m_OSSL_Functions.osGetNotecardLine(name, line); } public string osGetNotecard(string name) { return m_OSSL_Functions.osGetNotecard(name); } public int osGetNumberOfNotecardLines(string name) { return m_OSSL_Functions.osGetNumberOfNotecardLines(name); } public string osAvatarName2Key(string firstname, string lastname) { return m_OSSL_Functions.osAvatarName2Key(firstname, lastname); } public string osKey2Name(string id) { return m_OSSL_Functions.osKey2Name(id); } public string osGetGridNick() { return m_OSSL_Functions.osGetGridNick(); } public string osGetGridName() { return m_OSSL_Functions.osGetGridName(); } public string osGetGridLoginURI() { return m_OSSL_Functions.osGetGridLoginURI(); } public LSL_String osFormatString(string str, LSL_List strings) { return m_OSSL_Functions.osFormatString(str, strings); } public LSL_List osMatchString(string src, string pattern, int start) { return m_OSSL_Functions.osMatchString(src, pattern, start); } // Information about data loaded into the region public string osLoadedCreationDate() { return m_OSSL_Functions.osLoadedCreationDate(); } public string osLoadedCreationTime() { return m_OSSL_Functions.osLoadedCreationTime(); } public string osLoadedCreationID() { return m_OSSL_Functions.osLoadedCreationID(); } public LSL_List osGetLinkPrimitiveParams(int linknumber, LSL_List rules) { return m_OSSL_Functions.osGetLinkPrimitiveParams(linknumber, rules); } public key osNpcCreate(string user, string name, vector position, key cloneFrom) { return m_OSSL_Functions.osNpcCreate(user, name, position, cloneFrom); } public void osNpcMoveTo(key npc, vector position) { m_OSSL_Functions.osNpcMoveTo(npc, position); } public void osNpcSay(key npc, string message) { m_OSSL_Functions.osNpcSay(npc, message); } public void osNpcRemove(key npc) { m_OSSL_Functions.osNpcRemove(npc); } public OSSLPrim Prim; [Serializable] public class OSSLPrim { internal ScriptBaseClass OSSL; public OSSLPrim(ScriptBaseClass bc) { OSSL = bc; Position = new OSSLPrim_Position(this); Rotation = new OSSLPrim_Rotation(this); } public OSSLPrim_Position Position; public OSSLPrim_Rotation Rotation; private TextStruct _text; public TextStruct Text { get { return _text; } set { _text = value; OSSL.llSetText(_text.Text, _text.color, _text.alpha); } } [Serializable] public struct TextStruct { public string Text; public LSL_Types.Vector3 color; public double alpha; } } [Serializable] public class OSSLPrim_Position { private OSSLPrim prim; private LSL_Types.Vector3 Position; public OSSLPrim_Position(OSSLPrim _prim) { prim = _prim; } private void Load() { Position = prim.OSSL.llGetPos(); } private void Save() { if (Position.x > ((int)Constants.RegionSize - 1)) Position.x = ((int)Constants.RegionSize - 1); if (Position.x < 0) Position.x = 0; if (Position.y > ((int)Constants.RegionSize - 1)) Position.y = ((int)Constants.RegionSize - 1); if (Position.y < 0) Position.y = 0; if (Position.z > 768) Position.z = 768; if (Position.z < 0) Position.z = 0; prim.OSSL.llSetPos(Position); } public double x { get { Load(); return Position.x; } set { Load(); Position.x = value; Save(); } } public double y { get { Load(); return Position.y; } set { Load(); Position.y = value; Save(); } } public double z { get { Load(); return Position.z; } set { Load(); Position.z = value; Save(); } } } [Serializable] public class OSSLPrim_Rotation { private OSSLPrim prim; private LSL_Types.Quaternion Rotation; public OSSLPrim_Rotation(OSSLPrim _prim) { prim = _prim; } private void Load() { Rotation = prim.OSSL.llGetRot(); } private void Save() { prim.OSSL.llSetRot(Rotation); } public double x { get { Load(); return Rotation.x; } set { Load(); Rotation.x = value; Save(); } } public double y { get { Load(); return Rotation.y; } set { Load(); Rotation.y = value; Save(); } } public double z { get { Load(); return Rotation.z; } set { Load(); Rotation.z = value; Save(); } } public double s { get { Load(); return Rotation.s; } set { Load(); Rotation.s = value; Save(); } } } public key osGetMapTexture() { return m_OSSL_Functions.osGetMapTexture(); } public key osGetRegionMapTexture(string regionName) { return m_OSSL_Functions.osGetRegionMapTexture(regionName); } public LSL_List osGetRegionStats() { return m_OSSL_Functions.osGetRegionStats(); } /// <summary> /// Returns the amount of memory in use by the Simulator Daemon. /// Amount in bytes - if >= 4GB, returns 4GB. (LSL is not 64-bit aware) /// </summary> /// <returns></returns> public LSL_Integer osGetSimulatorMemory() { return m_OSSL_Functions.osGetSimulatorMemory(); } public void osKickAvatar(string FirstName,string SurName,string alert) { m_OSSL_Functions.osKickAvatar(FirstName, SurName, alert); } public void osSetSpeed(string UUID, float SpeedModifier) { m_OSSL_Functions.osSetSpeed(UUID, SpeedModifier); } public void osCauseDamage(string avatar, double damage) { m_OSSL_Functions.osCauseDamage(avatar, damage); } public void osCauseHealing(string avatar, double healing) { m_OSSL_Functions.osCauseHealing(avatar, healing); } public LSL_List osGetPrimitiveParams(LSL_Key prim, LSL_List rules) { return m_OSSL_Functions.osGetPrimitiveParams(prim, rules); } public void osSetPrimitiveParams(LSL_Key prim, LSL_List rules) { m_OSSL_Functions.osSetPrimitiveParams(prim, rules); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace East.Tool.UseCaseTranslator.WebAPI.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; /// <summary> /// System.Enum.IConvertibleToUint16(System.Type,IFormatProvider ) /// </summary> public class EnumIConvertibleToUint16 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Convert an enum of zero to Uint16"); try { color c1 = color.blue; IConvertible i1 = c1 as IConvertible; UInt16 u1 = i1.ToUInt16(null); if (u1 != 0) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Test a system defined enum type"); try { Enum e2 = System.StringComparison.CurrentCultureIgnoreCase; UInt16 l2 = (e2 as IConvertible).ToUInt16(null); if (l2 != 1) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Convert an enum of Uint16.maxvalue to uint16"); try { color c1 = color.white; IConvertible i1 = c1 as IConvertible; UInt16 u1 = i1.ToUInt16(null); if (u1 != UInt16.MaxValue) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Convert an enum of negative zero to Uint16 "); try { color c1 = color.red; IConvertible i1 = c1 as IConvertible; UInt16 u1 = i1.ToUInt16(null); if (u1 != 0) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: Convert an enum of negative value to Uint16"); try { e_test e1 = e_test.itemA; IConvertible i1 = e1 as IConvertible; UInt16 u1 = i1.ToUInt16(null); TestLibrary.TestFramework.LogError("101", "The OverflowException was not thrown as expected"); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: Convert an enum of the value which is bigger than uint16.maxvalue to Uint16"); try { e_test e1 = e_test.itemB; IConvertible i1 = e1 as IConvertible; UInt16 u1 = i1.ToUInt16(null); TestLibrary.TestFramework.LogError("103", "The OverflowException was not thrown as expected"); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { EnumIConvertibleToUint16 test = new EnumIConvertibleToUint16(); TestLibrary.TestFramework.BeginTestCase("EnumIConvertibleToUint16"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } enum color { blue = 0, white = UInt16.MaxValue, red = -0, } enum e_test : long { itemA = -123, itemB = Int32.MaxValue, itemC = Int64.MaxValue, itemD = -0, } }
// // WindowBackend.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // Andres G. Aragoneses <andres.aragoneses@7digital.com> // Konrad M. Kruczynski <kkruczynski@antmicro.com> // // Copyright (c) 2011 Xamarin Inc // Copyright (c) 2012 7Digital Media Ltd // Copyright (c) 2016 Antmicro Ltd // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Linq; using AppKit; using CoreGraphics; using Foundation; using ObjCRuntime; using Xwt.Backends; using Xwt.Drawing; namespace Xwt.Mac { public class WindowBackend: NSWindow, IWindowBackend, IMacWindowBackend, INSWindowDelegate { WindowBackendController controller; IWindowFrameEventSink eventSink; Window frontend; ViewBackend child; NSView childView; bool sensitive = true; WindowFrameEvent eventsEnabled; public WindowBackend (IntPtr ptr): base (ptr) { } public WindowBackend () { this.controller = new WindowBackendController (); controller.Window = this; StyleMask |= NSWindowStyle.Resizable | NSWindowStyle.Closable | NSWindowStyle.Miniaturizable; AutorecalculatesKeyViewLoop = true; ContentView.AutoresizesSubviews = true; ContentView.Hidden = true; // TODO: do it only if mouse move events are enabled in a widget AcceptsMouseMovedEvents = true; Center (); WeakDelegate = this; } object IWindowFrameBackend.Window { get { return this; } } public IntPtr NativeHandle { get { return Handle; } } public IWindowFrameEventSink EventSink { get { return (IWindowFrameEventSink)eventSink; } } public virtual void InitializeBackend (object frontend, ApplicationContext context) { this.ApplicationContext = context; this.frontend = (Window) frontend; } public void Initialize (IWindowFrameEventSink eventSink) { this.eventSink = eventSink; } public ApplicationContext ApplicationContext { get; private set; } public object NativeWidget { get { return this; } } public string Name { get; set; } void IMacWindowBackend.InternalShow () { InternalShow (); } internal void InternalShow () { MakeKeyAndOrderFront (MacEngine.App); if (ParentWindow != null) { if (!ParentWindow.ChildWindows.Contains(this)) ParentWindow.AddChildWindow(this, NSWindowOrderingMode.Above); // always use NSWindow for alignment when running in guest mode and // don't rely on AddChildWindow to position the window correctly if (frontend.InitialLocation == WindowLocation.CenterParent && !(ParentWindow is WindowBackend)) { var parentBounds = MacDesktopBackend.ToDesktopRect(ParentWindow.ContentRectFor(ParentWindow.Frame)); var bounds = ((IWindowFrameBackend)this).Bounds; bounds.X = parentBounds.Center.X - (Frame.Width / 2); bounds.Y = parentBounds.Center.Y - (Frame.Height / 2); ((IWindowFrameBackend)this).Bounds = bounds; } } } public void Present () { InternalShow(); } public bool Visible { get { return IsVisible; } set { if (value) MacEngine.App.ShowWindow(this); ContentView.Hidden = !value; // handle shown/hidden events IsVisible = value; } } public double Opacity { get { return AlphaValue; } set { AlphaValue = (float)value; } } Color IWindowBackend.BackgroundColor { get { return BackgroundColor.ToXwtColor (); } set { BackgroundColor = value.ToNSColor (); } } public bool Sensitive { get { return sensitive; } set { sensitive = value; if (child != null) child.UpdateSensitiveStatus (child.Widget, sensitive); } } public bool HasFocus { get { return IsKeyWindow; } } public bool FullScreen { get { if (MacSystemInformation.OsVersion < MacSystemInformation.Lion) return false; return (StyleMask & NSWindowStyle.FullScreenWindow) != 0; } set { if (MacSystemInformation.OsVersion < MacSystemInformation.Lion) return; if (value != ((StyleMask & NSWindowStyle.FullScreenWindow) != 0)) ToggleFullScreen (null); } } object IWindowFrameBackend.Screen { get { return Screen; } } #region IWindowBackend implementation void IBackend.EnableEvent (object eventId) { if (eventId is WindowFrameEvent) { var @event = (WindowFrameEvent)eventId; switch (@event) { case WindowFrameEvent.Hidden: case WindowFrameEvent.Shown: if (!VisibilityEventsEnabled()) { ContentView.AddObserver(this, HiddenProperty, NSKeyValueObservingOptions.New, IntPtr.Zero); } break; } eventsEnabled |= @event; } } [Export ("windowDidResize:")] new void DidResize (NSNotification notification) { OnBoundsChanged(); } [Export ("windowDidMove:")] new void DidMove (NSNotification notification) { OnBoundsChanged (); } [Export("windowShouldClose:")] new bool WindowShouldClose (NSObject sender) { return closePerformed = RequestClose (); } [Export ("windowWillClose:")] new void WillClose (NSNotification notification) { OnHidden (); OnClosed (); } internal bool RequestClose () { bool res = true; ApplicationContext.InvokeUserCode (() => res = eventSink.OnCloseRequested ()); return res; } protected virtual void OnClosed () { if (!disposing) ApplicationContext.InvokeUserCode (eventSink.OnClosed); } bool closePerformed; bool IWindowFrameBackend.Close () { closePerformed = true; if ((StyleMask & NSWindowStyle.Titled) != 0 && (StyleMask & NSWindowStyle.Closable) != 0) PerformClose(this); else Close (); if (ParentWindow != null) ParentWindow.RemoveChildWindow(this); return closePerformed; } bool VisibilityEventsEnabled () { return eventsEnabled.HasFlag(WindowFrameEvent.Hidden) || eventsEnabled.HasFlag(WindowFrameEvent.Shown); } NSString HiddenProperty { get { return new NSString ("hidden"); } } public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context) { if (keyPath.IsEqual (HiddenProperty) && ofObject.Equals (ContentView)) { if (ContentView.Hidden) { OnHidden (); } else { OnShown (); } } } void OnHidden () { if (eventsEnabled.HasFlag (WindowFrameEvent.Hidden)) { ApplicationContext.InvokeUserCode (eventSink.OnHidden); } } void OnShown () { if (eventsEnabled.HasFlag (WindowFrameEvent.Shown)) { ApplicationContext.InvokeUserCode (eventSink.OnShown); } } void IBackend.DisableEvent (object eventId) { if (eventId is WindowFrameEvent) { var @event = (WindowFrameEvent)eventId; eventsEnabled &= ~@event; switch (@event) { case WindowFrameEvent.Hidden: case WindowFrameEvent.Shown: if (!VisibilityEventsEnabled()) { ContentView.RemoveObserver(this, HiddenProperty); } break; } } } protected virtual void OnBoundsChanged () { LayoutWindow (); if (eventsEnabled.HasFlag(WindowFrameEvent.BoundsChanged)) { ApplicationContext.InvokeUserCode(delegate { eventSink.OnBoundsChanged(((IWindowBackend)this).Bounds); }); } } void IWindowBackend.SetChild (IWidgetBackend child) { if (this.child != null) { ViewBackend.RemoveChildPlacement (this.child.Widget); this.child.Widget.RemoveFromSuperview (); childView = null; } this.child = (ViewBackend) child; if (child != null) { childView = ViewBackend.GetWidgetWithPlacement (child); ContentView.AddSubview (childView); LayoutWindow (); childView.AutoresizingMask = NSViewResizingMask.HeightSizable | NSViewResizingMask.WidthSizable; } } public virtual void UpdateChildPlacement (IWidgetBackend childBackend) { var w = ViewBackend.SetChildPlacement (childBackend); LayoutWindow (); w.AutoresizingMask = NSViewResizingMask.HeightSizable | NSViewResizingMask.WidthSizable; } bool IWindowFrameBackend.Decorated { get { return (StyleMask & NSWindowStyle.Titled) != 0; } set { if (value) StyleMask |= NSWindowStyle.Titled; else StyleMask &= ~(NSWindowStyle.Titled | NSWindowStyle.Borderless); } } bool IWindowFrameBackend.ShowInTaskbar { get { return false; } set { } } void IWindowFrameBackend.SetTransientFor (IWindowFrameBackend window) { if (!((IWindowFrameBackend)this).ShowInTaskbar) StyleMask &= ~NSWindowStyle.Miniaturizable; var win = window as NSWindow ?? ApplicationContext.Toolkit.GetNativeWindow(window) as NSWindow; if (ParentWindow != win) { // remove from the previous parent if (ParentWindow != null) ParentWindow.RemoveChildWindow(this); ParentWindow = win; // A window must be visible to be added to a parent. See InternalShow(). if (Visible) ParentWindow.AddChildWindow(this, NSWindowOrderingMode.Above); } } bool IWindowFrameBackend.Resizable { get { return (StyleMask & NSWindowStyle.Resizable) != 0; } set { if (value) StyleMask |= NSWindowStyle.Resizable; else StyleMask &= ~NSWindowStyle.Resizable; } } public void SetPadding (double left, double top, double right, double bottom) { LayoutWindow (); } void IWindowFrameBackend.Move (double x, double y) { var r = FrameRectFor (new CGRect ((nfloat)x, (nfloat)y, Frame.Width, Frame.Height)); SetFrame (r, true); } void IWindowFrameBackend.SetSize (double width, double height) { var cr = ContentRectFor (Frame); if (width == -1) width = cr.Width; if (height == -1) height = cr.Height; var r = FrameRectFor (new CGRect ((nfloat)cr.X, (nfloat)cr.Y, (nfloat)width, (nfloat)height)); // preserve window location, FrameRectFor will not adjust the left-bottom corner automatically var oldFrame = Frame; if (!oldFrame.IsEmpty) { r.Y = (oldFrame.Y + oldFrame.Height) - r.Height; } SetFrame (r, true); LayoutWindow (); } Rectangle IWindowFrameBackend.Bounds { get { var b = ContentRectFor (Frame); var r = MacDesktopBackend.ToDesktopRect (b); return new Rectangle ((int)r.X, (int)r.Y, (int)r.Width, (int)r.Height); } set { var r = MacDesktopBackend.FromDesktopRect (value); var fr = FrameRectFor (r); SetFrame (fr, true); } } public void SetMainMenu (IMenuBackend menu) { var m = (MenuBackend) menu; m.SetMainMenuMode (); NSApplication.SharedApplication.Menu = m; // base.Menu = m; } #endregion static Selector closeSel = new Selector ("close"); static readonly bool XamMacDangerousDispose = Version.Parse(Constants.Version) < new Version(5, 6); bool disposing, disposed; protected override void Dispose(bool disposing) { if (!disposed && disposing) { this.disposing = true; try { if (VisibilityEventsEnabled() && ContentView != null) ContentView.RemoveObserver(this, HiddenProperty); if (XamMacDangerousDispose) { // HACK: Xamarin.Mac/MonoMac limitation: no direct way to release a window manually // A NSWindow instance will be removed from NSApplication.SharedApplication.Windows // only if it is being closed with ReleasedWhenClosed set to true but not on Dispose // and there is no managed way to tell Cocoa to release the window manually (and to // remove it from the active window list). // see also: https://bugzilla.xamarin.com/show_bug.cgi?id=45298 // WORKAROUND: // bump native reference count by calling DangerousRetain() // base.Dispose will now unref the window correctly without crashing DangerousRetain(); } // tell Cocoa to release the window on Close ReleasedWhenClosed = true; // Close the window (Cocoa will do its job even if the window is already closed) Messaging.void_objc_msgSend (this.Handle, closeSel.Handle); } finally { this.disposing = false; this.disposed = true; } } if (controller != null) { controller.Dispose (); controller = null; } base.Dispose (disposing); } public void DragStart (TransferDataSource data, DragDropAction dragAction, object dragImage, double xhot, double yhot) { throw new NotImplementedException (); } public void SetDragSource (string[] types, DragDropAction dragAction) { } public void SetDragTarget (string[] types, DragDropAction dragAction) { } public virtual void SetMinSize (Size s) { var b = ((IWindowBackend)this).Bounds; if (b.Size.Width < s.Width) b.Width = s.Width; if (b.Size.Height < s.Height) b.Height = s.Height; if (b != ((IWindowBackend)this).Bounds) ((IWindowBackend)this).Bounds = b; var r = FrameRectFor (new CGRect (0, 0, (nfloat)s.Width, (nfloat)s.Height)); MinSize = r.Size; } public void SetIcon (ImageDescription icon) { } public virtual void GetMetrics (out Size minSize, out Size decorationSize) { minSize = decorationSize = Size.Zero; } public virtual void LayoutWindow () { LayoutContent (ContentView.Frame); } public void LayoutContent (CGRect frame) { if (child != null) { frame.X += (nfloat) frontend.Padding.Left; frame.Width -= (nfloat) (frontend.Padding.HorizontalSpacing); frame.Y += (nfloat) (childView.IsFlipped ? frontend.Padding.Bottom : frontend.Padding.Top); frame.Height -= (nfloat) (frontend.Padding.VerticalSpacing); childView.Frame = frame; } } public override bool ConformsToProtocol (IntPtr protocol) { // HACK: for some reason on systems with a TouchBar this might be called // after the window has been closed and released, resulting in // an ObjectDisposedException followed by a crash if (disposed) return false; return base.ConformsToProtocol (protocol); } } public partial class WindowBackendController : NSWindowController { public WindowBackendController () { } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Compiler; using System.Compiler.Analysis; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Cci; using Microsoft.Cci.Analysis; using Microsoft.Research.CodeAnalysis; using Microsoft.Research.DataStructures; namespace ManyClousot { class Program { static int done = 0; static TimeSpan[] times; static void Main(string[] args) { var start = DateTime.Now; var stopWatch = new Stopwatch(); stopWatch.Start(); var tasks = new Task<int>[args.Length]; var cmds = new string[tasks.Length]; times = new TimeSpan[tasks.Length]; for (var i = 0; i < args.Length; i++) { cmds[i] = args[i]; } Console.WriteLine("We start the analyses"); for (var i = 0; i < tasks.Length; i++) { var clousotArgs = new List<string>(); clousotArgs.Add(cmds[i]); Console.WriteLine("call: " + i); var local = i; // without it we get the wrong parameter!!!!!!!! tasks[i] = new Task<int>(() => CallClousotEXE(local, clousotArgs.ToArray())); tasks[i].Start(); } Console.WriteLine("We wait"); Task.WaitAll(tasks); for(var i = 0; i < tasks.Length; i++) { Console.WriteLine("Time for {0} was : {1}", i, times[i]); } Console.WriteLine("we are done (in {0})! Press a key", stopWatch.Elapsed); Console.ReadKey(); } static string pathNET = "c:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\"; static string path = "d:\\tmp\\ref1\\"; static string cmd = "-arrays -arithmetic -enum -nonnull -bounds -suggest requires -sortwarns=false -stats slowmethods -scores -warninglevel=full"; // static string cmdFull = "-sortwarns=false"; static string[] assemblies = new string[] { "system.data.dll", "mscorlib.dll", "system.dll", "system.core.dll" }; static string PathEXE = "C:\\Program Files (x86)\\Microsoft\\Contracts\\Bin\\cccheck.exe"; static void MainOld(string[] args) { var start = DateTime.Now; var tasks = new Task<int>[assemblies.Length]; var threads = new Thread[tasks.Length]; var cmds = new string[tasks.Length]; for (var i = 0; i < assemblies.Length; i++) { var p = i % 2 == 0 ? path : pathNET; cmds[i] = cmd + " " + p + "" + assemblies[i]; } Console.WriteLine("We start the analyses"); #if true for (var i = 0; i < tasks.Length; i++) { var clousotArgs = cmds[i].Split(' '); tasks[i] = new Task<int>(() => CallClousotEXE(i, clousotArgs)); tasks[i].Start(); } Console.WriteLine("We wait"); Task.WaitAll(tasks); #else for (var i = 0; i < threads.Length; i++) { var clousotArgs = cmds[i].Split(' '); threads[i] = new Thread(new ThreadStart(() => CallClousot2(clousotArgs))); threads[i].Start(); } Console.WriteLine("We wait"); // Stupid way of waiting for (var i = 0; i < threads.Length; i++) { threads[i].Join(); } #endif Console.WriteLine("we are done (in {0})! Press a key", DateTime.Now - start); Console.ReadKey(); } static int CallClousot2(string[] args) { var cciilProvider = CciILCodeProvider.CreateCodeProvider(); var metadataDecoder = cciilProvider.MetaDataDecoder; var contractDecoder = cciilProvider.ContractDecoder; var assemblyCache = new System.Collections.Hashtable(); var textWriter = Console.Out; var outputFactory = new FullTextWriterOutputFactory<MethodReferenceAdaptor, IAssemblyReference>(textWriter, "ServiceOutput"); try { // We now call Clousot int returnCode = Clousot.ClousotMain(args, metadataDecoder, contractDecoder, assemblyCache, outputFactory: outputFactory, cacheAccessorFactories: null ); return returnCode; } catch (ExitRequestedException e) { return e.ExitCode; } catch (Exception e) { // We need to catch all exception, otherwise the service is turned into an faulted state and remains unusable textWriter.WriteLine("[{0}]: Many Clousot: caught exception: {1}", DateTime.Now, e); if (e.InnerException != null) { textWriter.WriteLine("Inner exception: {0}", e.InnerException); } return -4444; } finally { Console.WriteLine("Analysis done".PrefixWithCurrentTime()); textWriter.Close(); // make sure all pending output are flushed cciilProvider.Dispose(); // make sure all open files are closed } } static int CallClousot1(string[] args) { var assemblyCache = new System.Collections.Hashtable(); // We handle the platform option here as we can't do it from within Clousot // as it is very CCI specific. // //SetTargetPlatform(args, assemblyCache); try { var textWriter = Console.Out; var outputFactory = new FullTextWriterOutputFactory<Method, AssemblyNode>(textWriter, "ServiceOutput"); int returnCode = Clousot.ClousotMain(args, CCIMDDecoder.Value, CCIContractDecoder.Value, assemblyCache, outputFactory, null ); return returnCode; } catch (ExitRequestedException e) { return e.ExitCode; } finally { DisposeAssemblies(assemblyCache.Values); } } static int CallClousotEXE(int index, string[] args) { Console.WriteLine(" <<< " + index); var start = DateTime.Now; var startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = false; startInfo.UseShellExecute = false; startInfo.FileName = PathEXE; startInfo.WindowStyle = ProcessWindowStyle.Hidden; startInfo.Arguments = string.Join(" ", args); try { // Start the process with the info we specified. // Call WaitForExit and then the using statement will close. using (var exeProcess = Process.Start(startInfo)) { exeProcess.WaitForExit(); return exeProcess.ExitCode; } } catch { return -1; } finally { done++; Console.WriteLine(" >>> " + index); times[index] = DateTime.Now - start; Console.Title = string.Format("Done {0} analyses", done); } } private static void DisposeAssemblies(System.Collections.IEnumerable assemblies) { try { foreach (System.Compiler.Module assembly in assemblies) { assembly.Dispose(); } } catch { } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; namespace BinaryTree { /// <summary> /// An object representing a node. a node is a part of the binary tree which contains data /// </summary> public class Node { /// <summary> /// Gets or sets the value of current node, the value is unique /// </summary> public int Value { get; set; } /// <summary> /// Gets or sets the right node connected to this node, if any /// </summary> public Node Right { get; set; } /// <summary> /// Gets or sets the left node connected to this node, if any /// </summary> public Node Left { get; set; } private Brush _brushColor; /// <summary> /// Colors of the node /// </summary> public Brush BrushColor { get { return _brushColor ?? Brushes.Black; } set { _brushColor = value; } } /// <summary> /// Constructor to create new instance of node /// </summary> /// <param name="value"> /// The initial value of the node. /// </param> public Node(int value) : this(value, null, null) { } /// <summary> /// Constructor to create new instance of node /// </summary> /// <param name="value"> /// The initial value of the node. /// </param> /// <param name="left"> /// The node which will be connected to this node as the left node. null is also acceptable /// </param> /// <param name="right"> /// The node which will be connected to this node as the right node. null is also acceptable /// </param> public Node(int value, Node left, Node right) { Right = left; Left = right; Value = value; } /// <summary> /// The backgroung image of each nodes, the size of this bitmap affects the quality of /// output image /// </summary> private static Bitmap _nodeBg = new Bitmap(30, 25); /// <summary> /// The free space between nodes on the drawed image, /// </summary> private static Size _freeSpace = new Size(_nodeBg.Width / 8, (int)(_nodeBg.Height * 1.3f)); /// <summary> /// A value which is used, (on drawing the Value of the nodes), in order to make sure the /// drawed image would be the same for any size of _nodeBg. /// </summary> private static readonly float Coef = _nodeBg.Width / 40f; /// <summary> /// The constructor of static members /// </summary> static Node() { var g = Graphics.FromImage(_nodeBg); // get a Graphics from _nodeBg bitmap, g.SmoothingMode = SmoothingMode.HighQuality; // set the smoothing mode var rcl = new Rectangle(1, 1, _nodeBg.Width - 2, _nodeBg.Height - 2); // get a rectangle of drawer g.FillRectangle(Brushes.White, rcl); //g.FillEllipse(new LinearGradientBrush(new Point(0, 0), new Point(_me.Width, _me.Height), Color.Goldenrod, Color.Black), rcl); g.DrawEllipse(new Pen(Color.Black, 1.2f), rcl); // draw ellipse, you could also comment this line, and uncomment the above line as another option for background image } /// <summary> /// Add a node to the left or right side of current node /// </summary> /// <param name="node">The node to be added</param> /// <param name="addLeft">A flag to determine whether to add to left or right side</param> public void Add(Node node, bool addLeft) { if (addLeft) // Add to left { Left = node; } else // Add to right { Right = node; } } /// <summary> /// The location of the node. /// </summary> private int _lastImageLocationOfStarterNode; /// <summary> /// Font to be used /// </summary> private static Font font = new Font("Tahoma", 14f * Coef); /// <summary> /// Paints the node and its children /// </summary> /// <param name="center">The location of the node on the top of the drawn image.</param> /// <returns>The image representing the current node and its children</returns> public Image Draw(out int center) { center = _lastImageLocationOfStarterNode; var lCenter = 0; var rCenter = 0; Image lNodeImg = null, rNodeImg = null; if (Left != null) // draw left node's image lNodeImg = Left.Draw(out lCenter); if (Right != null) // draw right node's image rNodeImg = Right.Draw(out rCenter); // draw current node and it's childs (left node image and right node image) var lSize = new Size(); var rSize = new Size(); var under = (lNodeImg != null) || (rNodeImg != null);// if true the current node has childs if (lNodeImg != null) lSize = lNodeImg.Size; if (rNodeImg != null) rSize = rNodeImg.Size; var maxHeight = lSize.Height; if (maxHeight < rSize.Height) maxHeight = rSize.Height; if (lSize.Width <= 0) lSize.Width = (_nodeBg.Width - _freeSpace.Width) / 2; if (rSize.Width <= 0) rSize.Width = (_nodeBg.Width - _freeSpace.Width) / 2; var resSize = new Size { Width = lSize.Width + rSize.Width + _freeSpace.Width, Height = _nodeBg.Size.Height + (under ? maxHeight + _freeSpace.Height : 0) }; var result = new Bitmap(resSize.Width, resSize.Height); var g = Graphics.FromImage(result); g.SmoothingMode = SmoothingMode.HighQuality; g.FillRectangle(Brushes.White, new Rectangle(new Point(0, 0), resSize)); g.DrawImage(_nodeBg, lSize.Width - _nodeBg.Width / 2 + _freeSpace.Width / 2, 0); var str = Value.ToString(); g.DrawString(str, font, BrushColor, lSize.Width - _nodeBg.Width / 2 + _freeSpace.Width / 2 + (2 + (str.Length == 1 ? 10 : str.Length == 2 ? 5 : 0)) * Coef, _nodeBg.Height / 2f - 12 * Coef); center = lSize.Width + _freeSpace.Width / 2; var pen = new Pen(Brushes.Black, 1.2f * Coef) { EndCap = LineCap.ArrowAnchor, StartCap = LineCap.Round }; float x1 = center; float y1 = _nodeBg.Height; float y2 = _nodeBg.Height + _freeSpace.Height; float x2 = lCenter; var h = Math.Abs(y2 - y1); var w = Math.Abs(x2 - x1); if (lNodeImg != null) { g.DrawImage(lNodeImg, 0, _nodeBg.Size.Height + _freeSpace.Height); var points1 = new List<PointF> { new PointF(x1, y1), new PointF(x1 - w/6, y1 + h/3.5f), new PointF(x2 + w/6, y2 - h/3.5f), new PointF(x2, y2), }; g.DrawCurve(pen, points1.ToArray(), 0.5f); } if (rNodeImg != null) { g.DrawImage(rNodeImg, lSize.Width + _freeSpace.Width, _nodeBg.Size.Height + _freeSpace.Height); x2 = rCenter + lSize.Width + _freeSpace.Width; w = Math.Abs(x2 - x1); var points = new List<PointF> { new PointF(x1, y1), new PointF(x1 + w/6, y1 + h/3.5f), new PointF(x2 - w/6, y2 - h/3.5f), new PointF(x2, y2) }; g.DrawCurve(pen, points.ToArray(), 0.5f); } _lastImageLocationOfStarterNode = center; return result; } /// <summary> /// The count of nodes under this node + 1 /// </summary> public int Count { get { return 1 + (Left != null ? Left.Count : 0) + (Right != null ? Right.Count : 0); } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ImagePorter.cs" company="The Watcher"> // Copyright (c) The Watcher Partial Rights Reserved. // This software is licensed under the MIT license. See license.txt for details. // </copyright> // <summary> // Code Named: VG-Ripper // Function : Extracts Images posted on RiP forums and attempts to fetch them to disk. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Ripper.Services.ImageHosts { using System; using System.Collections; using System.IO; using System.Net; using System.Text.RegularExpressions; using System.Threading; using Ripper.Core.Components; using Ripper.Core.Objects; /// <summary> /// Worker class to get images from ImagePorter.com /// </summary> public class ImagePorter : ServiceTemplate { /// <summary> /// Initializes a new instance of the <see cref="ImagePorter"/> class. /// </summary> /// <param name="savePath"> /// The save Path. /// </param> /// <param name="imageUrl"> /// The image Url. /// </param> /// <param name="hashtable"> /// The hashtable. /// </param> public ImagePorter(ref string savePath, ref string imageUrl, ref string thumbUrl, ref string imageName, ref int imageNumber, ref Hashtable hashtable) : base(savePath, imageUrl, thumbUrl, imageName, imageNumber, ref hashtable) { } /// <summary> /// Do the Download /// </summary> /// <returns> /// Return if Downloaded or not /// </returns> protected override bool DoDownload() { string strImgURL = ImageLinkURL; if (EventTable.ContainsKey(strImgURL)) { return true; } string strFilePath = string.Empty; try { if (!Directory.Exists(SavePath)) { Directory.CreateDirectory(SavePath); } } catch (IOException ex) { //MainForm.DeleteMessage = ex.Message; //MainForm.Delete = true; return false; } CacheObject ccObj = new CacheObject { IsDownloaded = false, FilePath = strFilePath, Url = strImgURL }; try { EventTable.Add(strImgURL, ccObj); } catch (ThreadAbortException) { return true; } catch (Exception) { if (EventTable.ContainsKey(strImgURL)) { return false; } EventTable.Add(strImgURL, ccObj); } string sPage = this.GetImageHostsPage(ref strImgURL); if (sPage.Length < 10) { return false; } string strNewURL; var m = Regex.Match(sPage, @"src=\""http://img(?<inner>[^\""]*)\""", RegexOptions.Singleline); if (m.Success) { strNewURL = string.Format("http://img{0}", m.Groups["inner"].Value); } else { return false; } strFilePath = strImgURL.Substring(strImgURL.LastIndexOf("/", StringComparison.Ordinal) + 1).Replace(".html", string.Empty); strFilePath = Path.Combine(SavePath, Utility.RemoveIllegalCharecters(strFilePath)); ////////////////////////////////////////////////////////////////////////// string newAlteredPath = Utility.GetSuitableName(strFilePath); if (strFilePath != newAlteredPath) { strFilePath = newAlteredPath; ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath; } try { WebClient client = new WebClient(); client.Headers.Add(string.Format("Referer: {0}", strImgURL)); client.Headers.Add("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6"); client.DownloadFile(strNewURL, strFilePath); client.Dispose(); } catch (ThreadAbortException) { ((CacheObject)EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL); return true; } catch (IOException ex) { //MainForm.DeleteMessage = ex.Message; //MainForm.Delete = true; ((CacheObject)EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL); return true; } catch (WebException) { ((CacheObject)EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL); return false; } ((CacheObject)EventTable[ImageLinkURL]).IsDownloaded = true; CacheController.Instance().LastPic = ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath; return true; } /// <summary> /// a generic function to fetch urls. /// </summary> /// <param name="strURL"> /// The str URL. /// </param> /// <returns> /// Returns the Page as string. /// </returns> protected string GetImageHostsPage(ref string strURL) { string strPageRead; try { var req = (HttpWebRequest)WebRequest.Create(strURL); req.UserAgent = "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1"; req.Headers["Cookie"] = "porter8078_s=loaded;"; req.Referer = strURL; var res = (HttpWebResponse)req.GetResponse(); var stream = res.GetResponseStream(); if (stream != null) { var reader = new StreamReader(stream); strPageRead = reader.ReadToEnd(); res.Close(); reader.Close(); } else { res.Close(); return string.Empty; } } catch (ThreadAbortException) { return string.Empty; } catch (Exception) { return string.Empty; } return strPageRead; } ////////////////////////////////////////////////////////////////////////// } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Assets { public class AncestorIndividual { public string Id; public string GivenName; public string Surname; public string Suffix; public string Prefix; public string Sex; public string BirthDate; public string DiedDate; public string FatherId; public string MotherId; public string BirthPlace; public string DiedPlace; public string CountryCode; public int LowestGeneration; public int HighestGeneration; public long AppearanceCount; public long AhnentafelNumber; public string SummaryName; public string SummaryBirthDate; public string SummaryDeathDate; public Dictionary<string, string> SummarySpouse; public Dictionary<string, string> SummaryMarriage; public Dictionary<string, HashSet<string>> SummaryChildren; public string SummaryFatherName; public string SummaryMotherName; public string SummaryRelationship; public string FullSummary; public AncestorIndividual() { Id = ""; GivenName = ""; Surname = ""; Suffix = ""; Prefix = ""; Sex = ""; BirthDate = ""; DiedDate = ""; BirthPlace = ""; DiedPlace = ""; FatherId = ""; MotherId = ""; LowestGeneration = 0; HighestGeneration = 0; AppearanceCount = 0; AhnentafelNumber = 0; SummaryName = ""; SummaryFatherName = ""; SummaryMotherName = ""; SummaryBirthDate = ""; SummaryDeathDate = ""; SummarySpouse = new Dictionary<string, string>(); SummaryMarriage = new Dictionary<string, string>(); SummaryChildren = new Dictionary<string, HashSet<string>>(); SummaryRelationship = ""; FullSummary = ""; CountryCode = ""; } public AncestorIndividual(string id) { Id = id; GivenName = ""; Surname = ""; Suffix = ""; Prefix = ""; Sex = ""; BirthDate = ""; DiedDate = ""; BirthPlace = ""; DiedPlace = ""; FatherId = ""; MotherId = ""; LowestGeneration = 0; HighestGeneration = 0; AppearanceCount = 0; AhnentafelNumber = 0; SummaryName = ""; SummaryFatherName = ""; SummaryMotherName = ""; SummaryBirthDate = ""; SummaryDeathDate = ""; SummarySpouse = new Dictionary<string, string>(); SummaryMarriage = new Dictionary<string, string>(); SummaryChildren = new Dictionary<string, HashSet<string>>(); SummaryRelationship = ""; FullSummary = ""; CountryCode = ""; } public AncestorIndividual(BinaryReader reader) { ReadFromStream(reader); } public void WriteToStream(BinaryWriter writer) { writer.Write(Id); writer.Write(GivenName); writer.Write(Surname); writer.Write(Suffix); writer.Write(Prefix); writer.Write(Sex); writer.Write(BirthDate); writer.Write(BirthPlace); writer.Write(DiedDate); writer.Write(DiedPlace); writer.Write(FatherId); writer.Write(MotherId); writer.Write(LowestGeneration); writer.Write(HighestGeneration); writer.Write(AppearanceCount); writer.Write(AhnentafelNumber); writer.Write(SummaryName); writer.Write(SummaryFatherName); writer.Write(SummaryMotherName); writer.Write(SummaryBirthDate); writer.Write(SummaryDeathDate); writer.Write(SummaryRelationship); writer.Write(FullSummary); writer.Write(CountryCode); writer.Write(SummarySpouse.Count); foreach(KeyValuePair<string, string> values in SummarySpouse) { writer.Write(values.Key); writer.Write(values.Value); } writer.Write(SummaryMarriage.Count); foreach (KeyValuePair<string, string> values in SummaryMarriage) { writer.Write(values.Key); writer.Write(values.Value); } writer.Write(SummaryChildren.Count); foreach (KeyValuePair<string, HashSet<string>> values in SummaryChildren) { writer.Write(values.Key); writer.Write(values.Value.Count); foreach (string value in values.Value) writer.Write(value); } } private void ReadFromStream(BinaryReader reader) { Id = reader.ReadString(); GivenName = reader.ReadString(); Surname = reader.ReadString(); Suffix = reader.ReadString(); Prefix = reader.ReadString(); Sex = reader.ReadString(); BirthDate = reader.ReadString(); BirthPlace = reader.ReadString(); DiedDate = reader.ReadString(); DiedPlace = reader.ReadString(); FatherId = reader.ReadString(); MotherId = reader.ReadString(); LowestGeneration = reader.ReadInt32(); HighestGeneration = reader.ReadInt32(); AppearanceCount = reader.ReadInt64(); AhnentafelNumber = reader.ReadInt64(); SummaryName = reader.ReadString(); SummaryFatherName = reader.ReadString(); SummaryMotherName = reader.ReadString(); SummaryBirthDate = reader.ReadString(); SummaryDeathDate = reader.ReadString(); SummaryRelationship = reader.ReadString(); FullSummary = reader.ReadString(); CountryCode = reader.ReadString(); SummarySpouse = new Dictionary<string, string>(); int recordCount = reader.ReadInt32(); for(int i = 0; i < recordCount; i++) { SummarySpouse.Add(reader.ReadString(), reader.ReadString()); } SummaryMarriage = new Dictionary<string, string>(); recordCount = reader.ReadInt32(); for (int i = 0; i < recordCount; i++) { SummaryMarriage.Add(reader.ReadString(), reader.ReadString()); } SummaryChildren = new Dictionary<string, HashSet<string>>(); recordCount = reader.ReadInt32(); for (int i = 0; i < recordCount; i++) { string id = reader.ReadString(); HashSet<string> children = new HashSet<string>(); int childrenCount = reader.ReadInt32(); for (int j = 0; j < childrenCount; j++) children.Add(reader.ReadString()); SummaryChildren.Add(id, children); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Data; using System.Reflection; using log4net; using MySql.Data.MySqlClient; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Data.MySQL { public class MySQLEstateStore : IEstateDataStore { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const string m_waitTimeoutSelect = "select @@wait_timeout"; private string m_connectionString; private long m_waitTimeout; private long m_waitTimeoutLeeway = 60 * TimeSpan.TicksPerSecond; private long m_lastConnectionUse; private FieldInfo[] m_Fields; private Dictionary<string, FieldInfo> m_FieldMap = new Dictionary<string, FieldInfo>(); public void Initialise(string connectionString) { m_connectionString = connectionString; try { m_log.Info("[REGION DB]: MySql - connecting: " + Util.GetDisplayConnectionString(m_connectionString)); } catch (Exception e) { m_log.Debug("Exception: password not found in connection string\n" + e.ToString()); } GetWaitTimeout(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); Assembly assem = GetType().Assembly; Migration m = new Migration(dbcon, assem, "EstateStore"); m.Update(); Type t = typeof(EstateSettings); m_Fields = t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (FieldInfo f in m_Fields) { if (f.Name.Substring(0, 2) == "m_") m_FieldMap[f.Name.Substring(2)] = f; } } } private string[] FieldList { get { return new List<string>(m_FieldMap.Keys).ToArray(); } } protected void GetWaitTimeout() { using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, dbcon)) { using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (dbReader.Read()) { m_waitTimeout = Convert.ToInt32(dbReader["@@wait_timeout"]) * TimeSpan.TicksPerSecond + m_waitTimeoutLeeway; } } } m_lastConnectionUse = DateTime.Now.Ticks; m_log.DebugFormat( "[REGION DB]: Connection wait timeout {0} seconds", m_waitTimeout / TimeSpan.TicksPerSecond); } } public EstateSettings LoadEstateSettings(UUID regionID) { bool create = true; EstateSettings es = new EstateSettings(); es.OnSave += StoreEstateSettings; string sql = "select estate_settings." + String.Join(",estate_settings.", FieldList) + " from estate_map left join estate_settings on estate_map.EstateID = estate_settings.EstateID where estate_settings.EstateID is not null and RegionID = ?RegionID"; using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.AddWithValue("?RegionID", regionID.ToString()); using (IDataReader r = cmd.ExecuteReader()) { if (r.Read()) { create = false; foreach (string name in FieldList) { if (m_FieldMap[name].GetValue(es) is bool) { int v = Convert.ToInt32(r[name]); if (v != 0) m_FieldMap[name].SetValue(es, true); else m_FieldMap[name].SetValue(es, false); } else if (m_FieldMap[name].GetValue(es) is UUID) { UUID uuid = UUID.Zero; UUID.TryParse(r[name].ToString(), out uuid); m_FieldMap[name].SetValue(es, uuid); } else { m_FieldMap[name].SetValue(es, r[name]); } } } } } if (create) { // Migration case List<string> names = new List<string>(FieldList); names.Remove("EstateID"); sql = "insert into estate_settings (" + String.Join(",", names.ToArray()) + ") values ( ?" + String.Join(", ?", names.ToArray()) + ")"; using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.Clear(); foreach (string name in FieldList) { if (m_FieldMap[name].GetValue(es) is bool) { if ((bool)m_FieldMap[name].GetValue(es)) cmd.Parameters.AddWithValue("?" + name, "1"); else cmd.Parameters.AddWithValue("?" + name, "0"); } else { cmd.Parameters.AddWithValue("?" + name, m_FieldMap[name].GetValue(es).ToString()); } } cmd.ExecuteNonQuery(); cmd.CommandText = "select LAST_INSERT_ID() as id"; cmd.Parameters.Clear(); using (IDataReader r = cmd.ExecuteReader()) { r.Read(); es.EstateID = Convert.ToUInt32(r["id"]); } cmd.CommandText = "insert into estate_map values (?RegionID, ?EstateID)"; cmd.Parameters.AddWithValue("?RegionID", regionID.ToString()); cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString()); // This will throw on dupe key try { cmd.ExecuteNonQuery(); } catch (Exception) { } // Munge and transfer the ban list cmd.Parameters.Clear(); cmd.CommandText = "insert into estateban select " + es.EstateID.ToString() + ", bannedUUID, bannedIp, bannedIpHostMask, '' from regionban where regionban.regionUUID = ?UUID"; cmd.Parameters.AddWithValue("?UUID", regionID.ToString()); try { cmd.ExecuteNonQuery(); } catch (Exception) { } es.Save(); } } } LoadBanList(es); es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers"); es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users"); es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups"); return es; } public void StoreEstateSettings(EstateSettings es) { string sql = "replace into estate_settings (" + String.Join(",", FieldList) + ") values ( ?" + String.Join(", ?", FieldList) + ")"; using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = sql; foreach (string name in FieldList) { if (m_FieldMap[name].GetValue(es) is bool) { if ((bool)m_FieldMap[name].GetValue(es)) cmd.Parameters.AddWithValue("?" + name, "1"); else cmd.Parameters.AddWithValue("?" + name, "0"); } else { m_log.DebugFormat("Adding field '{0}'", name); cmd.Parameters.AddWithValue("?" + name, m_FieldMap[name].GetValue(es).ToString()); } } cmd.ExecuteNonQuery(); } } SaveBanList(es); SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers); SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess); SaveUUIDList(es.EstateID, "estate_groups", es.EstateGroups); } private void LoadBanList(EstateSettings es) { es.ClearBans(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select bannedUUID from estateban where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", es.EstateID); using (IDataReader r = cmd.ExecuteReader()) { while (r.Read()) { EstateBan eb = new EstateBan(); UUID uuid = new UUID(); UUID.TryParse(r["bannedUUID"].ToString(), out uuid); eb.BannedUserID = uuid; eb.BannedHostAddress = "0.0.0.0"; eb.BannedHostIPMask = "0.0.0.0"; es.AddBan(eb); } } } } } private void SaveBanList(EstateSettings es) { using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "delete from estateban where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) values ( ?EstateID, ?bannedUUID, '', '', '' )"; foreach (EstateBan b in es.EstateBans) { cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString()); cmd.Parameters.AddWithValue("?bannedUUID", b.BannedUserID.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } } } } void SaveUUIDList(uint EstateID, string table, UUID[] data) { using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "delete from " + table + " where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); cmd.CommandText = "insert into " + table + " (EstateID, uuid) values ( ?EstateID, ?uuid )"; foreach (UUID uuid in data) { cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString()); cmd.Parameters.AddWithValue("?uuid", uuid.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } } } } UUID[] LoadUUIDList(uint EstateID, string table) { List<UUID> uuids = new List<UUID>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select uuid from " + table + " where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", EstateID); using (IDataReader r = cmd.ExecuteReader()) { while (r.Read()) { // EstateBan eb = new EstateBan(); UUID uuid = new UUID(); UUID.TryParse(r["uuid"].ToString(), out uuid); uuids.Add(uuid); } } } } return uuids.ToArray(); } } }