context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Reflection.Emit;
namespace System.Linq.Expressions.Interpreter
{
/// <summary>
/// Contains compiler state corresponding to a LabelTarget
/// See also LabelScopeInfo.
/// </summary>
internal sealed class LabelInfo
{
// The tree node representing this label
private readonly LabelTarget _node;
// The BranchLabel label, will be mutated if Node is redefined
private BranchLabel _label;
// The blocks where this label is defined. If it has more than one item,
// the blocks can't be jumped to except from a child block
// If there's only 1 block (the common case) it's stored here, if there's multiple blocks it's stored
// as a HashSet<LabelScopeInfo>
private object _definitions;
// Blocks that jump to this block
private readonly List<LabelScopeInfo> _references = new List<LabelScopeInfo>();
// True if at least one jump is across blocks
// If we have any jump across blocks to this label, then the
// LabelTarget can only be defined in one place
private bool _acrossBlockJump;
internal LabelInfo(LabelTarget node)
{
_node = node;
}
internal BranchLabel GetLabel(LightCompiler compiler)
{
EnsureLabel(compiler);
return _label;
}
internal void Reference(LabelScopeInfo block)
{
_references.Add(block);
if (HasDefinitions)
{
ValidateJump(block);
}
}
internal void Define(LabelScopeInfo block)
{
// Prevent the label from being shadowed, which enforces cleaner
// trees. Also we depend on this for simplicity (keeping only one
// active IL Label per LabelInfo)
for (LabelScopeInfo j = block; j != null; j = j.Parent)
{
if (j.ContainsTarget(_node))
{
throw Error.LabelTargetAlreadyDefined(_node.Name);
}
}
AddDefinition(block);
block.AddLabelInfo(_node, this);
// Once defined, validate all jumps
if (HasDefinitions && !HasMultipleDefinitions)
{
foreach (var r in _references)
{
ValidateJump(r);
}
}
else
{
// Was just redefined, if we had any across block jumps, they're
// now invalid
if (_acrossBlockJump)
{
throw Error.AmbiguousJump(_node.Name);
}
// For local jumps, we need a new IL label
// This is okay because:
// 1. no across block jumps have been made or will be made
// 2. we don't allow the label to be shadowed
_label = null;
}
}
private void ValidateJump(LabelScopeInfo reference)
{
// look for a simple jump out
for (LabelScopeInfo j = reference; j != null; j = j.Parent)
{
if (DefinedIn(j))
{
// found it, jump is valid!
return;
}
if (j.Kind == LabelScopeKind.Finally || j.Kind == LabelScopeKind.Filter)
{
break;
}
}
_acrossBlockJump = true;
if (HasMultipleDefinitions)
{
throw Error.AmbiguousJump(_node.Name);
}
// We didn't find an outward jump. Look for a jump across blocks
LabelScopeInfo def = FirstDefinition();
LabelScopeInfo common = CommonNode(def, reference, b => b.Parent);
// Validate that we aren't jumping across a finally
for (LabelScopeInfo j = reference; j != common; j = j.Parent)
{
if (j.Kind == LabelScopeKind.Finally)
{
throw Error.ControlCannotLeaveFinally();
}
if (j.Kind == LabelScopeKind.Filter)
{
throw Error.ControlCannotLeaveFilterTest();
}
}
// Validate that we aren't jumping into a catch or an expression
for (LabelScopeInfo j = def; j != common; j = j.Parent)
{
if (!j.CanJumpInto)
{
if (j.Kind == LabelScopeKind.Expression)
{
throw Error.ControlCannotEnterExpression();
}
else
{
throw Error.ControlCannotEnterTry();
}
}
}
}
internal void ValidateFinish()
{
// Make sure that if this label was jumped to, it is also defined
if (_references.Count > 0 && !HasDefinitions)
{
throw Error.LabelTargetUndefined(_node.Name);
}
}
private void EnsureLabel(LightCompiler compiler)
{
if (_label == null)
{
_label = compiler.Instructions.MakeLabel();
}
}
private bool DefinedIn(LabelScopeInfo scope)
{
if (_definitions == scope)
{
return true;
}
HashSet<LabelScopeInfo> definitions = _definitions as HashSet<LabelScopeInfo>;
if (definitions != null)
{
return definitions.Contains(scope);
}
return false;
}
private bool HasDefinitions
{
get
{
return _definitions != null;
}
}
private LabelScopeInfo FirstDefinition()
{
LabelScopeInfo scope = _definitions as LabelScopeInfo;
if (scope != null)
{
return scope;
}
foreach (var x in (HashSet<LabelScopeInfo>)_definitions)
{
return x;
}
throw new InvalidOperationException();
}
private void AddDefinition(LabelScopeInfo scope)
{
if (_definitions == null)
{
_definitions = scope;
}
else
{
HashSet<LabelScopeInfo> set = _definitions as HashSet<LabelScopeInfo>;
if (set == null)
{
_definitions = set = new HashSet<LabelScopeInfo>() { (LabelScopeInfo)_definitions };
}
set.Add(scope);
}
}
private bool HasMultipleDefinitions
{
get
{
return _definitions is HashSet<LabelScopeInfo>;
}
}
internal static T CommonNode<T>(T first, T second, Func<T, T> parent) where T : class
{
var cmp = EqualityComparer<T>.Default;
if (cmp.Equals(first, second))
{
return first;
}
var set = new HashSet<T>(cmp);
for (T t = first; t != null; t = parent(t))
{
set.Add(t);
}
for (T t = second; t != null; t = parent(t))
{
if (set.Contains(t))
{
return t;
}
}
return null;
}
}
internal enum LabelScopeKind
{
// any "statement like" node that can be jumped into
Statement,
// these correspond to the node of the same name
Block,
Switch,
Lambda,
Try,
// these correspond to the part of the try block we're in
Catch,
Finally,
Filter,
// the catch-all value for any other expression type
// (means we can't jump into it)
Expression,
}
//
// Tracks scoping information for LabelTargets. Logically corresponds to a
// "label scope". Even though we have arbitrary goto support, we still need
// to track what kinds of nodes that gotos are jumping through, both to
// emit property IL ("leave" out of a try block), and for validation, and
// to allow labels to be duplicated in the tree, as long as the jumps are
// considered "up only" jumps.
//
// We create one of these for every Expression that can be jumped into, as
// well as creating them for the first expression we can't jump into. The
// "Kind" property indicates what kind of scope this is.
//
internal sealed class LabelScopeInfo
{
private HybridReferenceDictionary<LabelTarget, LabelInfo> _labels; // lazily allocated, we typically use this only once every 6th-7th block
internal readonly LabelScopeKind Kind;
internal readonly LabelScopeInfo Parent;
internal LabelScopeInfo(LabelScopeInfo parent, LabelScopeKind kind)
{
Parent = parent;
Kind = kind;
}
/// <summary>
/// Returns true if we can jump into this node
/// </summary>
internal bool CanJumpInto
{
get
{
switch (Kind)
{
case LabelScopeKind.Block:
case LabelScopeKind.Statement:
case LabelScopeKind.Switch:
case LabelScopeKind.Lambda:
return true;
}
return false;
}
}
internal bool ContainsTarget(LabelTarget target)
{
if (_labels == null)
{
return false;
}
return _labels.ContainsKey(target);
}
internal bool TryGetLabelInfo(LabelTarget target, out LabelInfo info)
{
if (_labels == null)
{
info = null;
return false;
}
return _labels.TryGetValue(target, out info);
}
internal void AddLabelInfo(LabelTarget target, LabelInfo info)
{
Debug.Assert(CanJumpInto);
if (_labels == null)
{
_labels = new HybridReferenceDictionary<LabelTarget, LabelInfo>();
}
_labels[target] = info;
}
}
}
| |
using AutoFixture;
using AutoFixture.NUnit3;
using FluentAssertions;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging;
using Moq;
using NServiceBus;
using NUnit.Framework;
using SFA.DAS.CommitmentsV2.Application.Commands.StopApprenticeship;
using SFA.DAS.CommitmentsV2.Authentication;
using SFA.DAS.CommitmentsV2.Data;
using SFA.DAS.CommitmentsV2.Domain.Exceptions;
using SFA.DAS.CommitmentsV2.Messages.Commands;
using SFA.DAS.CommitmentsV2.Messages.Events;
using SFA.DAS.CommitmentsV2.Models;
using SFA.DAS.CommitmentsV2.Shared.Interfaces;
using SFA.DAS.CommitmentsV2.Types;
using SFA.DAS.Encoding;
using SFA.DAS.NServiceBus.Services;
using SFA.DAS.Testing.AutoFixture;
using SFA.DAS.UnitOfWork.Context;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace SFA.DAS.CommitmentsV2.UnitTests.Application.Commands
{
[TestFixture]
[Parallelizable]
public class StopApprenticeshipCommandHandlerTests
{
private Mock<ICurrentDateTime> _currentDateTime;
private Mock<ILogger<StopApprenticeshipCommandHandler>> _logger;
private Mock<IAuthenticationService> _authenticationService;
private Mock<IMessageSession> _nserviceBusContext;
private Mock<IEncodingService> _encodingService;
ProviderCommitmentsDbContext _dbContext;
ProviderCommitmentsDbContext _confirmationDbContext;
private UnitOfWorkContext _unitOfWorkContext { get; set; }
private IRequestHandler<StopApprenticeshipCommand> _handler;
[SetUp]
public void Init()
{
var databaseGuid = Guid.NewGuid().ToString();
_dbContext = new ProviderCommitmentsDbContext(new DbContextOptionsBuilder<ProviderCommitmentsDbContext>()
.UseInMemoryDatabase(databaseGuid)
.Options);
_confirmationDbContext = new ProviderCommitmentsDbContext(new DbContextOptionsBuilder<ProviderCommitmentsDbContext>()
.UseInMemoryDatabase(databaseGuid)
.Options);
_currentDateTime = new Mock<ICurrentDateTime>();
_authenticationService = new Mock<IAuthenticationService>();
_nserviceBusContext = new Mock<IMessageSession>();
_encodingService = new Mock<IEncodingService>();
_logger = new Mock<ILogger<StopApprenticeshipCommandHandler>>();
_unitOfWorkContext = new UnitOfWorkContext();
_handler = new StopApprenticeshipCommandHandler(new Lazy<ProviderCommitmentsDbContext>(() => _dbContext),
_currentDateTime.Object,
_authenticationService.Object,
_nserviceBusContext.Object,
_encodingService.Object,
_logger.Object);
}
[Test]
public async Task Handle_WhenHandlingCommand_WithInvalidData_ThenShouldThrowException()
{
// Arrange
var command = new StopApprenticeshipCommand(0, 0, DateTime.MinValue, false, new UserInfo());
StopApprenticeshipCommandValidator sut = new StopApprenticeshipCommandValidator();
// Act
var result = await sut.ValidateAsync(command, new CancellationToken());
// Assert
result.Errors.Should().SatisfyRespectively(
first =>
{
first.PropertyName.Should().Be("AccountId");
first.ErrorMessage.Should().Be("The Account Id must be positive");
},
second =>
{
second.PropertyName.Should().Be("ApprenticeshipId");
second.ErrorMessage.Should().Be("The ApprenticeshipId must be positive");
},
third =>
{
third.PropertyName.Should().Be("UserInfo");
third.ErrorMessage.Should().Be("The User Info supplied must not be null and contain a UserId");
},
fourth =>
{
fourth.PropertyName.Should().Be("StopDate");
fourth.ErrorMessage.Should().Be("The StopDate must be supplied");
});
}
[Test, MoqAutoData]
public async Task Handle_WhenHandlingCommand_WithInvalidCallingParty_ThenShouldThrowDomainException(StopApprenticeshipCommand command)
{
// Arrange
var apprenticeship = await SetupApprenticeship(Party.Provider);
// Act
var exception = Assert.ThrowsAsync<DomainException>(async () => await _handler.Handle(command, new CancellationToken()));
// Assert
exception.DomainErrors.Should().BeEquivalentTo(new { ErrorMessage = "StopApprenticeship is restricted to Employers only - Provider is invalid" });
}
[Test]
[InlineAutoData(PaymentStatus.Completed)]
[InlineAutoData(PaymentStatus.Withdrawn)]
public async Task Handle_WhenHandlingCommand_WithInvalidApprenticeshipForStop_PaymentStatusCompleted_ThenShouldThrowDomainException(PaymentStatus paymentStatus)
{
// Arrange
var apprenticeship = await SetupApprenticeship(paymentStatus: paymentStatus);
var command = new StopApprenticeshipCommand(apprenticeship.Cohort.EmployerAccountId, apprenticeship.Id, DateTime.UtcNow, false, new UserInfo());
// Act
var exception = Assert.ThrowsAsync<DomainException>(async () => await _handler.Handle(command, new CancellationToken()));
// Assert
exception.DomainErrors.Should().BeEquivalentTo(new { PropertyName = "PaymentStatus", ErrorMessage = "Apprenticeship must be Active or Paused. Unable to stop apprenticeship" });
}
[Test, MoqAutoData]
public async Task Handle_WhenHandlingCommand_WithMismatchedAccountId_ThenShouldThrowDomainException()
{
// Arrange
var apprenticeship = await SetupApprenticeship();
var incorrectAccountId = apprenticeship.Cohort.EmployerAccountId - 1;
var command = new StopApprenticeshipCommand(incorrectAccountId, apprenticeship.Id, DateTime.UtcNow, false, new UserInfo());
// Act
var exception = Assert.ThrowsAsync<DomainException>(async () => await _handler.Handle(command, new CancellationToken()));
// Assert
exception.DomainErrors.Should().BeEquivalentTo(new { PropertyName = "accountId", ErrorMessage = $"Employer {command.AccountId} not authorised to access commitment {apprenticeship.Cohort.Id}, expected employer {apprenticeship.Cohort.EmployerAccountId}" });
}
[Test, MoqAutoData]
public async Task Handle_WhenHandlingCommand_WithApprenticeshipWaitingToStart_WithStopDateNotEqualStartDate_ThenShouldThrowDomainException()
{
// Arrange
var apprenticeship = await SetupApprenticeship(startDate: DateTime.UtcNow.AddMonths(2));
var command = new StopApprenticeshipCommand(apprenticeship.Cohort.EmployerAccountId, apprenticeship.Id, DateTime.UtcNow, false, new UserInfo());
// Act
var exception = Assert.ThrowsAsync<DomainException>(async () => await _handler.Handle(command, new CancellationToken()));
// Assert
exception.DomainErrors.Should().BeEquivalentTo(new { PropertyName = "stopDate", ErrorMessage = $"Invalid stop date. Date should be value of start date if training has not started." });
}
[Test, MoqAutoData]
public async Task Handle_WhenHandlingCommand_WhenValidatingApprenticeship_WithStopDateInFuture_ThenShouldThrowDomainException()
{
// Arrange
var stopDate = DateTime.UtcNow.AddMonths(1);
var apprenticeship = await SetupApprenticeship();
var command = new StopApprenticeshipCommand(apprenticeship.Cohort.EmployerAccountId, apprenticeship.Id, stopDate, false, new UserInfo());
// Act
var exception = Assert.ThrowsAsync<DomainException>(async () => await _handler.Handle(command, new CancellationToken()));
// Assert
exception.DomainErrors.Should().BeEquivalentTo(new { PropertyName = "stopDate", ErrorMessage = $"Invalid Stop Date. Stop date cannot be in the future and must be the 1st of the month." });
}
[Test, MoqAutoData]
public async Task Handle_WhenHandlingCommand_WhenValidatingApprenticeship_WithStopDateInPast_ThenShouldThrowDomainException()
{
// Arrange
var stopDate = DateTime.UtcNow.AddMonths(-3);
var apprenticeship = await SetupApprenticeship();
var command = new StopApprenticeshipCommand(apprenticeship.Cohort.EmployerAccountId, apprenticeship.Id, stopDate, false, new UserInfo());
// Act
var exception = Assert.ThrowsAsync<DomainException>(async () => await _handler.Handle(command, new CancellationToken()));
// Assert
exception.DomainErrors.Should().BeEquivalentTo(new { PropertyName = "stopDate", ErrorMessage = $"Invalid Stop Date. Stop date cannot be before the apprenticeship has started." });
}
[Test, MoqAutoData]
public async Task Handle_WhenHandlingCommand_StoppingApprenticeship_ThenShouldUpdateDatabaseRecord()
{
// Arrange
var apprenticeship = await SetupApprenticeship();
var stopDate = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 1);
var command = new StopApprenticeshipCommand(apprenticeship.Cohort.EmployerAccountId, apprenticeship.Id, stopDate, false, new UserInfo());
// Act
await _handler.Handle(command, new CancellationToken());
// Simulate Unit of Work contex transaction ending in http request.
await _dbContext.SaveChangesAsync();
// Assert
var apprenticeshipAssertion = await _confirmationDbContext.Apprenticeships.FirstAsync(a => a.Id == apprenticeship.Id);
apprenticeshipAssertion.StopDate.Should().Be(stopDate);
apprenticeshipAssertion.MadeRedundant.Should().Be(false);
apprenticeshipAssertion.PaymentStatus.Should().Be(PaymentStatus.Withdrawn);
}
[Test, MoqAutoData]
public async Task Handle_WhenHandlingCommand_StoppingApprenticeship_ThenShouldPublishApprenticeshipStoppedEvent()
{
// Arrange
var apprenticeship = await SetupApprenticeship();
var stopDate = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 1);
var command = new StopApprenticeshipCommand(apprenticeship.Cohort.EmployerAccountId, apprenticeship.Id, stopDate, false, new UserInfo());
// Act
await _handler.Handle(command, new CancellationToken());
// Assert
var stoppedEvent = _unitOfWorkContext.GetEvents().OfType<ApprenticeshipStoppedEvent>().First();
stoppedEvent.Should().BeEquivalentTo(new ApprenticeshipStoppedEvent
{
AppliedOn = _currentDateTime.Object.UtcNow,
ApprenticeshipId = apprenticeship.Id,
StopDate = stopDate
});
}
[Test, MoqAutoData]
public async Task Handle_WhenHandlingCommand_StoppingApprenticeship_ThenShouldSendProviderEmail(string hashedAppId)
{
// Arrange
var apprenticeship = await SetupApprenticeship();
var fixture = new Fixture();
apprenticeship.Cohort.ProviderId = fixture.Create<long>();
_encodingService.Setup(a => a.Encode(apprenticeship.Id, EncodingType.ApprenticeshipId)).Returns(hashedAppId);
var stopDate = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 1);
var templateName = "ProviderApprenticeshipStopNotification";
var tokenUrl = $"{apprenticeship.Cohort.ProviderId}/apprentices/manage/{hashedAppId}/details";
var tokens = new Dictionary<string, string>
{
{"EMPLOYER",apprenticeship.Cohort.AccountLegalEntity.Name },
{"APPRENTICE", apprenticeship.ApprenticeName },
{"DATE",stopDate.ToString("dd/MM/yyyy") },
{"URL",tokenUrl },
};
var command = new StopApprenticeshipCommand(apprenticeship.Cohort.EmployerAccountId, apprenticeship.Id, stopDate, false, new UserInfo());
// Act
await _handler.Handle(command, new CancellationToken());
// Assert
_nserviceBusContext.Verify(s => s.Send(It.Is<SendEmailToProviderCommand>(x =>
x.ProviderId == apprenticeship.Cohort.ProviderId &&
x.Template == templateName &&
VerifyTokens(x.Tokens, tokens)), It.IsAny<SendOptions>()));
}
[Test, MoqAutoData]
public async Task Handle_WhenHandlingCommand_StoppingApprenticeship_ThenShouldResolveDataLocks()
{
// Arrange
var apprenticeship = await SetupApprenticeship();
var stopDate = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 1);
var command = new StopApprenticeshipCommand(apprenticeship.Cohort.EmployerAccountId, apprenticeship.Id, stopDate, false, new UserInfo());
// Act
await _handler.Handle(command, new CancellationToken());
// Simulate Unit of Work contex transaction ending in http request.
await _dbContext.SaveChangesAsync();
// Assert
var dataLockAssertion = await _confirmationDbContext.DataLocks.Where(s => s.ApprenticeshipId == apprenticeship.Id).ToListAsync();
dataLockAssertion.Should().HaveCount(4);
dataLockAssertion.Where(s => s.IsResolved).Should().HaveCount(2);
}
[Test, MoqAutoData]
public async Task Handle_WhenHandlingCommand_StoppingApprenticeshipBeforeItSarts_ThenShouldResolveDataLocks()
{
// Arrange
var futureDate = DateTime.UtcNow.AddMonths(4);
var startAndStopDate = new DateTime(futureDate.Year, futureDate.Month, 1);
var apprenticeship = await SetupApprenticeship(startDate: startAndStopDate);
var command = new StopApprenticeshipCommand(apprenticeship.Cohort.EmployerAccountId, apprenticeship.Id, startAndStopDate, false, new UserInfo());
// Act
await _handler.Handle(command, new CancellationToken());
// Simulate Unit of Work contex transaction ending in http request.
await _dbContext.SaveChangesAsync();
// Assert
var dataLockAssertion = await _confirmationDbContext.DataLocks.Where(s => s.ApprenticeshipId == apprenticeship.Id).ToListAsync();
dataLockAssertion.Should().HaveCount(4);
dataLockAssertion.Where(s => s.IsResolved).Should().HaveCount(3);
}
[Test, MoqAutoData]
public async Task Handle_WhenHandlingCommand_StoppingApprenticeship_CreatesAddHistoyEvent()
{
// Arrange
var apprenticeship = await SetupApprenticeship();
var stopDate = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 1);
var command = new StopApprenticeshipCommand(apprenticeship.Cohort.EmployerAccountId, apprenticeship.Id, stopDate, false, new UserInfo());
// Act
await _handler.Handle(command, new CancellationToken());
// Simulate Unit of Work contex transaction ending in http request.
await _dbContext.SaveChangesAsync();
// Assert
var historyEvent = _unitOfWorkContext.GetEvents().OfType<EntityStateChangedEvent>().First(e => e.EntityId == apprenticeship.Id);
historyEvent.EntityType.Should().Be("Apprenticeship");
historyEvent.StateChangeType.Should().Be(UserAction.StopApprenticeship);
var definition = new { StopDate = DateTime.MinValue, MadeRedundant = true, PaymentStatus = PaymentStatus.Active };
var historyState = JsonConvert.DeserializeAnonymousType(historyEvent.UpdatedState, definition);
historyState.StopDate.Should().Be(stopDate);
historyState.MadeRedundant.Should().Be(false);
historyState.PaymentStatus.Should().Be(PaymentStatus.Withdrawn);
}
private bool VerifyTokens(Dictionary<string, string> actualTokens, Dictionary<string, string> expectedTokens)
{
actualTokens.Should().BeEquivalentTo(expectedTokens);
return true;
}
private async Task<Apprenticeship> SetupApprenticeship(Party party = Party.Employer, PaymentStatus paymentStatus = PaymentStatus.Active, DateTime? startDate = null)
{
var today = DateTime.UtcNow;
_authenticationService.Setup(a => a.GetUserParty()).Returns(party);
_currentDateTime.Setup(a => a.UtcNow).Returns(today);
var fixture = new Fixture();
var apprenticeshipId = fixture.Create<long>();
var apprenticeship = new Apprenticeship
{
Id = apprenticeshipId,
Cohort = new Cohort
{
EmployerAccountId = fixture.Create<long>(),
AccountLegalEntity = new AccountLegalEntity()
},
DataLockStatus = SetupDataLocks(apprenticeshipId),
PaymentStatus = paymentStatus,
StartDate = startDate != null ? startDate.Value : DateTime.UtcNow.AddMonths(-2)
};
_dbContext.Apprenticeships.Add(apprenticeship);
await _dbContext.SaveChangesAsync();
return apprenticeship;
}
private ICollection<DataLockStatus> SetupDataLocks(long apprenticeshipId)
{
var activeDataLock4 = new DataLockStatus
{
ApprenticeshipId = apprenticeshipId,
EventStatus = EventStatus.New,
IsExpired = false,
TriageStatus = TriageStatus.Restart,
ErrorCode = DataLockErrorCode.Dlock04
};
var activeDataLock5 = new DataLockStatus
{
ApprenticeshipId = apprenticeshipId,
EventStatus = EventStatus.New,
IsExpired = false,
TriageStatus = TriageStatus.Restart,
ErrorCode = DataLockErrorCode.Dlock05
};
var inactiveDataLock6 = new DataLockStatus
{
ApprenticeshipId = apprenticeshipId,
EventStatus = EventStatus.Removed,
IsExpired = false,
TriageStatus = TriageStatus.Restart,
ErrorCode = DataLockErrorCode.Dlock04
};
var dataLockForApprenticeshipBeforeStart = new DataLockStatus
{
ApprenticeshipId = apprenticeshipId,
EventStatus = EventStatus.New,
IsExpired = false,
TriageStatus = TriageStatus.Change,
ErrorCode = DataLockErrorCode.Dlock04
};
return new List<DataLockStatus> { activeDataLock4, activeDataLock5, inactiveDataLock6, dataLockForApprenticeshipBeforeStart };
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentitySample.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace IdentitySample.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "1.0.0-rc3")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("IdentitySample.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("IdentitySample.Models.ApplicationUser")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("IdentitySample.Models.ApplicationUser")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Users")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("IdentitySample.Models.ApplicationUser")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| |
using System;
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Support.V8.Renderscript;
using Android.Util;
using Android.Views;
namespace Blurring
{
/// <summary>
/// A custom view for presenting a dynamically blurred version of another view's content.
/// </summary>
public class BlurringView : View
{
/// <summary>
/// The default blur radius
/// </summary>
public readonly static int DefaultBlurRadius = 6;
/// <summary>
/// The default downsample factor
/// </summary>
public readonly static int DefaultDownsampleFactor = 4;
/// <summary>
/// The default overlay color
/// </summary>
public readonly static Color DefaultOverlayColor = Color.Argb(100, 0, 0, 0);
/// <summary>
/// The default overlay background color
/// </summary>
public readonly static Color DefaultOverlayBackgroundColor = Color.Transparent;
private int downsampleFactor;
private bool downsampleFactorChanged;
private int blurRadius;
private int blurredViewWidth;
private int blurredViewHeight;
private Bitmap bitmapToBlur;
private Bitmap blurredBitmap;
private Canvas blurringCanvas;
private RenderScript renderScript;
private ScriptIntrinsicBlur blurScript;
private Allocation blurInput;
private Allocation blurOutput;
/// <summary>
/// Initializes a new instance of the <see cref="BlurringView"/> class.
/// </summary>
/// <param name="context">The context.</param>
public BlurringView(Context context)
: base(context)
{
Init(context, null);
}
/// <summary>
/// Initializes a new instance of the <see cref="BlurringView"/> class.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="attrs">The attribute set.</param>
public BlurringView(Context context, IAttributeSet attrs)
: base(context, attrs)
{
Init(context, attrs);
}
private void Init(Context context, IAttributeSet attrs)
{
// set up the script
try
{
renderScript = RenderScript.Create(context);
blurScript = ScriptIntrinsicBlur.Create(renderScript, Element.U8_4(renderScript));
}
catch (Java.Lang.RuntimeException ex)
{
if (ex.Class.Name == "android.support.v8.renderscript.RSRuntimeException")
{
Console.WriteLine(ex);
}
else
{
throw;
}
}
// set the default values
BlurRadius = DefaultBlurRadius;
DownsampleFactor = DefaultDownsampleFactor;
OverlayColor = DefaultOverlayColor;
OverlayBackgroundColor = DefaultOverlayBackgroundColor;
BlurredView = null;
if (attrs != null)
{
// read any XML values
var a = context.Theme.ObtainStyledAttributes(attrs, Resource.Styleable.BlurringView, 0, 0);
try
{
BlurRadius = a.GetInteger(Resource.Styleable.BlurringView_blurRadius, DefaultBlurRadius);
DownsampleFactor = a.GetInteger(Resource.Styleable.BlurringView_downsampleFactor, DefaultDownsampleFactor);
OverlayColor = a.GetColor(Resource.Styleable.BlurringView_overlayColor, DefaultOverlayColor);
OverlayBackgroundColor = a.GetColor(Resource.Styleable.BlurringView_overlayBackgroundColor, DefaultOverlayBackgroundColor);
}
finally
{
a.Recycle();
}
}
}
/// <summary>
/// Gets or sets the view to be blurred.
/// </summary>
/// <value>The view to be blurred.</value>
public View BlurredView { get; set; }
/// <summary>
/// Gets or sets the downsample factor.
/// </summary>
/// <value>The downsample factor.</value>
/// <exception cref="ArgumentException">Downsample factor must be greater than 0.</exception>
public int DownsampleFactor
{
get { return downsampleFactor; }
set
{
if (value <= 0)
{
throw new ArgumentException("Downsample factor must be greater than 0.");
}
if (downsampleFactor != value)
{
downsampleFactor = value;
downsampleFactorChanged = true;
}
}
}
/// <summary>
/// Gets or sets the blur radius.
/// </summary>
/// <value>The blur radius.</value>
/// <exception cref="System.ArgumentException">
/// Blur radius factor must be greater than 0.
/// or
/// Blur radius must be less than 25.
/// </exception>
public int BlurRadius
{
get { return blurRadius; }
set
{
if (value <= 0)
{
throw new ArgumentException("Blur radius factor must be greater than 0.");
}
if (value > 25)
{
throw new ArgumentException("Blur radius must be less than 25.");
}
if (blurRadius != value)
{
blurRadius = value;
if (blurScript != null)
{
blurScript.SetRadius(value);
}
}
}
}
/// <summary>
/// Gets or sets the color of the overlay.
/// </summary>
/// <value>The color of the overlay.</value>
public Color OverlayColor { get; set; }
/// <summary>
/// Gets or sets the color of the overlay before blurring.
/// </summary>
/// <value>The color of the overlay before blurring.</value>
public Color OverlayBackgroundColor { get; set; }
/// <summary>
/// Handles the drawing of the blurred view.
/// </summary>
/// <param name="canvas">The canvas on which to draw.</param>
protected override void OnDraw(Canvas canvas)
{
base.OnDraw(canvas);
if (BlurredView != null)
{
if (Prepare())
{
bitmapToBlur.EraseColor(OverlayBackgroundColor);
BlurredView.Draw(blurringCanvas);
if (renderScript != null)
{
blurInput.CopyFrom(bitmapToBlur);
blurScript.SetInput(blurInput);
blurScript.ForEach(blurOutput);
blurOutput.CopyTo(blurredBitmap);
}
else
{
StackBlur.Blur(bitmapToBlur, blurredBitmap, BlurRadius);
}
canvas.Save();
float x = 0;
float y = 0;
if (Build.VERSION.SdkInt < BuildVersionCodes.Honeycomb)
{
x = BlurredView.Left - Left;
y = BlurredView.Top - Top;
}
else
{
x = BlurredView.GetX() - GetX();
y = BlurredView.GetY() - GetY();
}
canvas.Translate(x, y);
canvas.Scale(downsampleFactor, downsampleFactor);
canvas.DrawBitmap(blurredBitmap, 0, 0, null);
canvas.Restore();
}
canvas.DrawColor(OverlayColor);
}
}
private bool Prepare()
{
int width = BlurredView.Width;
int height = BlurredView.Height;
if (blurringCanvas == null || downsampleFactorChanged || blurredViewWidth != width || blurredViewHeight != height)
{
downsampleFactorChanged = false;
blurredViewWidth = width;
blurredViewHeight = height;
int scaledWidth = width / downsampleFactor;
int scaledHeight = height / downsampleFactor;
scaledWidth = scaledWidth - scaledWidth % 4 + 4;
scaledHeight = scaledHeight - scaledHeight % 4 + 4;
if (blurredBitmap == null || blurredBitmap.Width != scaledWidth || blurredBitmap.Height != scaledHeight)
{
bitmapToBlur = Bitmap.CreateBitmap(scaledWidth, scaledHeight, Bitmap.Config.Argb8888);
if (bitmapToBlur == null)
{
return false;
}
blurredBitmap = Bitmap.CreateBitmap(scaledWidth, scaledHeight, Bitmap.Config.Argb8888);
if (blurredBitmap == null)
{
return false;
}
}
blurringCanvas = new Canvas(bitmapToBlur);
blurringCanvas.Scale(1f / downsampleFactor, 1f / downsampleFactor);
if (renderScript != null)
{
blurInput = Allocation.CreateFromBitmap(renderScript, bitmapToBlur, Allocation.MipmapControl.MipmapNone, Allocation.UsageScript);
blurOutput = Allocation.CreateTyped(renderScript, blurInput.Type);
}
}
return true;
}
/// <summary>
/// This is called when the view is detached from a window.
/// </summary>
protected override void OnDetachedFromWindow()
{
base.OnDetachedFromWindow();
if (renderScript != null)
{
renderScript.Destroy();
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for VirtualNetworksOperations.
/// </summary>
public static partial class VirtualNetworksOperationsExtensions
{
/// <summary>
/// Deletes the specified virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
public static void Delete(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName)
{
operations.DeleteAsync(resourceGroupName, virtualNetworkName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the specified virtual network by resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
public static VirtualNetwork Get(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, string expand = default(string))
{
return operations.GetAsync(resourceGroupName, virtualNetworkName, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified virtual network by resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualNetwork> GetAsync(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a virtual network in the specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update virtual network operation
/// </param>
public static VirtualNetwork CreateOrUpdate(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, virtualNetworkName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a virtual network in the specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update virtual network operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualNetwork> CreateOrUpdateAsync(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all virtual networks in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<VirtualNetwork> ListAll(this IVirtualNetworksOperations operations)
{
return operations.ListAllAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all virtual networks in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualNetwork>> ListAllAsync(this IVirtualNetworksOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all virtual networks in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<VirtualNetwork> List(this IVirtualNetworksOperations operations, string resourceGroupName)
{
return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all virtual networks in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualNetwork>> ListAsync(this IVirtualNetworksOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Checks whether a private IP address is available for use.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='ipAddress'>
/// The private IP address to be verified.
/// </param>
public static IPAddressAvailabilityResult CheckIPAddressAvailability(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, string ipAddress = default(string))
{
return operations.CheckIPAddressAvailabilityAsync(resourceGroupName, virtualNetworkName, ipAddress).GetAwaiter().GetResult();
}
/// <summary>
/// Checks whether a private IP address is available for use.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='ipAddress'>
/// The private IP address to be verified.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPAddressAvailabilityResult> CheckIPAddressAvailabilityAsync(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, string ipAddress = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CheckIPAddressAvailabilityWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, ipAddress, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
public static void BeginDelete(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName)
{
operations.BeginDeleteAsync(resourceGroupName, virtualNetworkName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates or updates a virtual network in the specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update virtual network operation
/// </param>
public static VirtualNetwork BeginCreateOrUpdate(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, virtualNetworkName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a virtual network in the specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update virtual network operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualNetwork> BeginCreateOrUpdateAsync(this IVirtualNetworksOperations operations, string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all virtual networks in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<VirtualNetwork> ListAllNext(this IVirtualNetworksOperations operations, string nextPageLink)
{
return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all virtual networks in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualNetwork>> ListAllNextAsync(this IVirtualNetworksOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all virtual networks in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<VirtualNetwork> ListNext(this IVirtualNetworksOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all virtual networks in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualNetwork>> ListNextAsync(this IVirtualNetworksOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/*
* 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.IO;
using System.Reflection;
using log4net;
using NDesk.Options;
using Nini.Config;
using Mono.Addins;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenMetaverse;
namespace OpenSim.Region.CoreModules.World.Archiver
{
/// <summary>
/// This module loads and saves OpenSimulator region archives
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ArchiverModule")]
public class ArchiverModule : INonSharedRegionModule, IRegionArchiverModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public Scene Scene { get; private set; }
public IRegionCombinerModule RegionCombinerModule { get; private set; }
/// <value>
/// The file used to load and save an opensimulator archive if no filename has been specified
/// </value>
protected const string DEFAULT_OAR_BACKUP_FILENAME = "region.oar";
public string Name
{
get { return "RegionArchiverModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void Initialise(IConfigSource source)
{
//m_log.Debug("[ARCHIVER] Initialising");
}
public void AddRegion(Scene scene)
{
Scene = scene;
Scene.RegisterModuleInterface<IRegionArchiverModule>(this);
//m_log.DebugFormat("[ARCHIVER]: Enabled for region {0}", scene.RegionInfo.RegionName);
}
public void RegionLoaded(Scene scene)
{
RegionCombinerModule = scene.RequestModuleInterface<IRegionCombinerModule>();
}
public void RemoveRegion(Scene scene)
{
}
public void Close()
{
}
/// <summary>
/// Load a whole region from an opensimulator archive.
/// </summary>
/// <param name="cmdparams"></param>
public void HandleLoadOarConsoleCommand(string module, string[] cmdparams)
{
bool mergeOar = false;
bool skipAssets = false;
bool forceTerrain = false;
bool forceParcels = false;
bool noObjects = false;
Vector3 displacement = new Vector3(0f, 0f, 0f);
String defaultUser = "";
float rotation = 0f;
Vector3 rotationCenter = new Vector3(Constants.RegionSize / 2f, Constants.RegionSize / 2f, 0);
OptionSet options = new OptionSet();
options.Add("m|merge", delegate (string v) { mergeOar = (v != null); });
options.Add("s|skip-assets", delegate (string v) { skipAssets = (v != null); });
options.Add("force-terrain", delegate (string v) { forceTerrain = (v != null); });
options.Add("forceterrain", delegate (string v) { forceTerrain = (v != null); }); // downward compatibility
options.Add("force-parcels", delegate (string v) { forceParcels = (v != null); });
options.Add("forceparcels", delegate (string v) { forceParcels = (v != null); }); // downward compatibility
options.Add("no-objects", delegate (string v) { noObjects = (v != null); });
options.Add("default-user=", delegate(string v) { defaultUser = (v == null) ? "" : v; });
options.Add("displacement=", delegate (string v) {
try
{
displacement = v == null ? Vector3.Zero : Vector3.Parse(v);
}
catch
{
m_log.ErrorFormat("[ARCHIVER MODULE] failure parsing displacement");
m_log.ErrorFormat("[ARCHIVER MODULE] Must be represented as vector3: --displacement \"<128,128,0>\"");
return;
}
});
options.Add("rotation=", delegate(string v)
{
try
{
rotation = v == null ? 0f : float.Parse(v);
}
catch
{
m_log.ErrorFormat("[ARCHIVER MODULE] failure parsing rotation");
m_log.ErrorFormat("[ARCHIVER MODULE] Must be an angle in degrees between -360 and +360: --rotation 45");
return;
}
// Convert to radians for internals
rotation = Util.Clamp<float>(rotation, -359f, 359f) / 180f * (float)Math.PI;
});
options.Add("rotation-center=", delegate (string v) {
try
{
rotationCenter = v == null ? Vector3.Zero : Vector3.Parse(v);
}
catch
{
m_log.ErrorFormat("[ARCHIVER MODULE] failure parsing rotation displacement");
m_log.ErrorFormat("[ARCHIVER MODULE] Must be represented as vector3: --rotation-center \"<128,128,0>\"");
return;
}
});
// Send a message to the region ready module
/* bluewall* Disable this for the time being
IRegionReadyModule rready = m_scene.RequestModuleInterface<IRegionReadyModule>();
if (rready != null)
{
rready.OarLoadingAlert("load");
}
*/
List<string> mainParams = options.Parse(cmdparams);
// m_log.DebugFormat("MERGE OAR IS [{0}]", mergeOar);
//
// foreach (string param in mainParams)
// m_log.DebugFormat("GOT PARAM [{0}]", param);
Dictionary<string, object> archiveOptions = new Dictionary<string, object>();
if (mergeOar) archiveOptions.Add("merge", null);
if (skipAssets) archiveOptions.Add("skipAssets", null);
if (forceTerrain) archiveOptions.Add("force-terrain", null);
if (forceParcels) archiveOptions.Add("force-parcels", null);
if (noObjects) archiveOptions.Add("no-objects", null);
if (defaultUser != "")
{
UUID defaultUserUUID = UUID.Zero;
try
{
defaultUserUUID = Scene.UserManagementModule.GetUserIdByName(defaultUser);
}
catch
{
m_log.ErrorFormat("[ARCHIVER MODULE] default user must be in format \"First Last\"", defaultUser);
}
if (defaultUserUUID == UUID.Zero)
{
m_log.ErrorFormat("[ARCHIVER MODULE] cannot find specified default user {0}", defaultUser);
return;
}
else
{
archiveOptions.Add("default-user", defaultUserUUID);
}
}
archiveOptions.Add("displacement", displacement);
archiveOptions.Add("rotation", rotation);
archiveOptions.Add("rotation-center", rotationCenter);
if (mainParams.Count > 2)
{
DearchiveRegion(mainParams[2], Guid.Empty, archiveOptions);
}
else
{
DearchiveRegion(DEFAULT_OAR_BACKUP_FILENAME, Guid.Empty, archiveOptions);
}
}
/// <summary>
/// Save a region to a file, including all the assets needed to restore it.
/// </summary>
/// <param name="cmdparams"></param>
public void HandleSaveOarConsoleCommand(string module, string[] cmdparams)
{
Dictionary<string, object> options = new Dictionary<string, object>();
OptionSet ops = new OptionSet();
// legacy argument [obsolete]
ops.Add("p|profile=", delegate(string v) { Console.WriteLine("\n WARNING: -profile option is obsolete and it will not work. Use -home instead.\n"); });
// preferred
ops.Add("h|home=", delegate(string v) { options["home"] = v; });
ops.Add("noassets", delegate(string v) { options["noassets"] = v != null; });
ops.Add("publish", v => options["wipe-owners"] = v != null);
ops.Add("perm=", delegate(string v) { options["checkPermissions"] = v; });
ops.Add("all", delegate(string v) { options["all"] = v != null; });
List<string> mainParams = ops.Parse(cmdparams);
string path;
if (mainParams.Count > 2)
path = mainParams[2];
else
path = DEFAULT_OAR_BACKUP_FILENAME;
// Not doing this right now as this causes some problems with auto-backup systems. Maybe a force flag is
// needed
// if (!ConsoleUtil.CheckFileDoesNotExist(MainConsole.Instance, path))
// return;
ArchiveRegion(path, options);
}
public void ArchiveRegion(string savePath, Dictionary<string, object> options)
{
ArchiveRegion(savePath, Guid.Empty, options);
}
public void ArchiveRegion(string savePath, Guid requestId, Dictionary<string, object> options)
{
m_log.InfoFormat(
"[ARCHIVER]: Writing archive for region {0} to {1}", Scene.RegionInfo.RegionName, savePath);
new ArchiveWriteRequest(Scene, savePath, requestId).ArchiveRegion(options);
}
public void ArchiveRegion(Stream saveStream)
{
ArchiveRegion(saveStream, Guid.Empty);
}
public void ArchiveRegion(Stream saveStream, Guid requestId)
{
ArchiveRegion(saveStream, requestId, new Dictionary<string, object>());
}
public void ArchiveRegion(Stream saveStream, Guid requestId, Dictionary<string, object> options)
{
new ArchiveWriteRequest(Scene, saveStream, requestId).ArchiveRegion(options);
}
public void DearchiveRegion(string loadPath)
{
Dictionary<string, object> archiveOptions = new Dictionary<string, object>();
DearchiveRegion(loadPath, Guid.Empty, archiveOptions);
}
public void DearchiveRegion(string loadPath, Guid requestId, Dictionary<string,object> options)
{
m_log.InfoFormat(
"[ARCHIVER]: Loading archive to region {0} from {1}", Scene.RegionInfo.RegionName, loadPath);
new ArchiveReadRequest(Scene, loadPath, requestId, options).DearchiveRegion();
}
public void DearchiveRegion(Stream loadStream)
{
Dictionary<string, object> archiveOptions = new Dictionary<string, object>();
DearchiveRegion(loadStream, Guid.Empty, archiveOptions);
}
public void DearchiveRegion(Stream loadStream, Guid requestId, Dictionary<string, object> options)
{
new ArchiveReadRequest(Scene, loadStream, requestId, options).DearchiveRegion();
}
}
}
| |
using UnityEngine;
[AddComponentMenu("Modifiers/Selection/Volume")]
public class MegaVolSelect : MegaSelectionMod
{
public override MegaModChannel ChannelsReq() { return MegaModChannel.Col | MegaModChannel.Verts; }
public override string ModName() { return "Vol Select"; }
public override string GetHelpURL() { return "?page_id=1307"; }
float[] modselection;
public float[] GetSel() { return modselection; }
public Vector3 origin = Vector3.zero;
public float falloff = 1.0f;
public float radius = 1.0f;
public Color gizCol = new Color(0.5f, 0.5f, 0.5f, 0.25f);
public float gizSize = 0.01f;
public bool useCurrentVerts = true;
public bool displayWeights = true;
public bool freezeSelection = false;
public MegaVolumeType volType = MegaVolumeType.Sphere;
public Vector3 boxsize = Vector3.one;
public float weight = 1.0f;
public Transform target;
float GetDistBox(Vector3 p)
{
// Work in the box's coordinate system.
Vector3 diff = p - origin;
float sqrDistance = 0.0f;
float delta;
Vector3 closest = diff;
if ( closest.x < -boxsize.x )
{
delta = closest.x + boxsize.x;
sqrDistance += delta * delta;
closest.x = -boxsize.x;
}
else
{
if ( closest.x > boxsize.x )
{
delta = closest.x - boxsize.x;
sqrDistance += delta * delta;
closest.x = boxsize.x;
}
}
if ( closest.y < -boxsize.y )
{
delta = closest.y + boxsize.y;
sqrDistance += delta * delta;
closest.y = -boxsize.y;
}
else
{
if ( closest.y > boxsize.y )
{
delta = closest.y - boxsize.y;
sqrDistance += delta * delta;
closest.y = boxsize.y;
}
}
if ( closest.z < -boxsize.z )
{
delta = closest.z + boxsize.z;
sqrDistance += delta * delta;
closest.z = -boxsize.z;
}
else
{
if ( closest.z > boxsize.z )
{
delta = closest.z - boxsize.z;
sqrDistance += delta * delta;
closest.z = boxsize.z;
}
}
return Mathf.Sqrt(sqrDistance); // * 0.5f;
}
public override void GetSelection(MegaModifiers mc)
{
if ( target )
{
origin = transform.worldToLocalMatrix.MultiplyPoint(target.position);
}
if ( modselection == null || modselection.Length != mc.verts.Length )
{
modselection = new float[mc.verts.Length];
}
if ( freezeSelection )
{
mc.selection = modselection;
return;
}
// we dont need to update if nothing changes
if ( volType == MegaVolumeType.Sphere )
{
if ( useCurrentVerts )
{
for ( int i = 0; i < verts.Length; i++ )
{
float d = Vector3.Distance(origin, verts[i]) - radius;
if ( d < 0.0f )
modselection[i] = weight;
else
{
float w = Mathf.Exp(-falloff * Mathf.Abs(d));
modselection[i] = w * weight; //mc.cols[i][c];
}
}
}
else
{
for ( int i = 0; i < verts.Length; i++ )
{
float d = Vector3.Distance(origin, verts[i]) - radius;
if ( d < 0.0f )
modselection[i] = weight;
else
{
float w = Mathf.Exp(-falloff * Mathf.Abs(d));
modselection[i] = w * weight; //mc.cols[i][c];
}
}
}
}
else
{
if ( useCurrentVerts )
{
for ( int i = 0; i < verts.Length; i++ )
{
float d = GetDistBox(verts[i]);
if ( d < 0.0f )
modselection[i] = weight;
else
{
float w = Mathf.Exp(-falloff * Mathf.Abs(d));
modselection[i] = w * weight; //mc.cols[i][c];
}
}
}
else
{
for ( int i = 0; i < verts.Length; i++ )
{
float d = GetDistBox(verts[i]);
if ( d < 0.0f )
modselection[i] = weight;
else
{
float w = Mathf.Exp(-falloff * Mathf.Abs(d));
modselection[i] = w * weight; //mc.cols[i][c];
}
}
}
}
// We only need the copy if we are first mod
if ( (mc.dirtyChannels & MegaModChannel.Verts) == 0 )
mc.InitVertSource();
mc.selection = modselection;
}
public override void DrawGizmo(MegaModContext context)
{
if ( ModEnabled )
{
base.DrawGizmo(context);
Matrix4x4 tm = gameObject.transform.localToWorldMatrix;
Gizmos.matrix = tm;
if ( enabled && volType == MegaVolumeType.Box )
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireCube(origin, boxsize * 2.0f); // * 0.5f);
}
if ( enabled && volType == MegaVolumeType.Sphere )
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(origin, radius); // * 0.5f);
}
Gizmos.matrix = Matrix4x4.identity;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http2Cat;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
using Xunit;
namespace Microsoft.AspNetCore.Server.HttpSys.FunctionalTests
{
public class Http2Tests : LoggedTest
{
private const string VersionForReset = "10.0.19529";
[ConditionalFact]
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10, SkipReason = "Http2 requires Win10")]
public async Task EmptyResponse_200()
{
using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext =>
{
var feature = httpContext.Features.Get<IHttpUpgradeFeature>();
Assert.False(feature.IsUpgradableRequest);
Assert.False(httpContext.Request.CanHaveBody());
// Default 200
return Task.CompletedTask;
});
await new HostBuilder()
.UseHttp2Cat(address, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
await h2Connection.StartStreamAsync(1, Http2Utilities.BrowserRequestHeaders, endStream: true);
await h2Connection.ReceiveHeadersAsync(1, decodedHeaders =>
{
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
var dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: true, length: 0);
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalTheory]
[InlineData("POST")]
[InlineData("PUT")]
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10, SkipReason = "Http2 requires Win10")]
public async Task RequestWithoutData_LengthRequired_Rejected(string method)
{
using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext =>
{
throw new NotImplementedException();
});
await new HostBuilder()
.UseHttp2Cat(address, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
var headers = new[]
{
new KeyValuePair<string, string>(HeaderNames.Method, method),
new KeyValuePair<string, string>(HeaderNames.Path, "/"),
new KeyValuePair<string, string>(HeaderNames.Scheme, "https"),
new KeyValuePair<string, string>(HeaderNames.Authority, "localhost:80"),
};
await h2Connection.StartStreamAsync(1, headers, endStream: true);
await h2Connection.ReceiveHeadersAsync(1, decodedHeaders =>
{
Assert.Equal("411", decodedHeaders[HeaderNames.Status]);
});
var dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: false, length: 344);
dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: true, length: 0);
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalTheory]
[InlineData("GET")]
[InlineData("HEAD")]
[InlineData("PATCH")]
[InlineData("DELETE")]
[InlineData("CUSTOM")]
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10, SkipReason = "Http2 requires Win10")]
public async Task RequestWithoutData_Success(string method)
{
using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext =>
{
Assert.True(HttpMethods.Equals(method, httpContext.Request.Method));
Assert.False(httpContext.Request.CanHaveBody());
Assert.Null(httpContext.Request.ContentLength);
Assert.False(httpContext.Request.Headers.ContainsKey(HeaderNames.TransferEncoding));
return Task.CompletedTask;
});
await new HostBuilder()
.UseHttp2Cat(address, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
var headers = new[]
{
new KeyValuePair<string, string>(HeaderNames.Method, method),
new KeyValuePair<string, string>(HeaderNames.Path, "/"),
new KeyValuePair<string, string>(HeaderNames.Scheme, "https"),
new KeyValuePair<string, string>(HeaderNames.Authority, "localhost:80"),
};
await h2Connection.StartStreamAsync(1, headers, endStream: true);
await h2Connection.ReceiveHeadersAsync(1, decodedHeaders =>
{
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
var dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: true, length: 0);
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalTheory]
[InlineData("GET")]
// [InlineData("HEAD")] Reset with code HTTP_1_1_REQUIRED
[InlineData("POST")]
[InlineData("PUT")]
[InlineData("PATCH")]
[InlineData("DELETE")]
[InlineData("CUSTOM")]
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10, SkipReason = "Http2 requires Win10")]
public async Task RequestWithDataAndContentLength_Success(string method)
{
using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext =>
{
Assert.True(HttpMethods.Equals(method, httpContext.Request.Method));
Assert.True(httpContext.Request.CanHaveBody());
Assert.Equal(11, httpContext.Request.ContentLength);
Assert.False(httpContext.Request.Headers.ContainsKey(HeaderNames.TransferEncoding));
return httpContext.Request.Body.CopyToAsync(httpContext.Response.Body);
});
await new HostBuilder()
.UseHttp2Cat(address, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
var headers = new[]
{
new KeyValuePair<string, string>(HeaderNames.Method, method),
new KeyValuePair<string, string>(HeaderNames.Path, "/"),
new KeyValuePair<string, string>(HeaderNames.Scheme, "https"),
new KeyValuePair<string, string>(HeaderNames.Authority, "localhost:80"),
new KeyValuePair<string, string>(HeaderNames.ContentLength, "11"),
};
await h2Connection.StartStreamAsync(1, headers, endStream: false);
await h2Connection.SendDataAsync(1, Encoding.UTF8.GetBytes("Hello World"), endStream: true);
// Http.Sys no longer sends a window update here on later versions.
if (Environment.OSVersion.Version < new Version(10, 0, 19041, 0))
{
var windowUpdate = await h2Connection.ReceiveFrameAsync();
Assert.Equal(Http2FrameType.WINDOW_UPDATE, windowUpdate.Type);
}
await h2Connection.ReceiveHeadersAsync(1, decodedHeaders =>
{
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
var dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: false, length: 11);
Assert.Equal("Hello World", Encoding.UTF8.GetString(dataFrame.Payload.Span));
dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: true, length: 0);
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalTheory]
[InlineData("GET")]
// [InlineData("HEAD")] Reset with code HTTP_1_1_REQUIRED
[InlineData("POST")]
[InlineData("PUT")]
[InlineData("PATCH")]
[InlineData("DELETE")]
[InlineData("CUSTOM")]
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10, SkipReason = "Http2 requires Win10")]
public async Task RequestWithDataAndNoContentLength_Success(string method)
{
using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext =>
{
Assert.True(HttpMethods.Equals(method, httpContext.Request.Method));
Assert.True(httpContext.Request.CanHaveBody());
Assert.Null(httpContext.Request.ContentLength);
// The client didn't send this header, Http.Sys added it for back compat with HTTP/1.1.
Assert.Equal("chunked", httpContext.Request.Headers.TransferEncoding);
return httpContext.Request.Body.CopyToAsync(httpContext.Response.Body);
});
await new HostBuilder()
.UseHttp2Cat(address, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
var headers = new[]
{
new KeyValuePair<string, string>(HeaderNames.Method, method),
new KeyValuePair<string, string>(HeaderNames.Path, "/"),
new KeyValuePair<string, string>(HeaderNames.Scheme, "https"),
new KeyValuePair<string, string>(HeaderNames.Authority, "localhost:80"),
};
await h2Connection.StartStreamAsync(1, headers, endStream: false);
await h2Connection.SendDataAsync(1, Encoding.UTF8.GetBytes("Hello World"), endStream: true);
// Http.Sys no longer sends a window update here on later versions.
if (Environment.OSVersion.Version < new Version(10, 0, 19041, 0))
{
var windowUpdate = await h2Connection.ReceiveFrameAsync();
Assert.Equal(Http2FrameType.WINDOW_UPDATE, windowUpdate.Type);
}
await h2Connection.ReceiveHeadersAsync(1, decodedHeaders =>
{
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
var dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: false, length: 11);
Assert.Equal("Hello World", Encoding.UTF8.GetString(dataFrame.Payload.Span));
dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: true, length: 0);
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalFact]
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10, SkipReason = "Http2 requires Win10")]
public async Task ResponseWithData_Success()
{
using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext =>
{
return httpContext.Response.WriteAsync("Hello World");
});
await new HostBuilder()
.UseHttp2Cat(address, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
await h2Connection.StartStreamAsync(1, Http2Utilities.BrowserRequestHeaders, endStream: true);
await h2Connection.ReceiveHeadersAsync(1, decodedHeaders =>
{
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
var dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: false, length: 11);
dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: true, length: 0);
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalFact(Skip = "https://github.com/dotnet/aspnetcore/issues/17420")]
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10, SkipReason = "Http2 requires Win10")]
[MaximumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10_19H1, SkipReason = "This is last version without GoAway support")]
public async Task ConnectionClose_NoOSSupport_NoGoAway()
{
using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext =>
{
httpContext.Response.Headers.Connection = "close";
return Task.FromResult(0);
});
await new HostBuilder()
.UseHttp2Cat(address, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
await h2Connection.StartStreamAsync(1, Http2Utilities.BrowserRequestHeaders, endStream: true);
await h2Connection.ReceiveHeadersAsync(1, endStream: true, decodedHeaders =>
{
// HTTP/2 filters out the connection header
Assert.False(decodedHeaders.ContainsKey(HeaderNames.Connection));
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
// Send and receive a second request to ensure there is no GoAway frame on the wire yet.
await h2Connection.StartStreamAsync(3, Http2Utilities.BrowserRequestHeaders, endStream: true);
await h2Connection.ReceiveHeadersAsync(3, endStream: true, decodedHeaders =>
{
// HTTP/2 filters out the connection header
Assert.False(decodedHeaders.ContainsKey(HeaderNames.Connection));
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
await h2Connection.StopConnectionAsync(expectedLastStreamId: 1, ignoreNonGoAwayFrames: false);
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalFact]
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10_19H2, SkipReason = "GoAway support was added in Win10_19H2.")]
public async Task ConnectionHeaderClose_OSSupport_SendsGoAway()
{
using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext =>
{
httpContext.Response.Headers.Connection = "close";
return Task.FromResult(0);
});
await new HostBuilder()
.UseHttp2Cat(address, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
await h2Connection.StartStreamAsync(1, Http2Utilities.BrowserRequestHeaders, endStream: true);
var goAwayFrame = await h2Connection.ReceiveFrameAsync();
h2Connection.VerifyGoAway(goAwayFrame, int.MaxValue, Http2ErrorCode.NO_ERROR);
await h2Connection.ReceiveHeadersAsync(1, decodedHeaders =>
{
// HTTP/2 filters out the connection header
Assert.False(decodedHeaders.ContainsKey(HeaderNames.Connection));
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
var dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: true, length: 0);
// Http.Sys doesn't send a final GoAway unless we ignore the first one and send 200 additional streams.
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalFact]
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10_19H2, SkipReason = "GoAway support was added in Win10_19H2.")]
public async Task ConnectionRequestClose_OSSupport_SendsGoAway()
{
using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext =>
{
httpContext.Connection.RequestClose();
return Task.FromResult(0);
});
await new HostBuilder()
.UseHttp2Cat(address, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
await h2Connection.StartStreamAsync(1, Http2Utilities.BrowserRequestHeaders, endStream: true);
var goAwayFrame = await h2Connection.ReceiveFrameAsync();
h2Connection.VerifyGoAway(goAwayFrame, int.MaxValue, Http2ErrorCode.NO_ERROR);
await h2Connection.ReceiveHeadersAsync(1, decodedHeaders =>
{
// HTTP/2 filters out the connection header
Assert.False(decodedHeaders.ContainsKey(HeaderNames.Connection));
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
var dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: true, length: 0);
// Http.Sys doesn't send a final GoAway unless we ignore the first one and send 200 additional streams.
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalFact]
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10_19H2, SkipReason = "GoAway support was added in Win10_19H2.")]
public async Task ConnectionClose_AdditionalRequests_ReceivesSecondGoAway()
{
using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext =>
{
httpContext.Response.Headers.Connection = "close";
return Task.FromResult(0);
});
await new HostBuilder()
.UseHttp2Cat(address, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
var streamId = 1;
await h2Connection.StartStreamAsync(streamId, Http2Utilities.BrowserRequestHeaders, endStream: true);
var goAwayFrame = await h2Connection.ReceiveFrameAsync();
h2Connection.VerifyGoAway(goAwayFrame, int.MaxValue, Http2ErrorCode.NO_ERROR);
await h2Connection.ReceiveHeadersAsync(streamId, decodedHeaders =>
{
// HTTP/2 filters out the connection header
Assert.False(decodedHeaders.ContainsKey(HeaderNames.Connection));
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
var dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, streamId, endOfStream: true, length: 0);
// Http.Sys doesn't send a final GoAway unless we ignore the first one and send 200 additional streams.
for (var i = 1; i < 200; i++)
{
streamId = 1 + (i * 2); // Odds.
await h2Connection.StartStreamAsync(streamId, Http2Utilities.BrowserRequestHeaders, endStream: true);
await h2Connection.ReceiveHeadersAsync(streamId, decodedHeaders =>
{
// HTTP/2 filters out the connection header
Assert.False(decodedHeaders.ContainsKey(HeaderNames.Connection));
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, streamId, endOfStream: true, length: 0);
}
streamId = 1 + (200 * 2); // Odds.
await h2Connection.StartStreamAsync(streamId, Http2Utilities.BrowserRequestHeaders, endStream: true);
// Final GoAway
goAwayFrame = await h2Connection.ReceiveFrameAsync();
h2Connection.VerifyGoAway(goAwayFrame, streamId, Http2ErrorCode.NO_ERROR);
// Normal response
await h2Connection.ReceiveHeadersAsync(streamId, decodedHeaders =>
{
// HTTP/2 filters out the connection header
Assert.False(decodedHeaders.ContainsKey(HeaderNames.Connection));
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, streamId, endOfStream: true, length: 0);
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalFact]
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10, SkipReason = "Http2 requires Win10")]
public async Task AppException_BeforeResponseHeaders_500()
{
using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext =>
{
throw new Exception("Application exception");
});
await new HostBuilder()
.UseHttp2Cat(address, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
await h2Connection.StartStreamAsync(1, Http2Utilities.BrowserRequestHeaders, endStream: true);
await h2Connection.ReceiveHeadersAsync(1, decodedHeaders =>
{
Assert.Equal("500", decodedHeaders[HeaderNames.Status]);
});
var dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: true, length: 0);
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalFact]
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10, SkipReason = "Http2 requires Win10")]
[MaximumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10_20H1, SkipReason = "This is last version without custom Reset support")]
public async Task AppException_AfterHeaders_PriorOSVersions_ResetCancel()
{
using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext =>
{
await httpContext.Response.Body.FlushAsync();
throw new Exception("Application exception");
});
await new HostBuilder()
.UseHttp2Cat(address, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
await h2Connection.StartStreamAsync(1, Http2Utilities.BrowserRequestHeaders, endStream: true);
await h2Connection.ReceiveHeadersAsync(1, decodedHeaders =>
{
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
var resetFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyResetFrame(resetFrame, expectedStreamId: 1, Http2ErrorCode.CANCEL);
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalFact]
[MinimumOSVersion(OperatingSystems.Windows, VersionForReset)]
public async Task AppException_AfterHeaders_ResetInternalError()
{
using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext =>
{
await httpContext.Response.Body.FlushAsync();
throw new Exception("Application exception");
});
await new HostBuilder()
.UseHttp2Cat(address, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
await h2Connection.StartStreamAsync(1, Http2Utilities.BrowserRequestHeaders, endStream: true);
await h2Connection.ReceiveHeadersAsync(1, decodedHeaders =>
{
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
var frame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyResetFrame(frame, expectedStreamId: 1, Http2ErrorCode.INTERNAL_ERROR);
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalFact]
public async Task Reset_Http1_NotSupported()
{
using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext =>
{
Assert.Equal("HTTP/1.1", httpContext.Request.Protocol);
var feature = httpContext.Features.Get<IHttpResetFeature>();
Assert.Null(feature);
return httpContext.Response.WriteAsync("Hello World");
}, LoggerFactory);
var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
using HttpClient client = new HttpClient(handler);
client.DefaultRequestVersion = HttpVersion.Version11;
var response = await client.GetStringAsync(address);
Assert.Equal("Hello World", response);
}
[ConditionalFact]
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10, SkipReason = "Http2 requires Win10")]
[MaximumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10_20H2, SkipReason = "This is last version without Reset support")]
public async Task Reset_PriorOSVersions_NotSupported()
{
using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext =>
{
Assert.Equal("HTTP/2", httpContext.Request.Protocol);
var feature = httpContext.Features.Get<IHttpResetFeature>();
Assert.Null(feature);
return httpContext.Response.WriteAsync("Hello World");
});
var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
using HttpClient client = new HttpClient(handler);
client.DefaultRequestVersion = HttpVersion.Version20;
var response = await client.GetStringAsync(address);
Assert.Equal("Hello World", response);
}
[ConditionalFact]
[QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/29126")]
[MinimumOSVersion(OperatingSystems.Windows, VersionForReset)]
public async Task Reset_BeforeResponse_Resets()
{
var appResult = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext =>
{
try
{
Assert.Equal("HTTP/2", httpContext.Request.Protocol);
var feature = httpContext.Features.Get<IHttpResetFeature>();
Assert.NotNull(feature);
feature.Reset(1111); // Custom
appResult.SetResult(0);
}
catch (Exception ex)
{
appResult.SetException(ex);
}
return Task.FromResult(0);
}, LoggerFactory);
await new HostBuilder()
.UseHttp2Cat(address, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
await h2Connection.StartStreamAsync(1, Http2Utilities.BrowserRequestHeaders, endStream: true);
var resetFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyResetFrame(resetFrame, expectedStreamId: 1, expectedErrorCode: (Http2ErrorCode)1111);
// Any app errors?
Assert.Equal(0, await appResult.Task.DefaultTimeout());
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalFact]
[MinimumOSVersion(OperatingSystems.Windows, VersionForReset)]
public async Task Reset_AfterResponseHeaders_Resets()
{
var appResult = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext =>
{
try
{
Assert.Equal("HTTP/2", httpContext.Request.Protocol);
var feature = httpContext.Features.Get<IHttpResetFeature>();
Assert.NotNull(feature);
await httpContext.Response.Body.FlushAsync();
feature.Reset(1111); // Custom
appResult.SetResult(0);
}
catch (Exception ex)
{
appResult.SetException(ex);
}
});
await new HostBuilder()
.UseHttp2Cat(address, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
await h2Connection.StartStreamAsync(1, Http2Utilities.BrowserRequestHeaders, endStream: true);
// Any app errors?
Assert.Equal(0, await appResult.Task.DefaultTimeout());
await h2Connection.ReceiveHeadersAsync(1, decodedHeaders =>
{
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
var resetFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyResetFrame(resetFrame, expectedStreamId: 1, expectedErrorCode: (Http2ErrorCode)1111);
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalFact]
[MinimumOSVersion(OperatingSystems.Windows, VersionForReset)]
public async Task Reset_DurringResponseBody_Resets()
{
var appResult = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext =>
{
try
{
Assert.Equal("HTTP/2", httpContext.Request.Protocol);
var feature = httpContext.Features.Get<IHttpResetFeature>();
Assert.NotNull(feature);
await httpContext.Response.WriteAsync("Hello World");
feature.Reset(1111); // Custom
appResult.SetResult(0);
}
catch (Exception ex)
{
appResult.SetException(ex);
}
});
await new HostBuilder()
.UseHttp2Cat(address, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
await h2Connection.StartStreamAsync(1, Http2Utilities.BrowserRequestHeaders, endStream: true);
// Any app errors?
Assert.Equal(0, await appResult.Task.DefaultTimeout());
await h2Connection.ReceiveHeadersAsync(1, decodedHeaders =>
{
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
var dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: false, length: 11);
var resetFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyResetFrame(resetFrame, expectedStreamId: 1, expectedErrorCode: (Http2ErrorCode)1111);
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalFact]
[MinimumOSVersion(OperatingSystems.Windows, VersionForReset)]
public async Task Reset_AfterCompleteAsync_NoReset()
{
var appResult = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext =>
{
try
{
Assert.Equal("HTTP/2", httpContext.Request.Protocol);
var feature = httpContext.Features.Get<IHttpResetFeature>();
Assert.NotNull(feature);
await httpContext.Response.WriteAsync("Hello World");
await httpContext.Response.CompleteAsync();
// The request and response are fully complete, the reset doesn't get sent.
feature.Reset(1111);
appResult.SetResult(0);
}
catch (Exception ex)
{
appResult.SetException(ex);
}
});
await new HostBuilder()
.UseHttp2Cat(address, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
await h2Connection.StartStreamAsync(1, Http2Utilities.BrowserRequestHeaders, endStream: true);
// Any app errors?
Assert.Equal(0, await appResult.Task.DefaultTimeout());
await h2Connection.ReceiveHeadersAsync(1, decodedHeaders =>
{
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
var dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: false, length: 11);
dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: true, length: 0);
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalFact]
[QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/29126")]
[MinimumOSVersion(OperatingSystems.Windows, VersionForReset)]
public async Task Reset_BeforeRequestBody_Resets()
{
var appResult = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext =>
{
try
{
Assert.Equal("HTTP/2", httpContext.Request.Protocol);
var feature = httpContext.Features.Get<IHttpResetFeature>();
Assert.NotNull(feature);
var readTask = httpContext.Request.Body.ReadAsync(new byte[10], 0, 10);
feature.Reset(1111);
await Assert.ThrowsAsync<IOException>(() => readTask);
appResult.SetResult(0);
}
catch (Exception ex)
{
appResult.SetException(ex);
}
});
await new HostBuilder()
.UseHttp2Cat(address, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
await h2Connection.StartStreamAsync(1, Http2Utilities.PostRequestHeaders, endStream: false);
// Any app errors?
Assert.Equal(0, await appResult.Task.DefaultTimeout());
var resetFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyResetFrame(resetFrame, expectedStreamId: 1, expectedErrorCode: (Http2ErrorCode)1111);
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalFact]
[QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/29126")]
[MinimumOSVersion(OperatingSystems.Windows, VersionForReset)]
public async Task Reset_DurringRequestBody_Resets()
{
var appResult = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext =>
{
try
{
Assert.Equal("HTTP/2", httpContext.Request.Protocol);
var feature = httpContext.Features.Get<IHttpResetFeature>();
Assert.NotNull(feature);
var read = await httpContext.Request.Body.ReadAsync(new byte[10], 0, 10);
Assert.Equal(10, read);
var readTask = httpContext.Request.Body.ReadAsync(new byte[10], 0, 10);
feature.Reset(1111);
await Assert.ThrowsAsync<IOException>(() => readTask);
appResult.SetResult(0);
}
catch (Exception ex)
{
appResult.SetException(ex);
}
});
await new HostBuilder()
.UseHttp2Cat(address, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
await h2Connection.StartStreamAsync(1, Http2Utilities.PostRequestHeaders, endStream: false);
await h2Connection.SendDataAsync(1, new byte[10], endStream: false);
// Any app errors?
Assert.Equal(0, await appResult.Task.DefaultTimeout());
var resetFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyResetFrame(resetFrame, expectedStreamId: 1, expectedErrorCode: (Http2ErrorCode)1111);
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
[ConditionalFact]
[MinimumOSVersion(OperatingSystems.Windows, VersionForReset)]
public async Task Reset_CompleteAsyncDurringRequestBody_Resets()
{
var appResult = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext =>
{
try
{
Assert.Equal("HTTP/2", httpContext.Request.Protocol);
var feature = httpContext.Features.Get<IHttpResetFeature>();
Assert.NotNull(feature);
var read = await httpContext.Request.Body.ReadAsync(new byte[10], 0, 10);
Assert.Equal(10, read);
var readTask = httpContext.Request.Body.ReadAsync(new byte[10], 0, 10);
await httpContext.Response.CompleteAsync();
feature.Reset((int)Http2ErrorCode.NO_ERROR); // GRPC does this
await Assert.ThrowsAsync<IOException>(() => readTask);
appResult.SetResult(0);
}
catch (Exception ex)
{
appResult.SetException(ex);
}
});
await new HostBuilder()
.UseHttp2Cat(address, async h2Connection =>
{
await h2Connection.InitializeConnectionAsync();
h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1.");
await h2Connection.StartStreamAsync(1, Http2Utilities.PostRequestHeaders, endStream: false);
await h2Connection.SendDataAsync(1, new byte[10], endStream: false);
// Any app errors?
Assert.Equal(0, await appResult.Task.DefaultTimeout());
await h2Connection.ReceiveHeadersAsync(1, decodedHeaders =>
{
Assert.Equal("200", decodedHeaders[HeaderNames.Status]);
});
var dataFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: true, length: 0);
var resetFrame = await h2Connection.ReceiveFrameAsync();
Http2Utilities.VerifyResetFrame(resetFrame, expectedStreamId: 1, expectedErrorCode: Http2ErrorCode.NO_ERROR);
h2Connection.Logger.LogInformation("Connection stopped.");
})
.Build().RunAsync();
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using UnityStandardAssets.ImageEffects;
using UnityEngine;
public class InventoryOld : MonoBehaviour {
//[HideInInspector]
public List<InventorySlot> slotList = new List<InventorySlot>();
public int currentJunks = 0;
[HideInInspector]
public string openInventoryButton = "PS4_TRIANGLE";
[HideInInspector]
public string openInventoryKey = "";
public Texture2D quickSlotTexture;
public bool isInvOpened = false;
public bool isQuickOpened = true;
public int maxSlotNumber;
public int quickAccessSlotNumber;
public BlurOptimized blur;
public BaseCollectibleItem[] items;
public void Start()
{
maxSlotNumber = 20;
quickAccessSlotNumber = 4;
blur = Camera.main.GetComponent<BlurOptimized>();
blur.enabled = isInvOpened;
for (int i = 0; i < quickAccessSlotNumber; i++)
{
InventorySlot tempSlot = new InventorySlot();
//tempSlot.quickAccess = true;
tempSlot.itemOld = items[i];
tempSlot.value = Random.Range(1,10);
slotList.Add(tempSlot);
}
}
public void Update()
{
if (Input.GetKeyDown("i")) //|| Input.GetButtonDown(openInventoryButton))
{
isQuickOpened = isInvOpened;
isInvOpened = !isInvOpened;
blur.enabled = isInvOpened;
if (isInvOpened)
{
Time.timeScale = 0;
}
else
{
Time.timeScale = 1;
}
}
//if (Input.GetKey("q") && !isInvOpened)//|| Input.GetButtonDown(openInventoryButton))
//{
// isQuickOpened = true;
//}
//else
//{
// isQuickOpened = false;
//}
}
public ActionResult AddItem(BaseCollectibleItem objectToAdd)
{
bool needNewItemSlot = true;
foreach (InventorySlot slot in slotList)
{
//if (!slot.quickAccess)
//{
if (slot.itemOld.type == objectToAdd.type)
{
if (!slot.isFull)
{
needNewItemSlot = false;
slot.value += 1;
Debug.Log("PICKED UP OBJECT!");
return ActionResult.Success;
}
}
//}
}
if (needNewItemSlot)
{
int slotCounter = 0;
if (slotList.Count == maxSlotNumber)
{
Debug.Log("INVENTORY FULL!");
return ActionResult.InventoryFull;
}
foreach (InventorySlot slot1 in slotList)
{
//if (!slot1.quickAccess)
//{
if (slot1.itemOld.type == objectToAdd.type)
{
slotCounter += 1;
}
//}
}
if (slotCounter < objectToAdd.maxStackNumber)
{
if (slotList.Count - 1 < maxSlotNumber)
{
InventorySlot tempSlot = new InventorySlot();
tempSlot.value = 1;
tempSlot.itemOld = objectToAdd;
slotList.Add(tempSlot);
Debug.Log("NEW SLOT CREATED!");
return ActionResult.Success;
}
}
else
{
Debug.Log("MAX STACK NUMBER REACHED!");
return ActionResult.MaxStack;
}
}
return ActionResult.Fail;
}
public ActionResult AddItem(JunkCollectibleItem objectToAdd)
{
currentJunks += objectToAdd.junkValue;
return ActionResult.Success;
}
//DA RICONTROLLARE, MODIFICATO IL 12/06/2017
public ActionResult RemoveItem(BaseCollectibleItem.Type itemToRemove, int quantity)
{
foreach (InventorySlot slot in slotList)
{
if (slot.itemOld.type == itemToRemove)
{
if (slot.value >= quantity)
{
//if (quantity < slot.currentSlotValue) //Controllo ridondante
//{
slot.value -= quantity;
Debug.Log(slot.value);
if (slot.value == 0)
{
slotList.Remove(slot);
}
return ActionResult.Success;
//}
}
else
{
Debug.Log("You don't have enought items.");
return ActionResult.NotEnoughtItems;
}
}
}
return ActionResult.NoItemFound;
}
[HideInInspector]
public enum ActionResult
{
Fail = -1,
Success = 0,
NotEnoughtItems = 1,
MaxStack = 2,
InventoryFull = 3,
NoItemFound = 4,
}
private void OnGUI()
{
if (isQuickOpened)
{
ArrangeRapidAccessSlots();
}
}
public void ArrangeRapidAccessSlots()
{
int numberOfPoints = 0;
int circleRadius = 55;
float angleIncrement = 0;
numberOfPoints = quickAccessSlotNumber;
angleIncrement = 360 / numberOfPoints;
for (int i = 0; i < numberOfPoints; i++)
{
Vector2 p = new Vector2();
p.x = (circleRadius * Mathf.Cos((angleIncrement * i) * (Mathf.PI / 180)));
p.y = (circleRadius * Mathf.Sin((angleIncrement * i) * (Mathf.PI / 180)));
GUI.depth = 2;
GUI.Label(new Rect((150 + p.x) - (20 / 2), (((Screen.height - 150) + p.y) - (20 / 2)), 20, 20), quickSlotTexture);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BitDiffer.Common.Configuration;
using BitDiffer.Common.Model;
using BitDiffer.Common.Misc;
using BitDiffer.Core;
using BitDiffer.Common.Interfaces;
namespace BitDiffer.Tests
{
[TestClass]
public class Filters
{
[TestMethod]
public void Filters_ChangedOnly_Removed()
{
ComparisonFilter filter = new ComparisonFilter();
filter.ChangedItemsOnly = true;
DoCompareAndVerifyRemoved(filter, "BitDiffer.Tests.Subject", "BasicClass", "_privateField");
}
[TestMethod]
public void Filters_ChangedOnly_StillPresent()
{
ComparisonFilter filter = new ComparisonFilter();
filter.ChangedItemsOnly = true;
DoCompareAndVerifyStillPresent(filter, "BitDiffer.Tests.Subject", "BasicClass", "PublicEventDeclChange");
}
[TestMethod]
public void Filters_ChangedOnly_Nested_Child()
{
ComparisonFilter filter = new ComparisonFilter();
filter.ChangedItemsOnly = true;
DoCompareAndVerifyStillPresent(filter, "BitDiffer.Tests.Subject", "ParentClassPublicGrandchildChanges", "NestedPublicClass");
}
[TestMethod]
public void Filters_ChangedOnly_Nested_Parent()
{
ComparisonFilter filter = new ComparisonFilter();
filter.ChangedItemsOnly = true;
DoCompareAndVerifyRemoved(filter, "BitDiffer.Tests.Subject", "ParentClass");
}
[TestMethod]
public void Filters_ChangedOnly_ParentRemovedByChild()
{
ComparisonFilter filter = new ComparisonFilter();
filter.ChangedItemsOnly = true;
filter.IgnoreAssemblyAttributeChanges = true;
DoCompareAndVerifyRemoved(filter, "Attributes");
}
[TestMethod]
public void Filters_ChangedOnly_ParentChangedByChild()
{
ComparisonFilter filter = new ComparisonFilter();
filter.IgnoreAssemblyAttributeChanges = true;
DoCompareAndVerifyChange(filter, ChangeType.MembersChangedNonBreaking, ChangeType.None, "Attributes");
}
[TestMethod]
public void Filters_PublicOnly_Removed()
{
ComparisonFilter filter = new ComparisonFilter();
filter.IncludeProtected = false;
filter.IncludeInternal = false;
filter.IncludePrivate = false;
DoCompareAndVerifyRemoved(filter, "BitDiffer.Tests.Subject", "BasicClass", "_privateField");
}
[TestMethod]
public void Filters_PublicOnly_StillPresent()
{
ComparisonFilter filter = new ComparisonFilter();
filter.IncludeProtected = false;
filter.IncludeInternal = false;
filter.IncludePrivate = false;
DoCompareAndVerifyStillPresent(filter, "BitDiffer.Tests.Subject", "BasicClass", "_publicField");
}
[TestMethod]
public void Filters_PublicOrProt_Removed()
{
ComparisonFilter filter = new ComparisonFilter();
filter.IncludeInternal = false;
filter.IncludePrivate = false;
DoCompareAndVerifyRemoved(filter, "BitDiffer.Tests.Subject", "BasicClass", "_privateField");
}
[TestMethod]
public void Filters_PublicOrProt_StillPresent()
{
ComparisonFilter filter = new ComparisonFilter();
filter.IncludeInternal = false;
filter.IncludePrivate = false;
DoCompareAndVerifyStillPresent(filter, "BitDiffer.Tests.Subject", "BasicClass", "_publicField");
}
[TestMethod]
public void Filters_PublicOrProt_ProtStillPresent()
{
ComparisonFilter filter = new ComparisonFilter();
filter.IncludeInternal = false;
filter.IncludePrivate = false;
DoCompareAndVerifyStillPresent(filter, "BitDiffer.Tests.Subject", "BasicClass", "_protectedField");
}
[TestMethod]
public void Filters_MethodImpl()
{
ComparisonFilter filter = new ComparisonFilter();
filter.CompareMethodImplementations = false;
DoCompareAndVerifyChange(filter, ChangeType.ImplementationChanged, ChangeType.None, "BitDiffer.Tests.Subject", "BasicClass", "MethodBodyChanges");
}
[TestMethod]
public void Filters_IgnoreAssemAttributes()
{
ComparisonFilter filter = new ComparisonFilter();
filter.IgnoreAssemblyAttributeChanges = true;
DoCompareAndVerifyChange(filter, ChangeType.DeclarationChangedNonBreaking, ChangeType.None, "Attributes", "System.Reflection.AssemblyDescriptionAttribute");
}
[TestMethod]
public void Filters_IgnoreAssemAttributes_OtherAttersNotAffected()
{
ComparisonFilter filter = new ComparisonFilter();
filter.IgnoreAssemblyAttributeChanges = true;
DoCompareAndVerifyChange(filter, ChangeType.DeclarationChangedNonBreaking, ChangeType.DeclarationChangedNonBreaking, "BitDiffer.Tests.Subject", "BasicClass", "MethodAttributeChanges", "System.ComponentModel.DescriptionAttribute");
}
[TestMethod]
public void Filters_TextFilter_StillPresent()
{
ComparisonFilter filter = new ComparisonFilter();
filter.TextFilter = "_privateField";
DoCompareAndVerifyStillPresent(filter, "BitDiffer.Tests.Subject", "BasicClass", "_privateField");
}
[TestMethod]
public void Filters_TextFilter_Removed_Child()
{
ComparisonFilter filter = new ComparisonFilter();
filter.TextFilter = "Basic"; // This will keep basic class itself but remove it's children
DoCompareAndVerifyRemoved(filter, "BitDiffer.Tests.Subject", "BasicClass", "_privateField");
}
[TestMethod]
public void Filters_TextFilter_Removed_Sibling()
{
ComparisonFilter filter = new ComparisonFilter();
filter.TextFilter = "_privateField";
DoCompareAndVerifyRemoved(filter, "BitDiffer.Tests.Subject", "BasicClass", "_publicField");
}
[TestMethod]
public void Filters_TextFilter_NoMatches()
{
ComparisonFilter filter = new ComparisonFilter();
filter.TextFilter = "bogus";
AssemblyComparison ac = DoCompare(ComparisonFilter.Default);
Assert.AreEqual(true, ac.Groups[0].Assemblies[1].FilterChildren<ICanAlign>().GetEnumerator().MoveNext());
ac.Recompare(filter);
Assert.AreEqual(false, ac.Groups[0].Assemblies[1].FilterChildren<ICanAlign>().GetEnumerator().MoveNext());
}
private static void DoCompareAndVerifyChange(ComparisonFilter filter, ChangeType withoutFilter, ChangeType withFilter, params string[] names)
{
AssemblyComparison ac = DoCompare(ComparisonFilter.Default);
Assert.AreEqual(withoutFilter, FindInAssembly(ac, names).Change);
ac.Recompare(filter);
Assert.AreEqual(withFilter, FindInAssembly(ac, names).Change);
}
private static void DoCompareAndVerifyRemoved(ComparisonFilter filter, params string[] names)
{
AssemblyComparison ac = DoCompare(ComparisonFilter.Default);
Assert.AreEqual(Status.Present, FindInAssembly(ac, names).Status);
ac.Recompare(filter);
Assert.IsNull(FindInAssembly(ac, names));
}
private static void DoCompareAndVerifyStillPresent(ComparisonFilter filter, params string[] names)
{
AssemblyComparison ac = DoCompare(ComparisonFilter.Default);
Assert.AreEqual(Status.Present, FindInAssembly(ac, names).Status);
ac.Recompare(filter);
Assert.AreEqual(Status.Present, FindInAssembly(ac, names).Status);
}
private static AssemblyComparison DoCompare(ComparisonFilter filter)
{
AssemblyComparison ac = new AssemblyComparer().CompareAssemblyFiles(DiffConfig.Default, filter, Subjects.One, Subjects.Two);
Assert.AreEqual(1, ac.Groups.Count);
Assert.AreEqual(2, ac.Groups[0].Assemblies.Count);
return ac;
}
private static ICanCompare FindInAssembly(AssemblyComparison ac, params string[] names)
{
ICanCompare current = ac.Groups[0].Assemblies[1];
for (int i = 0; i < names.Length; i++)
{
ICanCompare child = (ICanCompare)FindChildByName(current, names[i]);
if ((i < names.Length - 1) && (child == null))
{
Assert.Inconclusive("Did not find child named {0} in {1}.", names[i], current.Name);
}
current = child;
}
return current;
}
private static ICanAlign FindChildByName(ICanAlign current, string name)
{
IEnumerable<ICanAlign> children = current.FilterChildren<ICanAlign>();
foreach (ICanAlign child in children)
{
if (child.Name == name)
{
return child;
}
}
return null;
}
}
}
| |
/****************************************************************************/
/* FileUtilities.cs */
/****************************************************************************/
/* Copyright (c) Microsoft Corporation. All rights reserved. */
/* AUTHOR: Vance Morrison
* Date : 10/20/2007 */
/****************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace Microsoft.Diagnostics.Utilities
{
/******************************************************************************/
/// <summary>
/// General purpose utilities dealing with archiveFile system files.
/// </summary>
#if UTILITIES_PUBLIC
public
#endif
static class FileUtilities
{
/// <summary>
/// GetLines works much like File.ReadAllLines, however instead of returning a
/// array of lines, it returns a IEnumerable so that the archiveFile is not read all
/// at once. This allows 'foreach' syntax to be used on very large files.
///
/// Suggested Usage
///
/// foreach(string lineNumber in FileUtilities.GetLines("largeFile.txt")){
/// Console.WriteLine(lineNumber);
/// }
/// </summary>
/// <param variable="fileName">The base directory to enumerate.</param>
/// <returns>The enumerator for all lines in the archiveFile.</returns>
public static IEnumerable<string> ReadAllLines(string fileName)
{
StreamReader stream = File.OpenText(fileName);
while (!stream.EndOfStream)
{
yield return stream.ReadLine();
}
stream.Dispose();
}
/// <summary>
/// Given archiveFile specifications possibly with wildcards in them
/// Returns an enumerator that returns each expanded archiveFile name in turn.
///
/// If searchOpt is AllDirectories it does a recursive match.
/// </summary>
public static IEnumerable<string> ExpandWildcards(string[] fileSpecifications, SearchOption searchOpt = SearchOption.TopDirectoryOnly)
{
foreach (string fileSpec in fileSpecifications)
{
string dir = Path.GetDirectoryName(fileSpec);
if (dir.Length == 0)
{
dir = ".";
}
string file = Path.GetFileName(fileSpec);
foreach (string fileName in DirectoryUtilities.GetFiles(dir, file, searchOpt))
{
yield return fileName;
}
}
}
/// <summary>
/// Delete works much like File.Delete, except that it will succeed if the
/// archiveFile does not exist, and will rename the archiveFile so that even if the archiveFile
/// is locked the original archiveFile variable will be made available.
///
/// It renames the archiveFile with a '[num].deleting'. These files might be left
/// behind.
///
/// It returns true if it was completely successful. If there is a *.deleting
/// archiveFile left behind, it returns false.
/// </summary>
/// <param variable="fileName">The variable of the archiveFile to delete</param>
public static bool ForceDelete(string fileName)
{
if (Directory.Exists(fileName))
{
return DirectoryUtilities.Clean(fileName) != 0;
}
if (!File.Exists(fileName))
{
return true;
}
// First move the archiveFile out of the way, so that even if it is locked
// The original archiveFile is still gone.
string fileToDelete = fileName;
bool tryToDeleteOtherFiles = true;
if (!fileToDelete.EndsWith(".deleting", StringComparison.OrdinalIgnoreCase))
{
tryToDeleteOtherFiles = false;
int i = 0;
for (i = 0; ; i++)
{
fileToDelete = fileName + "." + i.ToString() + ".deleting";
if (!File.Exists(fileToDelete))
{
break;
}
tryToDeleteOtherFiles = true;
}
try
{
File.Move(fileName, fileToDelete);
}
catch (Exception)
{
fileToDelete = fileName;
}
}
bool ret = false;
try
{
ret = TryDelete(fileToDelete);
if (tryToDeleteOtherFiles)
{
// delete any old *.deleting files that may have been left around
string deletePattern = Path.GetFileName(fileName) + @".*.deleting";
foreach (string deleteingFile in Directory.GetFiles(Path.GetDirectoryName(fileName), deletePattern))
{
TryDelete(deleteingFile);
}
}
} catch { };
return ret;
}
/// <summary>
/// Try to delete 'fileName' catching any exception. Returns true if successful. It will delete read-only files.
/// </summary>
public static bool TryDelete(string fileName)
{
bool ret = false;
if (!File.Exists(fileName))
{
return true;
}
try
{
FileAttributes attribs = File.GetAttributes(fileName);
if ((attribs & FileAttributes.ReadOnly) != 0)
{
attribs &= ~FileAttributes.ReadOnly;
File.SetAttributes(fileName, attribs);
}
File.Delete(fileName);
ret = true;
}
catch (Exception) { }
return ret;
}
/// <summary>
/// SafeCopy sourceFile to destinationFile. If the destination exists
/// used ForceDelete to get rid of it first.
/// </summary>
public static void ForceCopy(string sourceFile, string destinationFile)
{
ForceDelete(destinationFile); // will return immediate if the destination does not exist.
File.Copy(sourceFile, destinationFile);
}
/// <summary>
/// Moves sourceFile to destinationFile. If the destination exists
/// used ForceDelete to get rid of it first.
/// </summary>
public static void ForceMove(string sourceFile, string destinationFile)
{
ForceDelete(destinationFile); // will return immediate if the destination does not exist.
File.Move(sourceFile, destinationFile);
}
/// <summary>
/// Returns true if the two file have exactly the same content (as a stream of bytes).
/// </summary>
public static bool Equals(string fileName1, string fileName2)
{
byte[] buffer1 = new byte[8192];
byte[] buffer2 = new byte[8192];
using (FileStream file1 = File.Open(fileName1, FileMode.Open, FileAccess.Read))
{
using (FileStream file2 = File.Open(fileName2, FileMode.Open, FileAccess.Read))
{
int count1 = file1.Read(buffer1, 0, buffer1.Length);
int count2 = file2.Read(buffer2, 0, buffer2.Length);
if (count1 != count2)
{
return false;
}
for (int i = 0; i < count1; i++)
{
if (buffer1[i] != buffer2[i])
{
return false;
}
}
}
}
return true;
}
}
/// <summary>
/// Utilities associated with file name paths.
/// </summary>
#if UTILITIES_PUBLIC
public
#endif
static class PathUtil
{
/// <summary>
/// Given a path and a superdirectory path relativeToDirectory compute the relative path (the path from) relativeToDirectory
/// </summary>
public static string PathRelativeTo(string path, string relativeToDirectory)
{
Debug.Assert(!relativeToDirectory.EndsWith("\\"));
string fullPath = Path.GetFullPath(path);
string fullCurrentDirectory = Path.GetFullPath(relativeToDirectory);
int commonToSlashIndex = -1;
for (int i = 0; i < fullPath.Length; i++)
{
char cFullPath = fullPath[i];
if (i >= fullCurrentDirectory.Length)
{
if (cFullPath == '\\')
{
commonToSlashIndex = i;
}
break;
}
char cCurrentDirectory = fullCurrentDirectory[i];
if (cCurrentDirectory != cFullPath)
{
if (char.IsLower(cCurrentDirectory))
{
cCurrentDirectory = (char)(cCurrentDirectory - (char)('a' - 'A'));
}
if (char.IsLower(cFullPath))
{
cFullPath = (char)(cFullPath - (char)('a' - 'A'));
}
if (cCurrentDirectory != cFullPath)
{
break;
}
}
if (cCurrentDirectory == '\\')
{
commonToSlashIndex = i;
}
}
// There is no common prefix between the two paths, we give up.
if (commonToSlashIndex < 0)
{
return path;
}
string returnVal = "";
int nextSlash = commonToSlashIndex;
for (; ; )
{
if (nextSlash >= fullCurrentDirectory.Length)
{
break;
}
if (returnVal.Length > 0)
{
returnVal += "\\";
}
returnVal += @"..";
if (nextSlash + 1 == fullCurrentDirectory.Length)
{
break;
}
nextSlash = fullCurrentDirectory.IndexOf('\\', nextSlash + 1);
if (nextSlash < 0)
{
break;
}
}
string rest = fullPath.Substring(commonToSlashIndex + 1);
returnVal = Path.Combine(returnVal, rest);
Debug.Assert(string.Compare(Path.GetFullPath(Path.Combine(relativeToDirectory, returnVal)), fullPath, StringComparison.OrdinalIgnoreCase) == 0);
return returnVal;
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QLNet;
using QuantConnect.Data;
using QuantConnect.Data.Auxiliary;
using QuantConnect.Data.Market;
using QuantConnect.Python;
using QuantConnect.Orders.Fees;
using QuantConnect.Securities;
using QuantConnect.Securities.Equity;
using QuantConnect.Util;
namespace QuantConnect.Orders.Fills
{
/// <summary>
/// Provides a base class for all fill models
/// </summary>
public class EquityFillModel : IFillModel
{
/// <summary>
/// The parameters instance to be used by the different XxxxFill() implementations
/// </summary>
protected FillModelParameters Parameters { get; set; }
/// <summary>
/// This is required due to a limitation in PythonNet to resolved overriden methods.
/// When Python calls a C# method that calls a method that's overriden in python it won't
/// run the python implementation unless the call is performed through python too.
/// </summary>
protected FillModelPythonWrapper PythonWrapper;
/// <summary>
/// Used to set the <see cref="FillModelPythonWrapper"/> instance if any
/// </summary>
public void SetPythonWrapper(FillModelPythonWrapper pythonWrapper)
{
PythonWrapper = pythonWrapper;
}
/// <summary>
/// Return an order event with the fill details
/// </summary>
/// <param name="parameters">A <see cref="FillModelParameters"/> object containing the security and order</param>
/// <returns>Order fill information detailing the average price and quantity filled.</returns>
public virtual Fill Fill(FillModelParameters parameters)
{
// Important: setting the parameters is required because it is
// consumed by the different XxxxFill() implementations
Parameters = parameters;
var order = parameters.Order;
OrderEvent orderEvent;
switch (order.Type)
{
case OrderType.Market:
orderEvent = PythonWrapper != null
? PythonWrapper.MarketFill(parameters.Security, parameters.Order as MarketOrder)
: MarketFill(parameters.Security, parameters.Order as MarketOrder);
break;
case OrderType.Limit:
orderEvent = PythonWrapper != null
? PythonWrapper.LimitFill(parameters.Security, parameters.Order as LimitOrder)
: LimitFill(parameters.Security, parameters.Order as LimitOrder);
break;
case OrderType.LimitIfTouched:
orderEvent = PythonWrapper != null
? PythonWrapper.LimitIfTouchedFill(parameters.Security, parameters.Order as LimitIfTouchedOrder)
: LimitIfTouchedFill(parameters.Security, parameters.Order as LimitIfTouchedOrder);
break;
case OrderType.StopMarket:
orderEvent = PythonWrapper != null
? PythonWrapper.StopMarketFill(parameters.Security, parameters.Order as StopMarketOrder)
: StopMarketFill(parameters.Security, parameters.Order as StopMarketOrder);
break;
case OrderType.StopLimit:
orderEvent = PythonWrapper != null
? PythonWrapper.StopLimitFill(parameters.Security, parameters.Order as StopLimitOrder)
: StopLimitFill(parameters.Security, parameters.Order as StopLimitOrder);
break;
case OrderType.MarketOnOpen:
orderEvent = PythonWrapper != null
? PythonWrapper.MarketOnOpenFill(parameters.Security, parameters.Order as MarketOnOpenOrder)
: MarketOnOpenFill(parameters.Security, parameters.Order as MarketOnOpenOrder);
break;
case OrderType.MarketOnClose:
orderEvent = PythonWrapper != null
? PythonWrapper.MarketOnCloseFill(parameters.Security, parameters.Order as MarketOnCloseOrder)
: MarketOnCloseFill(parameters.Security, parameters.Order as MarketOnCloseOrder);
break;
default:
throw new ArgumentOutOfRangeException();
}
return new Fill(orderEvent);
}
/// <summary>
/// Default limit if touched fill model implementation in base class security.
/// </summary>
/// <param name="asset">Security asset we're filling</param>
/// <param name="order">Order packet to model</param>
/// <returns>Order fill information detailing the average price and quantity filled.</returns>
/// <remarks>
/// There is no good way to model limit orders with OHLC because we never know whether the market has
/// gapped past our fill price. We have to make the assumption of a fluid, high volume market.
///
/// With Limit if Touched orders, whether or not a trigger is surpassed is determined by the high (low)
/// of the previous tradebar when making a sell (buy) request. Following the behaviour of
/// <see cref="StopLimitFill"/>, current quote information is used when determining fill parameters
/// (e.g., price, quantity) as the tradebar containing the incoming data is not yet consolidated.
/// This conservative approach, however, can lead to trades not occuring as would be expected when
/// compared to future consolidated data.
/// </remarks>
public virtual OrderEvent LimitIfTouchedFill(Security asset, LimitIfTouchedOrder order)
{
//Default order event to return.
var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
var fill = new OrderEvent(order, utcTime, OrderFee.Zero);
//If its cancelled don't need anymore checks:
if (order.Status == OrderStatus.Canceled) return fill;
// Fill only if open or extended
if (!IsExchangeOpen(asset,
Parameters.ConfigProvider
.GetSubscriptionDataConfigs(asset.Symbol)
.IsExtendedMarketHours()))
{
return fill;
}
// Get the range of prices in the last bar:
var tradeHigh = 0m;
var tradeLow = 0m;
var endTimeUtc = DateTime.MinValue;
var subscribedTypes = GetSubscribedTypes(asset);
if (subscribedTypes.Contains(typeof(Tick)))
{
var trade = asset.Cache.GetAll<Tick>().LastOrDefault(x => x.TickType == TickType.Trade && x.Price > 0);
if (trade != null)
{
tradeHigh = trade.Price;
tradeLow = trade.Price;
endTimeUtc = trade.EndTime.ConvertToUtc(asset.Exchange.TimeZone);
}
}
else if (subscribedTypes.Contains(typeof(TradeBar)))
{
var tradeBar = asset.Cache.GetData<TradeBar>();
if (tradeBar != null)
{
tradeHigh = tradeBar.High;
tradeLow = tradeBar.Low;
endTimeUtc = tradeBar.EndTime.ConvertToUtc(asset.Exchange.TimeZone);
}
}
// do not fill on stale data
if (endTimeUtc <= order.Time) return fill;
//Check if the limit if touched order was filled:
switch (order.Direction)
{
case OrderDirection.Buy:
//-> 1.2 Buy: If Price below Trigger, Buy:
if (tradeLow <= order.TriggerPrice || order.TriggerTouched)
{
order.TriggerTouched = true;
var askCurrent = GetBestEffortAskPrice(asset, order.Time, out var fillMessage);
if (askCurrent <= order.LimitPrice)
{
fill.Status = OrderStatus.Filled;
fill.FillPrice = Math.Min(askCurrent, order.LimitPrice);
fill.FillQuantity = order.Quantity;
fill.Message = fillMessage;
}
}
break;
case OrderDirection.Sell:
//-> 1.2 Sell: If Price above Trigger, Sell:
if (tradeHigh >= order.TriggerPrice || order.TriggerTouched)
{
order.TriggerTouched = true;
var bidCurrent = GetBestEffortBidPrice(asset, order.Time, out var fillMessage);
if (bidCurrent >= order.LimitPrice)
{
fill.Status = OrderStatus.Filled;
fill.FillPrice = Math.Max(bidCurrent, order.LimitPrice);
fill.FillQuantity = order.Quantity;
fill.Message = fillMessage;
}
}
break;
}
return fill;
}
/// <summary>
/// Default market fill model for the base security class. Fills at the last traded price.
/// </summary>
/// <param name="asset">Security asset we're filling</param>
/// <param name="order">Order packet to model</param>
/// <returns>Order fill information detailing the average price and quantity filled.</returns>
public virtual OrderEvent MarketFill(Security asset, MarketOrder order)
{
//Default order event to return.
var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
var fill = new OrderEvent(order, utcTime, OrderFee.Zero);
if (order.Status == OrderStatus.Canceled) return fill;
// Make sure the exchange is open/normal market hours before filling
if (!IsExchangeOpen(asset, false)) return fill;
// Calculate the model slippage: e.g. 0.01c
var slip = asset.SlippageModel.GetSlippageApproximation(asset, order);
var fillMessage = string.Empty;
switch (order.Direction)
{
case OrderDirection.Buy:
//Order [fill]price for a buy market order model is the current security ask price
fill.FillPrice = GetBestEffortAskPrice(asset, order.Time, out fillMessage) + slip;
break;
case OrderDirection.Sell:
//Order [fill]price for a buy market order model is the current security bid price
fill.FillPrice = GetBestEffortBidPrice(asset, order.Time, out fillMessage) - slip;
break;
}
// assume the order completely filled
fill.FillQuantity = order.Quantity;
fill.Message = fillMessage;
fill.Status = OrderStatus.Filled;
return fill;
}
/// <summary>
/// Default stop fill model implementation in base class security. (Stop Market Order Type)
/// </summary>
/// <param name="asset">Security asset we're filling</param>
/// <param name="order">Order packet to model</param>
/// <returns>Order fill information detailing the average price and quantity filled.</returns>
/// <seealso cref="MarketFill(Security, MarketOrder)"/>
public virtual OrderEvent StopMarketFill(Security asset, StopMarketOrder order)
{
//Default order event to return.
var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
var fill = new OrderEvent(order, utcTime, OrderFee.Zero);
//If its cancelled don't need anymore checks:
if (order.Status == OrderStatus.Canceled) return fill;
// make sure the exchange is open/normal market hours before filling
if (!IsExchangeOpen(asset, false)) return fill;
//Get the range of prices in the last bar:
var prices = GetPricesCheckingPythonWrapper(asset, order.Direction);
var pricesEndTime = prices.EndTime.ConvertToUtc(asset.Exchange.TimeZone);
// do not fill on stale data
if (pricesEndTime <= order.Time) return fill;
//Calculate the model slippage: e.g. 0.01c
var slip = asset.SlippageModel.GetSlippageApproximation(asset, order);
//Check if the Stop Order was filled: opposite to a limit order
switch (order.Direction)
{
case OrderDirection.Sell:
//-> 1.1 Sell Stop: If Price below setpoint, Sell:
if (prices.Low < order.StopPrice)
{
fill.Status = OrderStatus.Filled;
// Assuming worse case scenario fill - fill at lowest of the stop & asset price.
fill.FillPrice = Math.Min(order.StopPrice, prices.Current - slip);
// assume the order completely filled
fill.FillQuantity = order.Quantity;
}
break;
case OrderDirection.Buy:
//-> 1.2 Buy Stop: If Price Above Setpoint, Buy:
if (prices.High > order.StopPrice)
{
fill.Status = OrderStatus.Filled;
// Assuming worse case scenario fill - fill at highest of the stop & asset price.
fill.FillPrice = Math.Max(order.StopPrice, prices.Current + slip);
// assume the order completely filled
fill.FillQuantity = order.Quantity;
}
break;
}
return fill;
}
/// <summary>
/// Default stop limit fill model implementation in base class security. (Stop Limit Order Type)
/// </summary>
/// <param name="asset">Security asset we're filling</param>
/// <param name="order">Order packet to model</param>
/// <returns>Order fill information detailing the average price and quantity filled.</returns>
/// <seealso cref="StopMarketFill(Security, StopMarketOrder)"/>
/// <remarks>
/// There is no good way to model limit orders with OHLC because we never know whether the market has
/// gapped past our fill price. We have to make the assumption of a fluid, high volume market.
///
/// Stop limit orders we also can't be sure of the order of the H - L values for the limit fill. The assumption
/// was made the limit fill will be done with closing price of the bar after the stop has been triggered..
/// </remarks>
public virtual OrderEvent StopLimitFill(Security asset, StopLimitOrder order)
{
//Default order event to return.
var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
var fill = new OrderEvent(order, utcTime, OrderFee.Zero);
//If its cancelled don't need anymore checks:
if (order.Status == OrderStatus.Canceled) return fill;
// make sure the exchange is open before filling -- allow pre/post market fills to occur
if (!IsExchangeOpen(
asset,
Parameters.ConfigProvider
.GetSubscriptionDataConfigs(asset.Symbol)
.IsExtendedMarketHours()))
{
return fill;
}
//Get the range of prices in the last bar:
var prices = GetPricesCheckingPythonWrapper(asset, order.Direction);
var pricesEndTime = prices.EndTime.ConvertToUtc(asset.Exchange.TimeZone);
// do not fill on stale data
if (pricesEndTime <= order.Time) return fill;
//Check if the Stop Order was filled: opposite to a limit order
switch (order.Direction)
{
case OrderDirection.Buy:
//-> 1.2 Buy Stop: If Price Above Setpoint, Buy:
if (prices.High > order.StopPrice || order.StopTriggered)
{
order.StopTriggered = true;
// Fill the limit order, using closing price of bar:
// Note > Can't use minimum price, because no way to be sure minimum wasn't before the stop triggered.
if (prices.Current < order.LimitPrice)
{
fill.Status = OrderStatus.Filled;
fill.FillPrice = Math.Min(prices.High, order.LimitPrice);
// assume the order completely filled
fill.FillQuantity = order.Quantity;
}
}
break;
case OrderDirection.Sell:
//-> 1.1 Sell Stop: If Price below setpoint, Sell:
if (prices.Low < order.StopPrice || order.StopTriggered)
{
order.StopTriggered = true;
// Fill the limit order, using minimum price of the bar
// Note > Can't use minimum price, because no way to be sure minimum wasn't before the stop triggered.
if (prices.Current > order.LimitPrice)
{
fill.Status = OrderStatus.Filled;
fill.FillPrice = Math.Max(prices.Low, order.LimitPrice);
// assume the order completely filled
fill.FillQuantity = order.Quantity;
}
}
break;
}
return fill;
}
/// <summary>
/// Default limit order fill model in the base security class.
/// </summary>
/// <param name="asset">Security asset we're filling</param>
/// <param name="order">Order packet to model</param>
/// <returns>Order fill information detailing the average price and quantity filled.</returns>
/// <seealso cref="StopMarketFill(Security, StopMarketOrder)"/>
/// <seealso cref="MarketFill(Security, MarketOrder)"/>
public virtual OrderEvent LimitFill(Security asset, LimitOrder order)
{
//Initialise;
var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
var fill = new OrderEvent(order, utcTime, OrderFee.Zero);
//If its cancelled don't need anymore checks:
if (order.Status == OrderStatus.Canceled) return fill;
// make sure the exchange is open before filling -- allow pre/post market fills to occur
if (!IsExchangeOpen(asset,
Parameters.ConfigProvider
.GetSubscriptionDataConfigs(asset.Symbol)
.IsExtendedMarketHours()))
{
return fill;
}
//Get the range of prices in the last bar:
var prices = GetPricesCheckingPythonWrapper(asset, order.Direction);
var pricesEndTime = prices.EndTime.ConvertToUtc(asset.Exchange.TimeZone);
// do not fill on stale data
if (pricesEndTime <= order.Time) return fill;
//-> Valid Live/Model Order:
switch (order.Direction)
{
case OrderDirection.Buy:
//Buy limit seeks lowest price
if (prices.Low < order.LimitPrice)
{
//Set order fill:
fill.Status = OrderStatus.Filled;
// fill at the worse price this bar or the limit price, this allows far out of the money limits
// to be executed properly
fill.FillPrice = Math.Min(prices.High, order.LimitPrice);
// assume the order completely filled
fill.FillQuantity = order.Quantity;
}
break;
case OrderDirection.Sell:
//Sell limit seeks highest price possible
if (prices.High > order.LimitPrice)
{
fill.Status = OrderStatus.Filled;
// fill at the worse price this bar or the limit price, this allows far out of the money limits
// to be executed properly
fill.FillPrice = Math.Max(prices.Low, order.LimitPrice);
// assume the order completely filled
fill.FillQuantity = order.Quantity;
}
break;
}
return fill;
}
/// <summary>
/// Market on Open Fill Model. Return an order event with the fill details
/// </summary>
/// <param name="asset">Asset we're trading with this order</param>
/// <param name="order">Order to be filled</param>
/// <returns>Order fill information detailing the average price and quantity filled.</returns>
public virtual OrderEvent MarketOnOpenFill(Security asset, MarketOnOpenOrder order)
{
var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
var fill = new OrderEvent(order, utcTime, OrderFee.Zero);
if (order.Status == OrderStatus.Canceled) return fill;
// MOO should never fill on the same bar or on stale data
// Imagine the case where we have a thinly traded equity, ASUR, and another liquid
// equity, say SPY, SPY gets data every minute but ASUR, if not on fill forward, maybe
// have large gaps, in which case the currentBar.EndTime will be in the past
// ASUR | | | [order] | | | | | | |
// SPY | | | | | | | | | | | | | | | | | | | |
var localOrderTime = order.Time.ConvertFromUtc(asset.Exchange.TimeZone);
var endTime = DateTime.MinValue;
var subscribedTypes = GetSubscribedTypes(asset);
if (subscribedTypes.Contains(typeof(Tick)))
{
var primaryExchange = (byte) ((Equity) asset).PrimaryExchange;
var officialOpen = (uint) (TradeConditionFlags.Regular | TradeConditionFlags.OfficialOpen);
var openingPrints = (uint) (TradeConditionFlags.Regular | TradeConditionFlags.OpeningPrints);
// Get the first valid (non-zero) tick of trade type from an open market
var trade = asset.Cache.GetAll<Tick>()
.Where(x => !string.IsNullOrWhiteSpace(x.SaleCondition))
.FirstOrDefault(x =>
x.TickType == TickType.Trade && x.Price > 0 && x.ExchangeCode == primaryExchange &&
(x.ParsedSaleCondition == officialOpen || x.ParsedSaleCondition == openingPrints) &&
asset.Exchange.DateTimeIsOpen(x.Time));
if (trade != null)
{
endTime = trade.EndTime;
fill.FillPrice = trade.Price;
}
}
else if (subscribedTypes.Contains(typeof(TradeBar)))
{
var tradeBar = asset.Cache.GetData<TradeBar>();
if (tradeBar != null)
{
// If the order was placed during the bar aggregation, we cannot use its open price
if (tradeBar.Time < localOrderTime) return fill;
// We need to verify whether the trade data is from the open market.
if (tradeBar.Period < Resolution.Hour.ToTimeSpan() && !asset.Exchange.DateTimeIsOpen(tradeBar.Time))
{
return fill;
}
endTime = tradeBar.EndTime;
fill.FillPrice = tradeBar.Open;
}
}
if (localOrderTime >= endTime) return fill;
// if the MOO was submitted during market the previous day, wait for a day to turn over
// The date of the order and the trade data end time cannot be the same.
// Note that the security local time can be ahead of the data end time.
if (asset.Exchange.DateTimeIsOpen(localOrderTime) && localOrderTime.Date == endTime.Date)
{
return fill;
}
// wait until market open
// make sure the exchange is open/normal market hours before filling
if (!IsExchangeOpen(asset, false)) return fill;
// assume the order completely filled
fill.FillQuantity = order.Quantity;
fill.Status = OrderStatus.Filled;
//Calculate the model slippage: e.g. 0.01c
var slip = asset.SlippageModel.GetSlippageApproximation(asset, order);
//Apply slippage
switch (order.Direction)
{
case OrderDirection.Buy:
fill.FillPrice += slip;
break;
case OrderDirection.Sell:
fill.FillPrice -= slip;
break;
}
return fill;
}
/// <summary>
/// Market on Close Fill Model. Return an order event with the fill details
/// </summary>
/// <param name="asset">Asset we're trading with this order</param>
/// <param name="order">Order to be filled</param>
/// <returns>Order fill information detailing the average price and quantity filled.</returns>
public virtual OrderEvent MarketOnCloseFill(Security asset, MarketOnCloseOrder order)
{
var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
var fill = new OrderEvent(order, utcTime, OrderFee.Zero);
if (order.Status == OrderStatus.Canceled) return fill;
var localOrderTime = order.Time.ConvertFromUtc(asset.Exchange.TimeZone);
var nextMarketClose = asset.Exchange.Hours.GetNextMarketClose(localOrderTime, false);
// wait until market closes after the order time
if (asset.LocalTime < nextMarketClose)
{
return fill;
}
// make sure the exchange is open/normal market hours before filling
if (!IsExchangeOpen(asset, false)) return fill;
fill.FillPrice = GetPricesCheckingPythonWrapper(asset, order.Direction).Close;
fill.Status = OrderStatus.Filled;
//Calculate the model slippage: e.g. 0.01c
var slip = asset.SlippageModel.GetSlippageApproximation(asset, order);
//Apply slippage
switch (order.Direction)
{
case OrderDirection.Buy:
fill.FillPrice += slip;
// assume the order completely filled
fill.FillQuantity = order.Quantity;
break;
case OrderDirection.Sell:
fill.FillPrice -= slip;
// assume the order completely filled
fill.FillQuantity = order.Quantity;
break;
}
return fill;
}
/// <summary>
/// Get data types the Security is subscribed to
/// </summary>
/// <param name="asset">Security which has subscribed data types</param>
private HashSet<Type> GetSubscribedTypes(Security asset)
{
var subscribedTypes = Parameters
.ConfigProvider
.GetSubscriptionDataConfigs(asset.Symbol)
.ToHashSet(x => x.Type);
if (subscribedTypes.Count == 0)
{
throw new InvalidOperationException($"Cannot perform fill for {asset.Symbol} because no data subscription were found.");
}
return subscribedTypes;
}
/// <summary>
/// Get current ask price for subscribed data
/// This method will try to get the most recent ask price data, so it will try to get tick quote first, then quote bar.
/// If no quote, tick or bar, is available (e.g. hourly data), use trade data with preference to tick data.
/// </summary>
/// <param name="asset">Security which has subscribed data types</param>
/// <param name="orderTime">Time the order was submitted</param>
/// <param name="message">Information about the best effort, whether prices are stale or need to use trade information</param>
private decimal GetBestEffortAskPrice(Security asset, DateTime orderTime, out string message)
{
message = string.Empty;
BaseData baseData = null;
var bestEffortAskPrice = 0m;
// Define the cut off time to get the best effort bid or ask and whether the price is stale
var localOrderTime = orderTime.ConvertFromUtc(asset.Exchange.TimeZone);
var cutOffTime = localOrderTime.Add(-Parameters.StalePriceTimeSpan);
var subscribedTypes = GetSubscribedTypes(asset);
List<Tick> ticks = null;
var isTickSubscribed = subscribedTypes.Contains(typeof(Tick));
if (isTickSubscribed)
{
ticks = asset.Cache.GetAll<Tick>().ToList();
var quote = ticks.LastOrDefault(x => x.TickType == TickType.Quote && x.AskPrice > 0);
if (quote != null)
{
if (quote.EndTime >= cutOffTime)
{
return quote.AskPrice;
}
baseData = quote;
bestEffortAskPrice = quote.AskPrice;
message = $"Warning: fill at stale price ({baseData.EndTime.ToStringInvariant()} {asset.Exchange.TimeZone}), using Quote Tick data.";
}
}
if (subscribedTypes.Contains(typeof(QuoteBar)))
{
var quoteBar = asset.Cache.GetData<QuoteBar>();
if (quoteBar != null && (baseData == null || quoteBar.EndTime > baseData.EndTime))
{
if (quoteBar.EndTime >= cutOffTime)
{
return quoteBar.Ask?.Close ?? quoteBar.Close;
}
baseData = quoteBar;
bestEffortAskPrice = quoteBar.Ask?.Close ?? quoteBar.Close;
message = $"Warning: fill at stale price ({baseData.EndTime.ToStringInvariant()} {asset.Exchange.TimeZone}), using QuoteBar data.";
}
}
if (isTickSubscribed)
{
var trade = ticks.LastOrDefault(x => x.TickType == TickType.Trade && x.Price > 0);
if (trade != null && (baseData == null || trade.EndTime > baseData.EndTime))
{
message = $"Warning: No quote information available at {trade.EndTime.ToStringInvariant()} {asset.Exchange.TimeZone}, order filled using Trade Tick data";
if (trade.EndTime >= cutOffTime)
{
return trade.Price;
}
baseData = trade;
bestEffortAskPrice = trade.Price;
}
}
if (subscribedTypes.Contains(typeof(TradeBar)))
{
var tradeBar = asset.Cache.GetData<TradeBar>();
if (tradeBar != null && (baseData == null || tradeBar.EndTime > baseData.EndTime))
{
message = $"Warning: No quote information available at {tradeBar.EndTime.ToStringInvariant()} {asset.Exchange.TimeZone}, order filled using TradeBar data";
if (tradeBar.EndTime >= cutOffTime)
{
return tradeBar.Close;
}
baseData = tradeBar;
bestEffortAskPrice = tradeBar.Close;
}
}
if (baseData != null)
{
return bestEffortAskPrice;
}
throw new InvalidOperationException($"Cannot get ask price to perform fill for {asset.Symbol} because no market data subscription were found.");
}
/// <summary>
/// Get current bid price for subscribed data
/// This method will try to get the most recent bid price data, so it will try to get tick quote first, then quote bar.
/// If no quote, tick or bar, is available (e.g. hourly data), use trade data with preference to tick data.
/// </summary>
/// <param name="asset">Security which has subscribed data types</param>
/// <param name="orderTime">Time the order was submitted</param>
/// <param name="message">Information about the best effort, whether prices are stale or need to use trade information</param>
private decimal GetBestEffortBidPrice(Security asset, DateTime orderTime, out string message)
{
message = string.Empty;
BaseData baseData = null;
var bestEffortBidPrice = 0m;
// Define the cut off time to get the best effort bid or ask and whether the price is stale
var localOrderTime = orderTime.ConvertFromUtc(asset.Exchange.TimeZone);
var cutOffTime = localOrderTime.Add(-Parameters.StalePriceTimeSpan);
var subscribedTypes = GetSubscribedTypes(asset);
List<Tick> ticks = null;
var isTickSubscribed = subscribedTypes.Contains(typeof(Tick));
if (isTickSubscribed)
{
ticks = asset.Cache.GetAll<Tick>().ToList();
var quote = ticks.LastOrDefault(x => x.TickType == TickType.Quote && x.BidPrice > 0);
if (quote != null)
{
if (quote.EndTime >= cutOffTime)
{
return quote.BidPrice;
}
baseData = quote;
bestEffortBidPrice = quote.BidPrice;
message = $"Warning: fill at stale price ({baseData.EndTime.ToStringInvariant()} {asset.Exchange.TimeZone}), using Quote Tick data.";
}
}
if (subscribedTypes.Contains(typeof(QuoteBar)))
{
var quoteBar = asset.Cache.GetData<QuoteBar>();
if (quoteBar != null && (baseData == null || quoteBar.EndTime > baseData.EndTime))
{
if (quoteBar.EndTime >= cutOffTime)
{
return quoteBar.Bid?.Close ?? quoteBar.Close;
}
baseData = quoteBar;
bestEffortBidPrice = quoteBar.Bid?.Close ?? quoteBar.Close;
message = $"Warning: fill at stale price ({baseData.EndTime.ToStringInvariant()} {asset.Exchange.TimeZone}), using QuoteBar data.";
}
}
if (isTickSubscribed)
{
var trade = ticks.LastOrDefault(x => x.TickType == TickType.Trade && x.Price > 0);
if (trade != null && (baseData == null || trade.EndTime > baseData.EndTime))
{
message = $"Warning: No quote information available at {trade.EndTime.ToStringInvariant()} {asset.Exchange.TimeZone}, order filled using Trade Tick data";
if (trade.EndTime >= cutOffTime)
{
return trade.Price;
}
baseData = trade;
bestEffortBidPrice = trade.Price;
}
}
if (subscribedTypes.Contains(typeof(TradeBar)))
{
var tradeBar = asset.Cache.GetData<TradeBar>();
if (tradeBar != null && (baseData == null || tradeBar.EndTime > baseData.EndTime))
{
message = $"Warning: No quote information available at {tradeBar.EndTime.ToStringInvariant()} {asset.Exchange.TimeZone}, order filled using TradeBar data";
if (tradeBar.EndTime >= cutOffTime)
{
return tradeBar.Close;
}
baseData = tradeBar;
bestEffortBidPrice = tradeBar.Close;
}
}
if (baseData != null)
{
return bestEffortBidPrice;
}
throw new InvalidOperationException($"Cannot get ask price to perform fill for {asset.Symbol} because no market data subscription were found.");
}
/// <summary>
/// This is required due to a limitation in PythonNet to resolved
/// overriden methods. <see cref="GetPrices"/>
/// </summary>
private Prices GetPricesCheckingPythonWrapper(Security asset, OrderDirection direction)
{
if (PythonWrapper != null)
{
var prices = PythonWrapper.GetPricesInternal(asset, direction);
return new Prices(prices.EndTime, prices.Current, prices.Open, prices.High, prices.Low, prices.Close);
}
return GetPrices(asset, direction);
}
/// <summary>
/// Get the minimum and maximum price for this security in the last bar:
/// </summary>
/// <param name="asset">Security asset we're checking</param>
/// <param name="direction">The order direction, decides whether to pick bid or ask</param>
protected virtual Prices GetPrices(Security asset, OrderDirection direction)
{
var low = asset.Low;
var high = asset.High;
var open = asset.Open;
var close = asset.Close;
var current = asset.Price;
var endTime = asset.Cache.GetData()?.EndTime ?? DateTime.MinValue;
if (direction == OrderDirection.Hold)
{
return new Prices(endTime, current, open, high, low, close);
}
// Only fill with data types we are subscribed to
var subscriptionTypes = Parameters.ConfigProvider
.GetSubscriptionDataConfigs(asset.Symbol)
.Select(x => x.Type).ToList();
// Tick
var tick = asset.Cache.GetData<Tick>();
if (subscriptionTypes.Contains(typeof(Tick)) && tick != null)
{
var price = direction == OrderDirection.Sell ? tick.BidPrice : tick.AskPrice;
if (price != 0m)
{
return new Prices(tick.EndTime, price, 0, 0, 0, 0);
}
// If the ask/bid spreads are not available for ticks, try the price
price = tick.Price;
if (price != 0m)
{
return new Prices(tick.EndTime, price, 0, 0, 0, 0);
}
}
// Quote
var quoteBar = asset.Cache.GetData<QuoteBar>();
if (subscriptionTypes.Contains(typeof(QuoteBar)) && quoteBar != null)
{
var bar = direction == OrderDirection.Sell ? quoteBar.Bid : quoteBar.Ask;
if (bar != null)
{
return new Prices(quoteBar.EndTime, bar);
}
}
// Trade
var tradeBar = asset.Cache.GetData<TradeBar>();
if (subscriptionTypes.Contains(typeof(TradeBar)) && tradeBar != null)
{
return new Prices(tradeBar);
}
return new Prices(endTime, current, open, high, low, close);
}
/// <summary>
/// Determines if the exchange is open using the current time of the asset
/// </summary>
protected static bool IsExchangeOpen(Security asset, bool isExtendedMarketHours)
{
if (!asset.Exchange.DateTimeIsOpen(asset.LocalTime))
{
// if we're not open at the current time exactly, check the bar size, this handle large sized bars (hours/days)
var currentBar = asset.GetLastData();
if (asset.LocalTime.Date != currentBar.EndTime.Date
|| !asset.Exchange.IsOpenDuringBar(currentBar.Time, currentBar.EndTime, isExtendedMarketHours))
{
return false;
}
}
return true;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using CURLAUTH = Interop.libcurl.CURLAUTH;
using CURLoption = Interop.libcurl.CURLoption;
using CURLProxyType = Interop.libcurl.curl_proxytype;
using SafeCurlHandle = Interop.libcurl.SafeCurlHandle;
using SafeCurlSlistHandle = Interop.libcurl.SafeCurlSlistHandle;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
private sealed class EasyRequest : TaskCompletionSource<HttpResponseMessage>
{
internal readonly CurlHandler _handler;
internal readonly HttpRequestMessage _requestMessage;
internal readonly CurlResponseMessage _responseMessage;
internal readonly CancellationToken _cancellationToken;
internal SafeCurlHandle _easyHandle;
private SafeCurlSlistHandle _requestHeaders;
internal Stream _requestContentStream;
internal NetworkCredential _networkCredential;
internal MultiAgent _associatedMultiAgent;
internal SendTransferState _sendTransferState;
public EasyRequest(CurlHandler handler, HttpRequestMessage requestMessage, CancellationToken cancellationToken) :
base(TaskCreationOptions.RunContinuationsAsynchronously)
{
_handler = handler;
_requestMessage = requestMessage;
_responseMessage = new CurlResponseMessage(this);
_cancellationToken = cancellationToken;
}
/// <summary>
/// Initialize the underlying libcurl support for this EasyRequest.
/// This is separated out of the constructor so that we can take into account
/// any additional configuration needed based on the request message
/// after the EasyRequest is configured and so that error handling
/// can be better handled in the caller.
/// </summary>
internal void InitializeCurl()
{
// Create the underlying easy handle
SafeCurlHandle easyHandle = Interop.libcurl.curl_easy_init();
if (easyHandle.IsInvalid)
{
throw new OutOfMemoryException();
}
_easyHandle = easyHandle;
// Configure the handle
SetUrl();
SetDebugging();
SetMultithreading();
SetRedirection();
SetVerb();
SetDecompressionOptions();
SetProxyOptions();
SetCredentialsOptions();
SetCookieOption();
SetRequestHeaders();
}
public void EnsureResponseMessagePublished()
{
bool result = TrySetResult(_responseMessage);
Debug.Assert(result || Task.Status == TaskStatus.RanToCompletion,
"If the task was already completed, it should have been completed succesfully; " +
"we shouldn't be completing as successful after already completing as failed.");
}
public void FailRequest(Exception error)
{
Debug.Assert(error != null, "Expected non-null exception");
var oce = error as OperationCanceledException;
if (oce != null)
{
TrySetCanceled(oce.CancellationToken);
}
else
{
TrySetException(error as HttpRequestException ?? CreateHttpRequestException(error));
}
// There's not much we can reasonably assert here about the result of TrySet*.
// It's possible that the task wasn't yet completed (e.g. a failure while initiating the request),
// it's possible that the task was already completed as success (e.g. a failure sending back the response),
// and it's possible that the task was already completed as failure (e.g. we handled the exception and
// faulted the task, but then tried to fault it again while finishing processing in the main loop).
// Make sure the exception is available on the response stream so that it's propagated
// from any attempts to read from the stream.
_responseMessage.ResponseStream.SignalComplete(error);
}
public void Cleanup() // not called Dispose because the request may still be in use after it's cleaned up
{
_responseMessage.ResponseStream.SignalComplete(); // No more callbacks so no more data
// Don't dispose of the ResponseMessage.ResponseStream as it may still be in use
// by code reading data stored in the stream.
// Dispose of the input content stream if there was one. Nothing should be using it any more.
if (_requestContentStream != null)
_requestContentStream.Dispose();
// Dispose of the underlying easy handle. We're no longer processing it.
if (_easyHandle != null)
_easyHandle.Dispose();
// Dispose of the request headers if we had any. We had to keep this handle
// alive as long as the easy handle was using it. We didn't need to do any
// ref counting on the safe handle, though, as the only processing happens
// in Process, which ensures the handle will be rooted while libcurl is
// doing any processing that assumes it's valid.
if (_requestHeaders != null)
_requestHeaders.Dispose();
}
private void SetUrl()
{
VerboseTrace(_requestMessage.RequestUri.AbsoluteUri);
SetCurlOption(CURLoption.CURLOPT_URL, _requestMessage.RequestUri.AbsoluteUri);
}
[Conditional(VerboseDebuggingConditional)]
private void SetDebugging()
{
SetCurlOption(CURLoption.CURLOPT_VERBOSE, 1L);
// In addition to CURLOPT_VERBOSE, CURLOPT_DEBUGFUNCTION could be used here in the future to:
// - Route the verbose output to somewhere other than stderr
// - Dump additional data related to CURLINFO_DATA_* and CURLINFO_SSL_DATA_*
}
private void SetMultithreading()
{
SetCurlOption(CURLoption.CURLOPT_NOSIGNAL, 1L);
}
private void SetRedirection()
{
if (!_handler._automaticRedirection)
{
return;
}
VerboseTrace(_handler._maxAutomaticRedirections.ToString());
SetCurlOption(CURLoption.CURLOPT_FOLLOWLOCATION, 1L);
SetCurlOption(CURLoption.CURLOPT_MAXREDIRS, _handler._maxAutomaticRedirections);
}
private void SetVerb()
{
VerboseTrace(_requestMessage.Method.Method);
if (_requestMessage.Method == HttpMethod.Put)
{
SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L);
if (_requestMessage.Content == null)
{
SetCurlOption(CURLoption.CURLOPT_INFILESIZE, 0L);
}
}
else if (_requestMessage.Method == HttpMethod.Head)
{
SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L);
}
else if (_requestMessage.Method == HttpMethod.Post)
{
SetCurlOption(CURLoption.CURLOPT_POST, 1L);
if (_requestMessage.Content == null)
{
SetCurlOption(CURLoption.CURLOPT_POSTFIELDSIZE, 0L);
SetCurlOption(CURLoption.CURLOPT_COPYPOSTFIELDS, string.Empty);
}
}
}
private void SetDecompressionOptions()
{
if (!_handler.SupportsAutomaticDecompression)
{
return;
}
DecompressionMethods autoDecompression = _handler.AutomaticDecompression;
bool gzip = (autoDecompression & DecompressionMethods.GZip) != 0;
bool deflate = (autoDecompression & DecompressionMethods.Deflate) != 0;
if (gzip || deflate)
{
string encoding = (gzip && deflate) ? EncodingNameGzip + "," + EncodingNameDeflate :
gzip ? EncodingNameGzip :
EncodingNameDeflate;
SetCurlOption(CURLoption.CURLOPT_ACCEPTENCODING, encoding);
VerboseTrace(encoding);
}
}
private void SetProxyOptions()
{
if (_handler._proxyPolicy == ProxyUsePolicy.DoNotUseProxy)
{
SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty);
VerboseTrace("No proxy");
return;
}
if ((_handler._proxyPolicy == ProxyUsePolicy.UseDefaultProxy) ||
(_handler.Proxy == null))
{
VerboseTrace("Default proxy");
return;
}
Debug.Assert(_handler.Proxy != null, "proxy is null");
Debug.Assert(_handler._proxyPolicy == ProxyUsePolicy.UseCustomProxy, "_proxyPolicy is not UseCustomProxy");
if (_handler.Proxy.IsBypassed(_requestMessage.RequestUri))
{
SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty);
VerboseTrace("Bypassed proxy");
return;
}
var proxyUri = _handler.Proxy.GetProxy(_requestMessage.RequestUri);
if (proxyUri == null)
{
VerboseTrace("No proxy URI");
return;
}
SetCurlOption(CURLoption.CURLOPT_PROXYTYPE, CURLProxyType.CURLPROXY_HTTP);
SetCurlOption(CURLoption.CURLOPT_PROXY, proxyUri.AbsoluteUri);
SetCurlOption(CURLoption.CURLOPT_PROXYPORT, proxyUri.Port);
VerboseTrace("Set proxy: " + proxyUri.ToString());
NetworkCredential credentials = GetCredentials(_handler.Proxy.Credentials, _requestMessage.RequestUri);
if (credentials != null)
{
if (string.IsNullOrEmpty(credentials.UserName))
{
throw new ArgumentException(SR.net_http_argument_empty_string, "UserName");
}
string credentialText = string.IsNullOrEmpty(credentials.Domain) ?
string.Format("{0}:{1}", credentials.UserName, credentials.Password) :
string.Format("{2}\\{0}:{1}", credentials.UserName, credentials.Password, credentials.Domain);
SetCurlOption(CURLoption.CURLOPT_PROXYUSERPWD, credentialText);
VerboseTrace("Set proxy credentials");
}
}
private void SetCredentialsOptions()
{
NetworkCredential credentials = _handler.GetNetworkCredentials(_handler._serverCredentials, _requestMessage.RequestUri);
if (credentials == null)
{
return;
}
string userName = string.IsNullOrEmpty(credentials.Domain) ?
credentials.UserName :
string.Format("{0}\\{1}", credentials.Domain, credentials.UserName);
SetCurlOption(CURLoption.CURLOPT_USERNAME, userName);
SetCurlOption(CURLoption.CURLOPT_HTTPAUTH, CURLAUTH.AuthAny);
if (credentials.Password != null)
{
SetCurlOption(CURLoption.CURLOPT_PASSWORD, credentials.Password);
}
_networkCredential = credentials;
VerboseTrace("Set credentials options");
}
private void SetCookieOption()
{
if (!_handler._useCookie)
{
return;
}
string cookieValues = _handler.CookieContainer.GetCookieHeader(_requestMessage.RequestUri);
if (cookieValues != null)
{
SetCurlOption(CURLoption.CURLOPT_COOKIE, cookieValues);
VerboseTrace("Set cookies");
}
}
private void SetRequestHeaders()
{
HttpContentHeaders contentHeaders = null;
if (_requestMessage.Content != null)
{
SetChunkedModeForSend(_requestMessage);
// TODO: Content-Length header isn't getting correctly placed using ToString()
// This is a bug in HttpContentHeaders that needs to be fixed.
if (_requestMessage.Content.Headers.ContentLength.HasValue)
{
long contentLength = _requestMessage.Content.Headers.ContentLength.Value;
_requestMessage.Content.Headers.ContentLength = null;
_requestMessage.Content.Headers.ContentLength = contentLength;
}
contentHeaders = _requestMessage.Content.Headers;
}
var slist = new SafeCurlSlistHandle();
// Add request and content request headers
if (_requestMessage.Headers != null)
{
AddRequestHeaders(_requestMessage.Headers, slist);
}
if (contentHeaders != null)
{
AddRequestHeaders(contentHeaders, slist);
if (contentHeaders.ContentType == null)
{
if (!Interop.libcurl.curl_slist_append(slist, NoContentType))
{
throw CreateHttpRequestException();
}
}
}
// Since libcurl always adds a Transfer-Encoding header, we need to explicitly block
// it if caller specifically does not want to set the header
if (_requestMessage.Headers.TransferEncodingChunked.HasValue &&
!_requestMessage.Headers.TransferEncodingChunked.Value)
{
if (!Interop.libcurl.curl_slist_append(slist, NoTransferEncoding))
{
throw CreateHttpRequestException();
}
}
if (!slist.IsInvalid)
{
_requestHeaders = slist;
SetCurlOption(CURLoption.CURLOPT_HTTPHEADER, slist);
VerboseTrace("Set headers");
}
else
{
slist.Dispose();
}
}
private static void AddRequestHeaders(HttpHeaders headers, SafeCurlSlistHandle handle)
{
foreach (KeyValuePair<string, IEnumerable<string>> header in headers)
{
string headerStr = header.Key + ": " + headers.GetHeaderString(header.Key);
if (!Interop.libcurl.curl_slist_append(handle, headerStr))
{
throw CreateHttpRequestException();
}
}
}
internal void SetCurlOption(int option, string value)
{
ThrowIfCURLEError(Interop.libcurl.curl_easy_setopt(_easyHandle, option, value));
}
internal void SetCurlOption(int option, long value)
{
ThrowIfCURLEError(Interop.libcurl.curl_easy_setopt(_easyHandle, option, value));
}
internal void SetCurlOption(int option, ulong value)
{
ThrowIfCURLEError(Interop.libcurl.curl_easy_setopt(_easyHandle, option, value));
}
internal void SetCurlOption(int option, IntPtr value)
{
ThrowIfCURLEError(Interop.libcurl.curl_easy_setopt(_easyHandle, option, value));
}
internal void SetCurlOption(int option, Delegate value)
{
ThrowIfCURLEError(Interop.libcurl.curl_easy_setopt(_easyHandle, option, value));
}
internal void SetCurlOption(int option, SafeHandle value)
{
ThrowIfCURLEError(Interop.libcurl.curl_easy_setopt(_easyHandle, option, value));
}
internal sealed class SendTransferState
{
internal readonly byte[] _buffer = new byte[RequestBufferSize]; // PERF TODO: Determine if this should be optimized to start smaller and grow
internal int _offset;
internal int _count;
internal Task<int> _task;
internal void SetTaskOffsetCount(Task<int> task, int offset, int count)
{
Debug.Assert(offset >= 0, "Offset should never be negative");
Debug.Assert(count >= 0, "Count should never be negative");
Debug.Assert(offset <= count, "Offset should never be greater than count");
_task = task;
_offset = offset;
_count = count;
}
}
[Conditional(VerboseDebuggingConditional)]
private void VerboseTrace(string text = null, [CallerMemberName] string memberName = null)
{
CurlHandler.VerboseTrace(text, memberName, easy: this, agent: null);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.NetworkInformation;
using System.Text;
// Relevant cookie specs:
//
// PERSISTENT CLIENT STATE HTTP COOKIES (1996)
// From <http:// web.archive.org/web/20020803110822/http://wp.netscape.com/newsref/std/cookie_spec.html>
//
// RFC2109 HTTP State Management Mechanism (February 1997)
// From <http:// tools.ietf.org/html/rfc2109>
//
// RFC2965 HTTP State Management Mechanism (October 2000)
// From <http:// tools.ietf.org/html/rfc2965>
//
// RFC6265 HTTP State Management Mechanism (April 2011)
// From <http:// tools.ietf.org/html/rfc6265>
//
// The Version attribute of the cookie header is defined and used only in RFC2109 and RFC2965 cookie
// specs and specifies Version=1. The Version attribute is not used in the Netscape cookie spec
// (considered as Version=0). Nor is it used in the most recent cookie spec, RFC6265, introduced in 2011.
// RFC6265 deprecates all previous cookie specs including the Version attribute.
//
// Cookies without an explicit Domain attribute will only match a potential uri that matches the original
// uri from where the cookie came from.
//
// For explicit Domain attribute in the cookie, the following rules apply:
//
// Version=0 (Netscape, RFC6265) allows the Domain attribute of the cookie to match any tail substring
// of the host uri.
//
// Version=1 related cookie specs only allows the Domain attribute to match the host uri based on a
// more restricted set of rules.
//
// According to RFC2109/RFC2965, the cookie will be rejected for matching if:
// * The value for the Domain attribute contains no embedded dots or does not start with a dot.
// * The value for the request-host does not domain-match the Domain attribute.
// " The request-host is a FQDN (not IP address) and has the form HD, where D is the value of the Domain
// attribute, and H is a string that contains one or more dots.
//
// Examples:
// * A cookie from request-host y.x.foo.com for Domain=.foo.com would be rejected, because H is y.x
// and contains a dot.
//
// * A cookie from request-host x.foo.com for Domain=.foo.com would be accepted.
//
// * A cookie with Domain=.com or Domain=.com., will always be rejected, because there is no embedded dot.
//
// * A cookie with Domain=ajax.com will be rejected because the value for Domain does not begin with a dot.
namespace System.Net
{
internal struct HeaderVariantInfo
{
private readonly string _name;
private readonly CookieVariant _variant;
internal HeaderVariantInfo(string name, CookieVariant variant)
{
_name = name;
_variant = variant;
}
internal string Name
{
get
{
return _name;
}
}
internal CookieVariant Variant
{
get
{
return _variant;
}
}
}
// CookieContainer
//
// Manage cookies for a user (implicit). Based on RFC 2965.
[Serializable]
public class CookieContainer
{
public const int DefaultCookieLimit = 300;
public const int DefaultPerDomainCookieLimit = 20;
public const int DefaultCookieLengthLimit = 4096;
private static readonly HeaderVariantInfo[] s_headerInfo = {
new HeaderVariantInfo(HttpKnownHeaderNames.SetCookie, CookieVariant.Rfc2109),
new HeaderVariantInfo(HttpKnownHeaderNames.SetCookie2, CookieVariant.Rfc2965)
};
// NOTE: all accesses of _domainTable must be performed with _domainTable locked.
private readonly Dictionary<string, PathList> _domainTable = new Dictionary<string, PathList>();
private int _maxCookieSize = DefaultCookieLengthLimit;
private int _maxCookies = DefaultCookieLimit;
private int _maxCookiesPerDomain = DefaultPerDomainCookieLimit;
private int _count = 0;
private string _fqdnMyDomain = string.Empty;
public CookieContainer()
{
string domain = HostInformation.DomainName;
if (domain != null && domain.Length > 1)
{
_fqdnMyDomain = '.' + domain;
}
// Otherwise it will remain string.Empty.
}
public CookieContainer(int capacity) : this()
{
if (capacity <= 0)
{
throw new ArgumentException(SR.net_toosmall, "Capacity");
}
_maxCookies = capacity;
}
public CookieContainer(int capacity, int perDomainCapacity, int maxCookieSize) : this(capacity)
{
if (perDomainCapacity != Int32.MaxValue && (perDomainCapacity <= 0 || perDomainCapacity > capacity))
{
throw new ArgumentOutOfRangeException(nameof(perDomainCapacity), SR.Format(SR.net_cookie_capacity_range, "PerDomainCapacity", 0, capacity));
}
_maxCookiesPerDomain = perDomainCapacity;
if (maxCookieSize <= 0)
{
throw new ArgumentException(SR.net_toosmall, "MaxCookieSize");
}
_maxCookieSize = maxCookieSize;
}
// NOTE: after shrinking the capacity, Count can become greater than Capacity.
public int Capacity
{
get
{
return _maxCookies;
}
set
{
if (value <= 0 || (value < _maxCookiesPerDomain && _maxCookiesPerDomain != Int32.MaxValue))
{
throw new ArgumentOutOfRangeException(nameof(value), SR.Format(SR.net_cookie_capacity_range, "Capacity", 0, _maxCookiesPerDomain));
}
if (value < _maxCookies)
{
_maxCookies = value;
AgeCookies(null);
}
_maxCookies = value;
}
}
/// <devdoc>
/// <para>Returns the total number of cookies in the container.</para>
/// </devdoc>
public int Count
{
get
{
return _count;
}
}
public int MaxCookieSize
{
get
{
return _maxCookieSize;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_maxCookieSize = value;
}
}
/// <devdoc>
/// <para>After shrinking domain capacity, each domain will less hold than new domain capacity.</para>
/// </devdoc>
public int PerDomainCapacity
{
get
{
return _maxCookiesPerDomain;
}
set
{
if (value <= 0 || (value > _maxCookies && value != Int32.MaxValue))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
if (value < _maxCookiesPerDomain)
{
_maxCookiesPerDomain = value;
AgeCookies(null);
}
_maxCookiesPerDomain = value;
}
}
// This method will construct a faked URI: the Domain property is required for param.
public void Add(Cookie cookie)
{
if (cookie == null)
{
throw new ArgumentNullException(nameof(cookie));
}
if (cookie.Domain.Length == 0)
{
throw new ArgumentException(SR.net_emptystringcall, "cookie.Domain");
}
Uri uri;
var uriSb = new StringBuilder();
// We cannot add an invalid cookie into the container.
// Trying to prepare Uri for the cookie verification.
uriSb.Append(cookie.Secure ? UriScheme.Https : UriScheme.Http).Append(UriScheme.SchemeDelimiter);
// If the original cookie has an explicitly set domain, copy it over to the new cookie.
if (!cookie.DomainImplicit)
{
if (cookie.Domain[0] == '.')
{
uriSb.Append("0"); // URI cctor should consume this faked host.
}
}
uriSb.Append(cookie.Domain);
// Either keep Port as implicit or set it according to original cookie.
if (cookie.PortList != null)
{
uriSb.Append(":").Append(cookie.PortList[0]);
}
// Path must be present, set to root by default.
uriSb.Append(cookie.Path);
if (!Uri.TryCreate(uriSb.ToString(), UriKind.Absolute, out uri))
throw new CookieException(SR.Format(SR.net_cookie_attribute, "Domain", cookie.Domain));
// We don't know cookie verification status, so re-create the cookie and verify it.
Cookie new_cookie = cookie.Clone();
new_cookie.VerifySetDefaults(new_cookie.Variant, uri, IsLocalDomain(uri.Host), _fqdnMyDomain, true, true);
Add(new_cookie, true);
}
// This method is called *only* when cookie verification is done, so unlike with public
// Add(Cookie cookie) the cookie is in a reasonable condition.
internal void Add(Cookie cookie, bool throwOnError)
{
PathList pathList;
if (cookie.Value.Length > _maxCookieSize)
{
if (throwOnError)
{
throw new CookieException(SR.Format(SR.net_cookie_size, cookie.ToString(), _maxCookieSize));
}
return;
}
try
{
lock (_domainTable)
{
if (!_domainTable.TryGetValue(cookie.DomainKey, out pathList))
{
_domainTable[cookie.DomainKey] = (pathList = PathList.Create());
}
}
int domain_count = pathList.GetCookiesCount();
CookieCollection cookies;
lock (pathList.SyncRoot)
{
cookies = pathList[cookie.Path];
if (cookies == null)
{
cookies = new CookieCollection();
pathList[cookie.Path] = cookies;
}
}
if (cookie.Expired)
{
// Explicit removal command (Max-Age == 0)
lock (cookies)
{
int idx = cookies.IndexOf(cookie);
if (idx != -1)
{
cookies.RemoveAt(idx);
--_count;
}
}
}
else
{
// This is about real cookie adding, check Capacity first
if (domain_count >= _maxCookiesPerDomain && !AgeCookies(cookie.DomainKey))
{
return; // Cannot age: reject new cookie
}
else if (_count >= _maxCookies && !AgeCookies(null))
{
return; // Cannot age: reject new cookie
}
// About to change the collection
lock (cookies)
{
_count += cookies.InternalAdd(cookie, true);
}
}
}
catch (OutOfMemoryException)
{
throw;
}
catch (Exception e)
{
if (throwOnError)
{
throw new CookieException(SR.net_container_add_cookie, e);
}
}
}
// This function, when called, must delete at least one cookie.
// If there are expired cookies in given scope they are cleaned up.
// If nothing is found the least used Collection will be found and removed
// from the container.
//
// Also note that expired cookies are also removed during request preparation
// (this.GetCookies method).
//
// Param. 'domain' == null means to age in the whole container.
private bool AgeCookies(string domain)
{
Debug.Assert(_maxCookies != 0);
Debug.Assert(_maxCookiesPerDomain != 0);
int removed = 0;
DateTime oldUsed = DateTime.MaxValue;
DateTime tempUsed;
CookieCollection lruCc = null;
string lruDomain = null;
string tempDomain = null;
PathList pathList;
int domain_count = 0;
int itemp = 0;
float remainingFraction = 1.0F;
// The container was shrunk, might need additional cleanup for each domain
if (_count > _maxCookies)
{
// Means the fraction of the container to be left.
// Each domain will be cut accordingly.
remainingFraction = (float)_maxCookies / (float)_count;
}
lock (_domainTable)
{
foreach (KeyValuePair<string, PathList> entry in _domainTable)
{
if (domain == null)
{
tempDomain = entry.Key;
pathList = entry.Value; // Aliasing to trick foreach
}
else
{
tempDomain = domain;
_domainTable.TryGetValue(domain, out pathList);
}
domain_count = 0; // Cookies in the domain
lock (pathList.SyncRoot)
{
foreach (KeyValuePair<string, CookieCollection> pair in pathList)
{
CookieCollection cc = pair.Value;
itemp = ExpireCollection(cc);
removed += itemp;
_count -= itemp; // Update this container's count
domain_count += cc.Count;
// We also find the least used cookie collection in ENTIRE container.
// We count the collection as LRU only if it holds 1+ elements.
if (cc.Count > 0 && (tempUsed = cc.TimeStamp(CookieCollection.Stamp.Check)) < oldUsed)
{
lruDomain = tempDomain;
lruCc = cc;
oldUsed = tempUsed;
}
}
}
// Check if we have reduced to the limit of the domain by expiration only.
int min_count = Math.Min((int)(domain_count * remainingFraction), Math.Min(_maxCookiesPerDomain, _maxCookies) - 1);
if (domain_count > min_count)
{
// This case requires sorting all domain collections by timestamp.
KeyValuePair<DateTime, CookieCollection>[] cookies;
lock (pathList.SyncRoot)
{
cookies = new KeyValuePair<DateTime, CookieCollection>[pathList.Count];
foreach (KeyValuePair<string, CookieCollection> pair in pathList)
{
CookieCollection cc = pair.Value;
cookies[itemp] = new KeyValuePair<DateTime, CookieCollection>(cc.TimeStamp(CookieCollection.Stamp.Check), cc);
++itemp;
}
}
Array.Sort(cookies, (a, b) => a.Key.CompareTo(b.Key));
itemp = 0;
for (int i = 0; i < cookies.Length; ++i)
{
CookieCollection cc = cookies[i].Value;
lock (cc)
{
while (domain_count > min_count && cc.Count > 0)
{
cc.RemoveAt(0);
--domain_count;
--_count;
++removed;
}
}
if (domain_count <= min_count)
{
break;
}
}
if (domain_count > min_count && domain != null)
{
// Cannot complete aging of explicit domain (no cookie adding allowed).
return false;
}
}
}
}
// We have completed aging of the specified domain.
if (domain != null)
{
return true;
}
// The rest is for entire container aging.
// We must get at least one free slot.
// Don't need to apply LRU if we already cleaned something.
if (removed != 0)
{
return true;
}
if (oldUsed == DateTime.MaxValue)
{
// Something strange. Either capacity is 0 or all collections are locked with cc.Used.
return false;
}
// Remove oldest cookies from the least used collection.
lock (lruCc)
{
while (_count >= _maxCookies && lruCc.Count > 0)
{
lruCc.RemoveAt(0);
--_count;
}
}
return true;
}
// Return number of cookies removed from the collection.
private int ExpireCollection(CookieCollection cc)
{
lock (cc)
{
int oldCount = cc.Count;
int idx = oldCount - 1;
// Cannot use enumerator as we are going to alter collection.
while (idx >= 0)
{
Cookie cookie = cc[idx];
if (cookie.Expired)
{
cc.RemoveAt(idx);
}
--idx;
}
return oldCount - cc.Count;
}
}
public void Add(CookieCollection cookies)
{
if (cookies == null)
{
throw new ArgumentNullException(nameof(cookies));
}
foreach (Cookie c in cookies)
{
Add(c);
}
}
// This will try (if needed) get the full domain name of the host given the Uri.
// NEVER call this function from internal methods with 'fqdnRemote' == null.
// Since this method counts security issue for DNS and hence will slow
// the performance.
internal bool IsLocalDomain(string host)
{
int dot = host.IndexOf('.');
if (dot == -1)
{
// No choice but to treat it as a host on the local domain.
// This also covers 'localhost' and 'loopback'.
return true;
}
// Quick test for typical cases: loopback addresses for IPv4 and IPv6.
if ((host == "127.0.0.1") || (host == "::1") || (host == "0:0:0:0:0:0:0:1"))
{
return true;
}
// Test domain membership.
if (string.Compare(_fqdnMyDomain, 0, host, dot, _fqdnMyDomain.Length, StringComparison.OrdinalIgnoreCase) == 0)
{
return true;
}
// Test for "127.###.###.###" without using regex.
string[] ipParts = host.Split('.');
if (ipParts != null && ipParts.Length == 4 && ipParts[0] == "127")
{
int i;
for (i = 1; i < ipParts.Length; i++)
{
string part = ipParts[i];
switch (part.Length)
{
case 3:
if (part[2] < '0' || part[2] > '9')
{
break;
}
goto case 2;
case 2:
if (part[1] < '0' || part[1] > '9')
{
break;
}
goto case 1;
case 1:
if (part[0] < '0' || part[0] > '9')
{
break;
}
continue;
}
break;
}
if (i == 4)
{
return true;
}
}
return false;
}
public void Add(Uri uri, Cookie cookie)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
if (cookie == null)
{
throw new ArgumentNullException(nameof(cookie));
}
Cookie new_cookie = cookie.Clone();
new_cookie.VerifySetDefaults(new_cookie.Variant, uri, IsLocalDomain(uri.Host), _fqdnMyDomain, true, true);
Add(new_cookie, true);
}
public void Add(Uri uri, CookieCollection cookies)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
if (cookies == null)
{
throw new ArgumentNullException(nameof(cookies));
}
bool isLocalDomain = IsLocalDomain(uri.Host);
foreach (Cookie c in cookies)
{
Cookie new_cookie = c.Clone();
new_cookie.VerifySetDefaults(new_cookie.Variant, uri, isLocalDomain, _fqdnMyDomain, true, true);
Add(new_cookie, true);
}
}
internal CookieCollection CookieCutter(Uri uri, string headerName, string setCookieHeader, bool isThrow)
{
if (NetEventSource.IsEnabled)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"uri:{uri} headerName:{headerName} setCookieHeader:{setCookieHeader} isThrow:{isThrow}");
}
CookieCollection cookies = new CookieCollection();
CookieVariant variant = CookieVariant.Unknown;
if (headerName == null)
{
variant = CookieVariant.Default;
}
else
{
for (int i = 0; i < s_headerInfo.Length; ++i)
{
if ((String.Compare(headerName, s_headerInfo[i].Name, StringComparison.OrdinalIgnoreCase) == 0))
{
variant = s_headerInfo[i].Variant;
}
}
}
bool isLocalDomain = IsLocalDomain(uri.Host);
try
{
CookieParser parser = new CookieParser(setCookieHeader);
do
{
Cookie cookie = parser.Get();
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"CookieParser returned cookie:{cookie}");
if (cookie == null)
{
break;
}
// Parser marks invalid cookies this way
if (String.IsNullOrEmpty(cookie.Name))
{
if (isThrow)
{
throw new CookieException(SR.net_cookie_format);
}
// Otherwise, ignore (reject) cookie
continue;
}
// This will set the default values from the response URI
// AND will check for cookie validity
if (!cookie.VerifySetDefaults(variant, uri, isLocalDomain, _fqdnMyDomain, true, isThrow))
{
continue;
}
// If many same cookies arrive we collapse them into just one, hence setting
// parameter isStrict = true below
cookies.InternalAdd(cookie, true);
} while (true);
}
catch (OutOfMemoryException)
{
throw;
}
catch (Exception e)
{
if (isThrow)
{
throw new CookieException(SR.Format(SR.net_cookie_parse_header, uri.AbsoluteUri), e);
}
}
foreach (Cookie c in cookies)
{
Add(c, isThrow);
}
return cookies;
}
public CookieCollection GetCookies(Uri uri)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
return InternalGetCookies(uri) ?? new CookieCollection();
}
internal CookieCollection InternalGetCookies(Uri uri)
{
if (_count == 0)
{
return null;
}
bool isSecure = (uri.Scheme == UriScheme.Https);
int port = uri.Port;
CookieCollection cookies = null;
List<string> domainAttributeMatchAnyCookieVariant = new List<string>();
List<string> domainAttributeMatchOnlyCookieVariantPlain = null;
string fqdnRemote = uri.Host;
// Add initial candidates to match Domain attribute of possible cookies.
// For these Domains, cookie can have any CookieVariant enum value.
domainAttributeMatchAnyCookieVariant.Add(fqdnRemote);
domainAttributeMatchAnyCookieVariant.Add("." + fqdnRemote);
int dot = fqdnRemote.IndexOf('.');
if (dot == -1)
{
// DNS.resolve may return short names even for other inet domains ;-(
// We _don't_ know what the exact domain is, so try also grab short hostname cookies.
// Grab long name from the local domain
if (_fqdnMyDomain != null && _fqdnMyDomain.Length != 0)
{
domainAttributeMatchAnyCookieVariant.Add(fqdnRemote + _fqdnMyDomain);
// Grab the local domain itself
domainAttributeMatchAnyCookieVariant.Add(_fqdnMyDomain);
}
}
else
{
// Grab the host domain
domainAttributeMatchAnyCookieVariant.Add(fqdnRemote.Substring(dot));
// The following block is only for compatibility with Version0 spec.
// Still, we'll add only Plain-Variant cookies if found under below keys
if (fqdnRemote.Length > 2)
{
// We ignore the '.' at the end on the name
int last = fqdnRemote.LastIndexOf('.', fqdnRemote.Length - 2);
// AND keys with <2 dots inside.
if (last > 0)
{
last = fqdnRemote.LastIndexOf('.', last - 1);
}
if (last != -1)
{
while ((dot < last) && (dot = fqdnRemote.IndexOf('.', dot + 1)) != -1)
{
if (domainAttributeMatchOnlyCookieVariantPlain == null)
{
domainAttributeMatchOnlyCookieVariantPlain = new List<string>();
}
// These candidates can only match CookieVariant.Plain cookies.
domainAttributeMatchOnlyCookieVariantPlain.Add(fqdnRemote.Substring(dot));
}
}
}
}
BuildCookieCollectionFromDomainMatches(uri, isSecure, port, ref cookies, domainAttributeMatchAnyCookieVariant, false);
if (domainAttributeMatchOnlyCookieVariantPlain != null)
{
BuildCookieCollectionFromDomainMatches(uri, isSecure, port, ref cookies, domainAttributeMatchOnlyCookieVariantPlain, true);
}
return cookies;
}
private void BuildCookieCollectionFromDomainMatches(Uri uri, bool isSecure, int port, ref CookieCollection cookies, List<string> domainAttribute, bool matchOnlyPlainCookie)
{
for (int i = 0; i < domainAttribute.Count; i++)
{
bool found = false;
bool defaultAdded = false;
PathList pathList;
lock (_domainTable)
{
if (!_domainTable.TryGetValue(domainAttribute[i], out pathList))
{
continue;
}
}
lock (pathList.SyncRoot)
{
foreach (KeyValuePair<string, CookieCollection> pair in pathList)
{
string path = pair.Key;
if (uri.AbsolutePath.StartsWith(CookieParser.CheckQuoted(path)))
{
found = true;
CookieCollection cc = pair.Value;
cc.TimeStamp(CookieCollection.Stamp.Set);
MergeUpdateCollections(ref cookies, cc, port, isSecure, matchOnlyPlainCookie);
if (path == "/")
{
defaultAdded = true;
}
}
else if (found)
{
break;
}
}
}
if (!defaultAdded)
{
CookieCollection cc = pathList["/"];
if (cc != null)
{
cc.TimeStamp(CookieCollection.Stamp.Set);
MergeUpdateCollections(ref cookies, cc, port, isSecure, matchOnlyPlainCookie);
}
}
// Remove unused domain
// (This is the only place that does domain removal)
if (pathList.Count == 0)
{
lock (_domainTable)
{
_domainTable.Remove(domainAttribute[i]);
}
}
}
}
private void MergeUpdateCollections(ref CookieCollection destination, CookieCollection source, int port, bool isSecure, bool isPlainOnly)
{
lock (source)
{
// Cannot use foreach as we are going to update 'source'
for (int idx = 0; idx < source.Count; ++idx)
{
bool to_add = false;
Cookie cookie = source[idx];
if (cookie.Expired)
{
// If expired, remove from container and don't add to the destination
source.RemoveAt(idx);
--_count;
--idx;
}
else
{
// Add only if port does match to this request URI
// or was not present in the original response.
if (isPlainOnly && cookie.Variant != CookieVariant.Plain)
{
; // Don't add
}
else if (cookie.PortList != null)
{
foreach (int p in cookie.PortList)
{
if (p == port)
{
to_add = true;
break;
}
}
}
else
{
// It was implicit Port, always OK to add.
to_add = true;
}
// Refuse to add a secure cookie into an 'unsecure' destination
if (cookie.Secure && !isSecure)
{
to_add = false;
}
if (to_add)
{
// In 'source' are already ordered.
// If two same cookies come from different 'source' then they
// will follow (not replace) each other.
if (destination == null)
{
destination = new CookieCollection();
}
destination.InternalAdd(cookie, false);
}
}
}
}
}
public string GetCookieHeader(Uri uri)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
string dummy;
return GetCookieHeader(uri, out dummy);
}
internal string GetCookieHeader(Uri uri, out string optCookie2)
{
CookieCollection cookies = InternalGetCookies(uri);
if (cookies == null)
{
optCookie2 = string.Empty;
return string.Empty;
}
string delimiter = string.Empty;
var builder = StringBuilderCache.Acquire();
for (int i = 0; i < cookies.Count; i++)
{
builder.Append(delimiter);
cookies[i].ToString(builder);
delimiter = "; ";
}
optCookie2 = cookies.IsOtherVersionSeen ?
(Cookie.SpecialAttributeLiteral +
Cookie.VersionAttributeName +
Cookie.EqualsLiteral +
Cookie.MaxSupportedVersionString) : string.Empty;
return StringBuilderCache.GetStringAndRelease(builder);
}
public void SetCookies(Uri uri, string cookieHeader)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
if (cookieHeader == null)
{
throw new ArgumentNullException(nameof(cookieHeader));
}
CookieCutter(uri, null, cookieHeader, true); // Will throw on error
}
}
[Serializable]
internal struct PathList
{
// Usage of PathList depends on it being shallowly immutable;
// adding any mutable fields to it would result in breaks.
private readonly SortedList<string, CookieCollection> _list;
public static PathList Create() => new PathList(new SortedList<string, CookieCollection>(PathListComparer.StaticInstance));
private PathList(SortedList<string, CookieCollection> list)
{
Debug.Assert(list != null, $"{nameof(list)} must not be null.");
_list = list;
}
public int Count
{
get
{
lock (SyncRoot)
{
return _list.Count;
}
}
}
public int GetCookiesCount()
{
int count = 0;
lock (SyncRoot)
{
foreach (KeyValuePair<string, CookieCollection> pair in _list)
{
CookieCollection cc = pair.Value;
count += cc.Count;
}
}
return count;
}
public CookieCollection this[string s]
{
get
{
lock (SyncRoot)
{
CookieCollection value;
_list.TryGetValue(s, out value);
return value;
}
}
set
{
lock (SyncRoot)
{
Debug.Assert(value != null);
_list[s] = value;
}
}
}
public IEnumerator<KeyValuePair<string, CookieCollection>> GetEnumerator()
{
lock (SyncRoot)
{
return _list.GetEnumerator();
}
}
public object SyncRoot
{
get
{
Debug.Assert(_list != null, $"{nameof(PathList)} should never be default initialized and only ever created with {nameof(Create)}.");
return _list;
}
}
[Serializable]
private sealed class PathListComparer : IComparer<string>
{
internal static readonly PathListComparer StaticInstance = new PathListComparer();
int IComparer<string>.Compare(string x, string y)
{
string pathLeft = CookieParser.CheckQuoted(x);
string pathRight = CookieParser.CheckQuoted(y);
int ll = pathLeft.Length;
int lr = pathRight.Length;
int length = Math.Min(ll, lr);
for (int i = 0; i < length; ++i)
{
if (pathLeft[i] != pathRight[i])
{
return pathLeft[i] - pathRight[i];
}
}
return lr - ll;
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="MethodCaller.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>Provides methods to dynamically find and call methods.</summary>
//-----------------------------------------------------------------------
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using Csla.Properties;
using Csla.Server;
using Csla;
using System.Globalization;
using System.Threading.Tasks;
namespace Csla.Reflection
{
/// <summary>
/// Provides methods to dynamically find and call methods.
/// </summary>
public static class MethodCaller
{
private const BindingFlags allLevelFlags
= BindingFlags.FlattenHierarchy
| BindingFlags.Instance
| BindingFlags.Public
| BindingFlags.NonPublic
;
private const BindingFlags oneLevelFlags
= BindingFlags.DeclaredOnly
| BindingFlags.Instance
| BindingFlags.Public
| BindingFlags.NonPublic
;
private const BindingFlags ctorFlags
= BindingFlags.Instance
| BindingFlags.Public
| BindingFlags.NonPublic
;
private const BindingFlags factoryFlags =
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.FlattenHierarchy;
private const BindingFlags privateMethodFlags =
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.FlattenHierarchy;
#if !IOS
#region Dynamic Method Cache
private static Dictionary<MethodCacheKey, DynamicMethodHandle> _methodCache = new Dictionary<MethodCacheKey, DynamicMethodHandle>();
private static DynamicMethodHandle GetCachedMethod(object obj, System.Reflection.MethodInfo info, params object[] parameters)
{
var key = new MethodCacheKey(obj.GetType().FullName, info.Name, GetParameterTypes(parameters));
DynamicMethodHandle mh = null;
var found = false;
try
{
found = _methodCache.TryGetValue(key, out mh);
}
catch
{ /* failure will drop into !found block */ }
if (!found)
{
lock (_methodCache)
{
if (!_methodCache.TryGetValue(key, out mh))
{
mh = new DynamicMethodHandle(info, parameters);
_methodCache.Add(key, mh);
}
}
}
return mh;
}
private static DynamicMethodHandle GetCachedMethod(object obj, string method)
{
return GetCachedMethod(obj, method, false, null);
}
private static DynamicMethodHandle GetCachedMethod(object obj, string method, params object[] parameters)
{
return GetCachedMethod(obj, method, true, parameters);
}
private static DynamicMethodHandle GetCachedMethod(object obj, string method, bool hasParameters, params object[] parameters)
{
var key = new MethodCacheKey(obj.GetType().FullName, method, GetParameterTypes(hasParameters, parameters));
DynamicMethodHandle mh = null;
if (!_methodCache.TryGetValue(key, out mh))
{
lock (_methodCache)
{
if (!_methodCache.TryGetValue(key, out mh))
{
var info = GetMethod(obj.GetType(), method, hasParameters, parameters);
mh = new DynamicMethodHandle(info, parameters);
_methodCache.Add(key, mh);
}
}
}
return mh;
}
#endregion
#region Dynamic Constructor Cache
private static Dictionary<Type, DynamicCtorDelegate> _ctorCache = new Dictionary<Type, DynamicCtorDelegate>();
private static DynamicCtorDelegate GetCachedConstructor(Type objectType)
{
DynamicCtorDelegate result = null;
var found = false;
try
{
found = _ctorCache.TryGetValue(objectType, out result);
}
catch
{ /* failure will drop into !found block */ }
if (!found)
{
lock (_ctorCache)
{
if (!_ctorCache.TryGetValue(objectType, out result))
{
#if NETFX_CORE
ConstructorInfo info = objectType.GetConstructor(ctorFlags, null, new Type[] { }, null);
#else
ConstructorInfo info = objectType.GetConstructor(ctorFlags, null, Type.EmptyTypes, null);
#endif
if (info == null)
throw new NotSupportedException(string.Format(
CultureInfo.CurrentCulture,
"Cannot create instance of Type '{0}'. No public parameterless constructor found.",
objectType));
result = DynamicMethodHandlerFactory.CreateConstructor(info);
_ctorCache.Add(objectType, result);
}
}
}
return result;
}
#endregion
#endif
#region GetType
/// <summary>
/// Gets a Type object based on the type name.
/// </summary>
/// <param name="typeName">Type name including assembly name.</param>
/// <param name="throwOnError">true to throw an exception if the type can't be found.</param>
/// <param name="ignoreCase">true for a case-insensitive comparison of the type name.</param>
public static Type GetType(string typeName, bool throwOnError, bool ignoreCase)
{
string fullTypeName;
#if (ANDROID || IOS) || NETFX_CORE
if (typeName.Contains("Version="))
fullTypeName = typeName;
else
fullTypeName = typeName + ", Version=..., Culture=neutral, PublicKeyToken=null";
#else
fullTypeName = typeName;
#endif
#if NETFX_CORE
if (throwOnError)
return Type.GetType(fullTypeName);
else
try
{
return Type.GetType(fullTypeName);
}
catch
{
return null;
}
#else
return Type.GetType(fullTypeName, throwOnError, ignoreCase);
#endif
}
/// <summary>
/// Gets a Type object based on the type name.
/// </summary>
/// <param name="typeName">Type name including assembly name.</param>
/// <param name="throwOnError">true to throw an exception if the type can't be found.</param>
public static Type GetType(string typeName, bool throwOnError)
{
return GetType(typeName, throwOnError, false);
}
/// <summary>
/// Gets a Type object based on the type name.
/// </summary>
/// <param name="typeName">Type name including assembly name.</param>
public static Type GetType(string typeName)
{
return GetType(typeName, true, false);
}
#endregion
#region Create Instance
/// <summary>
/// Uses reflection to create an object using its
/// default constructor.
/// </summary>
/// <param name="objectType">Type of object to create.</param>
public static object CreateInstance(Type objectType)
{
#if IOS
return Activator.CreateInstance(objectType);
#else
var ctor = GetCachedConstructor(objectType);
if (ctor == null)
throw new NotImplementedException(objectType.Name + " " + Resources.DefaultConstructor + Resources.MethodNotImplemented);
return ctor.Invoke();
#endif
}
/// <summary>
/// Creates an instance of a generic type
/// using its default constructor.
/// </summary>
/// <param name="type">Generic type to create</param>
/// <param name="paramTypes">Type parameters</param>
/// <returns></returns>
public static object CreateGenericInstance(Type type, params Type[] paramTypes)
{
var genericType = type.GetGenericTypeDefinition();
var gt = genericType.MakeGenericType(paramTypes);
return Activator.CreateInstance(gt);
}
#endregion
private const BindingFlags propertyFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy;
private const BindingFlags fieldFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
#if !IOS
private static readonly Dictionary<MethodCacheKey, DynamicMemberHandle> _memberCache = new Dictionary<MethodCacheKey, DynamicMemberHandle>();
internal static DynamicMemberHandle GetCachedProperty(Type objectType, string propertyName)
{
var key = new MethodCacheKey(objectType.FullName, propertyName, GetParameterTypes(null));
DynamicMemberHandle mh = null;
if (!_memberCache.TryGetValue(key, out mh))
{
lock (_memberCache)
{
if (!_memberCache.TryGetValue(key, out mh))
{
PropertyInfo info = objectType.GetProperty(propertyName, propertyFlags);
if (info == null)
throw new InvalidOperationException(
string.Format(Resources.MemberNotFoundException, propertyName));
mh = new DynamicMemberHandle(info);
_memberCache.Add(key, mh);
}
}
}
return mh;
}
internal static DynamicMemberHandle GetCachedField(Type objectType, string fieldName)
{
var key = new MethodCacheKey(objectType.FullName, fieldName, GetParameterTypes(null));
DynamicMemberHandle mh = null;
if (!_memberCache.TryGetValue(key, out mh))
{
lock (_memberCache)
{
if (!_memberCache.TryGetValue(key, out mh))
{
FieldInfo info = objectType.GetField(fieldName, fieldFlags);
if (info == null)
throw new InvalidOperationException(
string.Format(Resources.MemberNotFoundException, fieldName));
mh = new DynamicMemberHandle(info);
_memberCache.Add(key, mh);
}
}
}
return mh;
}
#endif
/// <summary>
/// Invokes a property getter using dynamic
/// method invocation.
/// </summary>
/// <param name="obj">Target object.</param>
/// <param name="property">Property to invoke.</param>
/// <returns></returns>
public static object CallPropertyGetter(object obj, string property)
{
#if IOS
var propertyInfo = obj.GetType().GetProperty(property);
return propertyInfo.GetValue(obj);
#else
if (obj == null)
throw new ArgumentNullException("obj");
if (string.IsNullOrEmpty(property))
throw new ArgumentException("Argument is null or empty.", "property");
var mh = GetCachedProperty(obj.GetType(), property);
if (mh.DynamicMemberGet == null)
{
throw new NotSupportedException(string.Format(
CultureInfo.CurrentCulture,
"The property '{0}' on Type '{1}' does not have a public getter.",
property,
obj.GetType()));
}
return mh.DynamicMemberGet(obj);
#endif
}
/// <summary>
/// Invokes a property setter using dynamic
/// method invocation.
/// </summary>
/// <param name="obj">Target object.</param>
/// <param name="property">Property to invoke.</param>
/// <param name="value">New value for property.</param>
public static void CallPropertySetter(object obj, string property, object value)
{
if (obj == null)
throw new ArgumentNullException("obj");
if (string.IsNullOrEmpty(property))
throw new ArgumentException("Argument is null or empty.", "property");
#if IOS
var propertyInfo = obj.GetType().GetProperty(property);
propertyInfo.SetValue(obj, value);
#else
var mh = GetCachedProperty(obj.GetType(), property);
if (mh.DynamicMemberSet == null)
{
throw new NotSupportedException(string.Format(
CultureInfo.CurrentCulture,
"The property '{0}' on Type '{1}' does not have a public setter.",
property,
obj.GetType()));
}
mh.DynamicMemberSet(obj, value);
#endif
}
#region Call Method
/// <summary>
/// Uses reflection to dynamically invoke a method
/// if that method is implemented on the target object.
/// </summary>
/// <param name="obj">
/// Object containing method.
/// </param>
/// <param name="method">
/// Name of the method.
/// </param>
public static object CallMethodIfImplemented(object obj, string method)
{
return CallMethodIfImplemented(obj, method, false, null);
}
/// <summary>
/// Uses reflection to dynamically invoke a method
/// if that method is implemented on the target object.
/// </summary>
/// <param name="obj">
/// Object containing method.
/// </param>
/// <param name="method">
/// Name of the method.
/// </param>
/// <param name="parameters">
/// Parameters to pass to method.
/// </param>
public static object CallMethodIfImplemented(object obj, string method, params object[] parameters)
{
return CallMethodIfImplemented(obj, method, true, parameters);
}
private static object CallMethodIfImplemented(object obj, string method, bool hasParameters, params object[] parameters)
{
#if IOS
var found = (FindMethod(obj.GetType(), method, GetParameterTypes(hasParameters, parameters)) != null);
if (found)
return CallMethod(obj, method, parameters);
else
return null;
#else
var mh = GetCachedMethod(obj, method, parameters);
if (mh == null || mh.DynamicMethod == null)
return null;
return CallMethod(obj, mh, hasParameters, parameters);
#endif
}
#if !IOS
/// <summary>
/// Detects if a method matching the name and parameters is implemented on the provided object.
/// </summary>
/// <param name="obj">The object implementing the method.</param>
/// <param name="method">The name of the method to find.</param>
/// <param name="parameters">The parameters matching the parameters types of the method to match.</param>
/// <returns>True obj implements a matching method.</returns>
public static bool IsMethodImplemented(object obj, string method, params object[] parameters)
{
var mh = GetCachedMethod(obj, method, parameters);
return mh != null && mh.DynamicMethod != null;
}
#endif
/// <summary>
/// Uses reflection to dynamically invoke a method,
/// throwing an exception if it is not
/// implemented on the target object.
/// </summary>
/// <param name="obj">
/// Object containing method.
/// </param>
/// <param name="method">
/// Name of the method.
/// </param>
public static object CallMethod(object obj, string method)
{
return CallMethod(obj, method, false, null);
}
/// <summary>
/// Uses reflection to dynamically invoke a method,
/// throwing an exception if it is not
/// implemented on the target object.
/// </summary>
/// <param name="obj">
/// Object containing method.
/// </param>
/// <param name="method">
/// Name of the method.
/// </param>
/// <param name="parameters">
/// Parameters to pass to method.
/// </param>
public static object CallMethod(object obj, string method, params object[] parameters)
{
return CallMethod(obj, method, true, parameters);
}
private static object CallMethod(object obj, string method, bool hasParameters, params object[] parameters)
{
#if IOS
System.Reflection.MethodInfo info = GetMethod(obj.GetType(), method, hasParameters, parameters);
if (info == null)
throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented);
return CallMethod(obj, info, hasParameters, parameters);
#else
var mh = GetCachedMethod(obj, method, hasParameters, parameters);
if (mh == null || mh.DynamicMethod == null)
throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented);
return CallMethod(obj, mh, hasParameters, parameters);
#endif
}
/// <summary>
/// Uses reflection to dynamically invoke a method,
/// throwing an exception if it is not
/// implemented on the target object.
/// </summary>
/// <param name="obj">
/// Object containing method.
/// </param>
/// <param name="info">
/// System.Reflection.MethodInfo for the method.
/// </param>
/// <param name="parameters">
/// Parameters to pass to method.
/// </param>
public static object CallMethod(object obj, System.Reflection.MethodInfo info, params object[] parameters)
{
return CallMethod(obj, info, true, parameters);
}
private static object CallMethod(object obj, System.Reflection.MethodInfo info, bool hasParameters, params object[] parameters)
{
#if IOS
var infoParams = info.GetParameters();
var infoParamsCount = infoParams.Length;
bool hasParamArray = infoParamsCount > 0 && infoParams[infoParamsCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Length > 0;
bool specialParamArray = false;
if (hasParamArray && infoParams[infoParamsCount - 1].ParameterType.Equals(typeof(string[])))
specialParamArray = true;
if (hasParamArray && infoParams[infoParamsCount - 1].ParameterType.Equals(typeof(object[])))
specialParamArray = true;
object[] par = null;
if (infoParamsCount == 1 && specialParamArray)
{
par = new object[] { parameters };
}
else if (infoParamsCount > 1 && hasParamArray && specialParamArray)
{
par = new object[infoParamsCount];
for (int i = 0; i < infoParamsCount - 1; i++)
par[i] = parameters[i];
par[infoParamsCount - 1] = parameters[infoParamsCount - 1];
}
else
{
par = parameters;
}
object result = null;
try
{
result = info.Invoke(obj, par);
}
catch (Exception e)
{
Exception inner = null;
if (e.InnerException == null)
inner = e;
else
inner = e.InnerException;
throw new CallMethodException(obj.GetType().Name + "." + info.Name + " " + Resources.MethodCallFailed, inner);
}
return result;
#else
var mh = GetCachedMethod(obj, info, parameters);
if (mh == null || mh.DynamicMethod == null)
throw new NotImplementedException(obj.GetType().Name + "." + info.Name + " " + Resources.MethodNotImplemented);
return CallMethod(obj, mh, hasParameters, parameters);
#endif
}
#if !IOS
private static object CallMethod(object obj, DynamicMethodHandle methodHandle, bool hasParameters, params object[] parameters)
{
object result = null;
var method = methodHandle.DynamicMethod;
object[] inParams = null;
if (parameters == null)
inParams = new object[] { null };
else
inParams = parameters;
if (methodHandle.HasFinalArrayParam)
{
// last param is a param array or only param is an array
var pCount = methodHandle.MethodParamsLength;
var inCount = inParams.Length;
if (inCount == pCount - 1)
{
// no paramter was supplied for the param array
// copy items into new array with last entry null
object[] paramList = new object[pCount];
for (var pos = 0; pos <= pCount - 2; pos++)
paramList[pos] = parameters[pos];
paramList[paramList.Length - 1] = hasParameters && inParams.Length == 0 ? inParams : null;
// use new array
inParams = paramList;
}
else if ((inCount == pCount && inParams[inCount - 1] != null && !inParams[inCount - 1].GetType().IsArray) || inCount > pCount)
{
// 1 or more params go in the param array
// copy extras into an array
var extras = inParams.Length - (pCount - 1);
object[] extraArray = GetExtrasArray(extras, methodHandle.FinalArrayElementType);
Array.Copy(inParams, pCount - 1, extraArray, 0, extras);
// copy items into new array
object[] paramList = new object[pCount];
for (var pos = 0; pos <= pCount - 2; pos++)
paramList[pos] = parameters[pos];
paramList[paramList.Length - 1] = extraArray;
// use new array
inParams = paramList;
}
}
try
{
result = methodHandle.DynamicMethod(obj, inParams);
}
catch (Exception ex)
{
throw new CallMethodException(obj.GetType().Name + "." + methodHandle.MethodName + " " + Resources.MethodCallFailed, ex);
}
return result;
}
#endif
private static object[] GetExtrasArray(int count, Type arrayType)
{
return (object[])(System.Array.CreateInstance(arrayType.GetElementType(), count));
}
#endregion
#region Get/Find Method
/// <summary>
/// Uses reflection to locate a matching method
/// on the target object.
/// </summary>
/// <param name="objectType">
/// Type of object containing method.
/// </param>
/// <param name="method">
/// Name of the method.
/// </param>
public static System.Reflection.MethodInfo GetMethod(Type objectType, string method)
{
return GetMethod(objectType, method, true, false, null);
}
/// <summary>
/// Uses reflection to locate a matching method
/// on the target object.
/// </summary>
/// <param name="objectType">
/// Type of object containing method.
/// </param>
/// <param name="method">
/// Name of the method.
/// </param>
/// <param name="parameters">
/// Parameters to pass to method.
/// </param>
public static System.Reflection.MethodInfo GetMethod(Type objectType, string method, params object[] parameters)
{
return GetMethod(objectType, method, true, parameters);
}
private static System.Reflection.MethodInfo GetMethod(Type objectType, string method, bool hasParameters, params object[] parameters)
{
System.Reflection.MethodInfo result = null;
object[] inParams = null;
if (!hasParameters)
inParams = new object[] { };
else if (parameters == null)
inParams = new object[] { null };
else
inParams = parameters;
// try to find a strongly typed match
// first see if there's a matching method
// where all params match types
result = FindMethod(objectType, method, GetParameterTypes(hasParameters, inParams));
if (result == null)
{
// no match found - so look for any method
// with the right number of parameters
try
{
result = FindMethod(objectType, method, inParams.Length);
}
catch (AmbiguousMatchException)
{
// we have multiple methods matching by name and parameter count
result = FindMethodUsingFuzzyMatching(objectType, method, inParams);
}
}
// no strongly typed match found, get default based on name only
if (result == null)
{
result = objectType.GetMethod(method, allLevelFlags);
}
return result;
}
private static System.Reflection.MethodInfo FindMethodUsingFuzzyMatching(Type objectType, string method, object[] parameters)
{
System.Reflection.MethodInfo result = null;
Type currentType = objectType;
do
{
System.Reflection.MethodInfo[] methods = currentType.GetMethods(oneLevelFlags);
int parameterCount = parameters.Length;
// Match based on name and parameter types and parameter arrays
foreach (System.Reflection.MethodInfo m in methods)
{
if (m.Name == method)
{
var infoParams = m.GetParameters();
var pCount = infoParams.Length;
if (pCount > 0)
{
if (pCount == 1 && infoParams[0].ParameterType.IsArray)
{
// only param is an array
if (parameters.GetType().Equals(infoParams[0].ParameterType))
{
// got a match so use it
result = m;
break;
}
}
#if NETFX_CORE
if (infoParams[pCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Count() > 0)
#else
if (infoParams[pCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Length > 0)
#endif
{
// last param is a param array
if (parameterCount == pCount && parameters[pCount - 1].GetType().Equals(infoParams[pCount - 1].ParameterType))
{
// got a match so use it
result = m;
break;
}
}
}
}
}
if (result == null)
{
// match based on parameter name and number of parameters
foreach (System.Reflection.MethodInfo m in methods)
{
if (m.Name == method && m.GetParameters().Length == parameterCount)
{
result = m;
break;
}
}
}
if (result != null)
break;
#if NETFX_CORE
currentType = currentType.BaseType();
#else
currentType = currentType.BaseType;
#endif
} while (currentType != null);
return result;
}
/// <summary>
/// Returns information about the specified
/// method, even if the parameter types are
/// generic and are located in an abstract
/// generic base class.
/// </summary>
/// <param name="objectType">
/// Type of object containing method.
/// </param>
/// <param name="method">
/// Name of the method.
/// </param>
/// <param name="types">
/// Parameter types to pass to method.
/// </param>
public static System.Reflection.MethodInfo FindMethod(Type objectType, string method, Type[] types)
{
System.Reflection.MethodInfo info = null;
do
{
// find for a strongly typed match
info = objectType.GetMethod(method, oneLevelFlags, null, types, null);
if (info != null)
{
break; // match found
}
#if NETFX_CORE
objectType = objectType.BaseType();
#else
objectType = objectType.BaseType;
#endif
} while (objectType != null);
return info;
}
/// <summary>
/// Returns information about the specified
/// method, finding the method based purely
/// on the method name and number of parameters.
/// </summary>
/// <param name="objectType">
/// Type of object containing method.
/// </param>
/// <param name="method">
/// Name of the method.
/// </param>
/// <param name="parameterCount">
/// Number of parameters to pass to method.
/// </param>
public static System.Reflection.MethodInfo FindMethod(Type objectType, string method, int parameterCount)
{
// walk up the inheritance hierarchy looking
// for a method with the right number of
// parameters
System.Reflection.MethodInfo result = null;
Type currentType = objectType;
do
{
System.Reflection.MethodInfo info = currentType.GetMethod(method, oneLevelFlags);
if (info != null)
{
var infoParams = info.GetParameters();
var pCount = infoParams.Length;
if (pCount > 0 &&
((pCount == 1 && infoParams[0].ParameterType.IsArray) ||
#if NETFX_CORE
(infoParams[pCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Count() > 0)))
#else
(infoParams[pCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Length > 0)))
#endif
{
// last param is a param array or only param is an array
if (parameterCount >= pCount - 1)
{
// got a match so use it
result = info;
break;
}
}
else if (pCount == parameterCount)
{
// got a match so use it
result = info;
break;
}
}
#if NETFX_CORE
currentType = currentType.BaseType();
#else
currentType = currentType.BaseType;
#endif
} while (currentType != null);
return result;
}
#endregion
/// <summary>
/// Returns an array of Type objects corresponding
/// to the type of parameters provided.
/// </summary>
public static Type[] GetParameterTypes()
{
return GetParameterTypes(false, null);
}
/// <summary>
/// Returns an array of Type objects corresponding
/// to the type of parameters provided.
/// </summary>
/// <param name="parameters">
/// Parameter values.
/// </param>
public static Type[] GetParameterTypes(object[] parameters)
{
return GetParameterTypes(true, parameters);
}
private static Type[] GetParameterTypes(bool hasParameters, object[] parameters)
{
if (!hasParameters)
return new Type[] { };
List<Type> result = new List<Type>();
if (parameters == null)
{
result.Add(typeof(object));
}
else
{
foreach (object item in parameters)
{
if (item == null)
{
result.Add(typeof(object));
}
else
{
result.Add(item.GetType());
}
}
}
return result.ToArray();
}
#if !(ANDROID || IOS) && !NETFX_CORE
/// <summary>
/// Gets a property type descriptor by name.
/// </summary>
/// <param name="t">Type of object containing the property.</param>
/// <param name="propertyName">Name of the property.</param>
public static PropertyDescriptor GetPropertyDescriptor(Type t, string propertyName)
{
var propertyDescriptors = TypeDescriptor.GetProperties(t);
PropertyDescriptor result = null;
foreach (PropertyDescriptor desc in propertyDescriptors)
if (desc.Name == propertyName)
{
result = desc;
break;
}
return result;
}
#endif
/// <summary>
/// Gets information about a property.
/// </summary>
/// <param name="objectType">Object containing the property.</param>
/// <param name="propertyName">Name of the property.</param>
public static PropertyInfo GetProperty(Type objectType, string propertyName)
{
return objectType.GetProperty(propertyName, propertyFlags);
}
/// <summary>
/// Gets a property value.
/// </summary>
/// <param name="obj">Object containing the property.</param>
/// <param name="info">Property info object for the property.</param>
/// <returns>The value of the property.</returns>
public static object GetPropertyValue(object obj, PropertyInfo info)
{
object result = null;
try
{
result = info.GetValue(obj, null);
}
catch (Exception e)
{
Exception inner = null;
if (e.InnerException == null)
inner = e;
else
inner = e.InnerException;
throw new CallMethodException(obj.GetType().Name + "." + info.Name + " " + Resources.MethodCallFailed, inner);
}
return result;
}
/// <summary>
/// Invokes an instance method on an object.
/// </summary>
/// <param name="obj">Object containing method.</param>
/// <param name="info">Method info object.</param>
/// <returns>Any value returned from the method.</returns>
public static object CallMethod(object obj, System.Reflection.MethodInfo info)
{
object result = null;
try
{
result = info.Invoke(obj, null);
}
catch (Exception e)
{
Exception inner = null;
if (e.InnerException == null)
inner = e;
else
inner = e.InnerException;
throw new CallMethodException(obj.GetType().Name + "." + info.Name + " " + Resources.MethodCallFailed, inner);
}
return result;
}
/// <summary>
/// Uses reflection to dynamically invoke a method,
/// throwing an exception if it is not
/// implemented on the target object.
/// </summary>
/// <param name="obj">
/// Object containing method.
/// </param>
/// <param name="method">
/// Name of the method.
/// </param>
/// <param name="parameters">
/// Parameters to pass to method.
/// </param>
public async static System.Threading.Tasks.Task<object> CallMethodTryAsync(object obj, string method, params object[] parameters)
{
return await CallMethodTryAsync(obj, method, true, parameters);
}
/// <summary>
/// Invokes an instance method on an object. If the method
/// is async returning Task of object it will be invoked using an await statement.
/// </summary>
/// <param name="obj">Object containing method.</param>
/// <param name="method">
/// Name of the method.
/// </param>
public async static System.Threading.Tasks.Task<object> CallMethodTryAsync(object obj, string method)
{
return await CallMethodTryAsync(obj, method, false, null);
}
private async static System.Threading.Tasks.Task<object> CallMethodTryAsync(object obj, string method, bool hasParameters, params object[] parameters)
{
try
{
#if IOS
var info = FindMethod(obj.GetType(), method, GetParameterTypes(hasParameters, parameters));
if (info == null)
throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented);
var isAsyncTask = (info.ReturnType == typeof(System.Threading.Tasks.Task));
var isAsyncTaskObject = (info.ReturnType.IsGenericType && (info.ReturnType.GetGenericTypeDefinition() == typeof(System.Threading.Tasks.Task<>)));
if (isAsyncTask)
{
await (System.Threading.Tasks.Task)CallMethod(obj, method, hasParameters, parameters);
return null;
}
else if (isAsyncTaskObject)
{
return await (System.Threading.Tasks.Task<object>)CallMethod(obj, method, hasParameters, parameters);
}
else
{
return CallMethod(obj, method, hasParameters, parameters);
}
#else
var mh = GetCachedMethod(obj, method, hasParameters, parameters);
if (mh == null || mh.DynamicMethod == null)
throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented);
if (mh.IsAsyncTask)
{
await (System.Threading.Tasks.Task)CallMethod(obj, mh, hasParameters, parameters);
return null;
}
else if (mh.IsAsyncTaskObject)
{
return await (System.Threading.Tasks.Task<object>)CallMethod(obj, mh, hasParameters, parameters);
}
else
{
return CallMethod(obj, mh, hasParameters, parameters);
}
#endif
}
catch (InvalidCastException ex)
{
throw new NotSupportedException(
string.Format(Resources.TaskOfObjectException, obj.GetType().Name + "." + method),
ex);
}
}
#if !NETFX_CORE
/// <summary>
/// Invokes a generic async static method by name
/// </summary>
/// <param name="objectType">Class containing static method</param>
/// <param name="method">Method to invoke</param>
/// <param name="typeParams">Type parameters for method</param>
/// <param name="hasParameters">Flag indicating whether method accepts parameters</param>
/// <param name="parameters">Parameters for method</param>
/// <returns></returns>
public static Task<object> CallGenericStaticMethodAsync(Type objectType, string method, Type[] typeParams, bool hasParameters, params object[] parameters)
{
var tcs = new TaskCompletionSource<object>();
try
{
Task task = null;
if (hasParameters)
{
var pTypes = GetParameterTypes(parameters);
var methodReference = objectType.GetMethod(method, BindingFlags.Static | BindingFlags.Public, null, CallingConventions.Any, pTypes, null);
if (methodReference == null)
methodReference = objectType.GetMethod(method, BindingFlags.Static | BindingFlags.Public);
if (methodReference == null)
throw new InvalidOperationException(objectType.Name + "." + method);
var gr = methodReference.MakeGenericMethod(typeParams);
task = (Task)gr.Invoke(null, parameters);
}
else
{
var methodReference = objectType.GetMethod(method, BindingFlags.Static | BindingFlags.Public, null, CallingConventions.Any, System.Type.EmptyTypes, null);
var gr = methodReference.MakeGenericMethod(typeParams);
task = (Task)gr.Invoke(null, null);
}
task.Wait();
if (task.Exception != null)
tcs.SetException(task.Exception);
else
tcs.SetResult(Csla.Reflection.MethodCaller.CallPropertyGetter(task, "Result"));
}
catch (Exception ex)
{
tcs.SetException(ex);
}
return tcs.Task;
}
#endif
/// <summary>
/// Invokes a static factory method.
/// </summary>
/// <param name="objectType">Business class where the factory is defined.</param>
/// <param name="method">Name of the factory method</param>
/// <param name="parameters">Parameters passed to factory method.</param>
/// <returns>Result of the factory method invocation.</returns>
public static object CallFactoryMethod(Type objectType, string method, params object[] parameters)
{
object returnValue;
System.Reflection.MethodInfo factory = objectType.GetMethod(
method, factoryFlags, null,
MethodCaller.GetParameterTypes(parameters), null);
if (factory == null)
{
// strongly typed factory couldn't be found
// so find one with the correct number of
// parameters
int parameterCount = parameters.Length;
System.Reflection.MethodInfo[] methods = objectType.GetMethods(factoryFlags);
foreach (System.Reflection.MethodInfo oneMethod in methods)
if (oneMethod.Name == method && oneMethod.GetParameters().Length == parameterCount)
{
factory = oneMethod;
break;
}
}
if (factory == null)
{
// no matching factory could be found
// so throw exception
throw new InvalidOperationException(
string.Format(Resources.NoSuchFactoryMethod, method));
}
try
{
returnValue = factory.Invoke(null, parameters);
}
catch (Exception ex)
{
Exception inner = null;
if (ex.InnerException == null)
inner = ex;
else
inner = ex.InnerException;
throw new CallMethodException(objectType.Name + "." + factory.Name + " " + Resources.MethodCallFailed, inner);
}
return returnValue;
}
/// <summary>
/// Gets a System.Reflection.MethodInfo object corresponding to a
/// non-public method.
/// </summary>
/// <param name="objectType">Object containing the method.</param>
/// <param name="method">Name of the method.</param>
public static System.Reflection.MethodInfo GetNonPublicMethod(Type objectType, string method)
{
System.Reflection.MethodInfo result = null;
result = FindMethod(objectType, method, privateMethodFlags);
return result;
}
#if !NETFX_CORE
/// <summary>
/// Returns information about the specified
/// method.
/// </summary>
/// <param name="objType">Type of object.</param>
/// <param name="method">Name of the method.</param>
/// <param name="flags">Flag values.</param>
public static System.Reflection.MethodInfo FindMethod(Type objType, string method, BindingFlags flags)
{
System.Reflection.MethodInfo info = null;
do
{
// find for a strongly typed match
info = objType.GetMethod(method, flags);
if (info != null)
break; // match found
objType = objType.BaseType;
} while (objType != null);
return info;
}
#else
/// <summary>
/// Returns information about the specified
/// method.
/// </summary>
/// <param name="objType">Type of object.</param>
/// <param name="method">Name of the method.</param>
/// <param name="flags">Flag values.</param>
public static System.Reflection.MethodInfo FindMethod(Type objType, string method, BindingFlags flags)
{
var info = objType.GetMethod(method);
return info;
}
#endif
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using gagr = Google.Api.Gax.ResourceNames;
using proto = Google.Protobuf;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.PubSub.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedSchemaServiceClientTest
{
[xunit::FactAttribute]
public void CreateSchemaRequestObject()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
CreateSchemaRequest request = new CreateSchemaRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
Schema = new Schema(),
SchemaId = "schema_idb515cf80",
};
Schema expectedResponse = new Schema
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
Type = Schema.Types.Type.Unspecified,
Definition = "definition3b8b6130",
};
mockGrpcClient.Setup(x => x.CreateSchema(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
Schema response = client.CreateSchema(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateSchemaRequestObjectAsync()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
CreateSchemaRequest request = new CreateSchemaRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
Schema = new Schema(),
SchemaId = "schema_idb515cf80",
};
Schema expectedResponse = new Schema
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
Type = Schema.Types.Type.Unspecified,
Definition = "definition3b8b6130",
};
mockGrpcClient.Setup(x => x.CreateSchemaAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Schema>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
Schema responseCallSettings = await client.CreateSchemaAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Schema responseCancellationToken = await client.CreateSchemaAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateSchema()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
CreateSchemaRequest request = new CreateSchemaRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
Schema = new Schema(),
SchemaId = "schema_idb515cf80",
};
Schema expectedResponse = new Schema
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
Type = Schema.Types.Type.Unspecified,
Definition = "definition3b8b6130",
};
mockGrpcClient.Setup(x => x.CreateSchema(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
Schema response = client.CreateSchema(request.Parent, request.Schema, request.SchemaId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateSchemaAsync()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
CreateSchemaRequest request = new CreateSchemaRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
Schema = new Schema(),
SchemaId = "schema_idb515cf80",
};
Schema expectedResponse = new Schema
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
Type = Schema.Types.Type.Unspecified,
Definition = "definition3b8b6130",
};
mockGrpcClient.Setup(x => x.CreateSchemaAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Schema>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
Schema responseCallSettings = await client.CreateSchemaAsync(request.Parent, request.Schema, request.SchemaId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Schema responseCancellationToken = await client.CreateSchemaAsync(request.Parent, request.Schema, request.SchemaId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateSchemaResourceNames()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
CreateSchemaRequest request = new CreateSchemaRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
Schema = new Schema(),
SchemaId = "schema_idb515cf80",
};
Schema expectedResponse = new Schema
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
Type = Schema.Types.Type.Unspecified,
Definition = "definition3b8b6130",
};
mockGrpcClient.Setup(x => x.CreateSchema(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
Schema response = client.CreateSchema(request.ParentAsProjectName, request.Schema, request.SchemaId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateSchemaResourceNamesAsync()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
CreateSchemaRequest request = new CreateSchemaRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
Schema = new Schema(),
SchemaId = "schema_idb515cf80",
};
Schema expectedResponse = new Schema
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
Type = Schema.Types.Type.Unspecified,
Definition = "definition3b8b6130",
};
mockGrpcClient.Setup(x => x.CreateSchemaAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Schema>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
Schema responseCallSettings = await client.CreateSchemaAsync(request.ParentAsProjectName, request.Schema, request.SchemaId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Schema responseCancellationToken = await client.CreateSchemaAsync(request.ParentAsProjectName, request.Schema, request.SchemaId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSchemaRequestObject()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
GetSchemaRequest request = new GetSchemaRequest
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
View = SchemaView.Basic,
};
Schema expectedResponse = new Schema
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
Type = Schema.Types.Type.Unspecified,
Definition = "definition3b8b6130",
};
mockGrpcClient.Setup(x => x.GetSchema(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
Schema response = client.GetSchema(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSchemaRequestObjectAsync()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
GetSchemaRequest request = new GetSchemaRequest
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
View = SchemaView.Basic,
};
Schema expectedResponse = new Schema
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
Type = Schema.Types.Type.Unspecified,
Definition = "definition3b8b6130",
};
mockGrpcClient.Setup(x => x.GetSchemaAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Schema>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
Schema responseCallSettings = await client.GetSchemaAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Schema responseCancellationToken = await client.GetSchemaAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSchema()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
GetSchemaRequest request = new GetSchemaRequest
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
};
Schema expectedResponse = new Schema
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
Type = Schema.Types.Type.Unspecified,
Definition = "definition3b8b6130",
};
mockGrpcClient.Setup(x => x.GetSchema(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
Schema response = client.GetSchema(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSchemaAsync()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
GetSchemaRequest request = new GetSchemaRequest
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
};
Schema expectedResponse = new Schema
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
Type = Schema.Types.Type.Unspecified,
Definition = "definition3b8b6130",
};
mockGrpcClient.Setup(x => x.GetSchemaAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Schema>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
Schema responseCallSettings = await client.GetSchemaAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Schema responseCancellationToken = await client.GetSchemaAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSchemaResourceNames()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
GetSchemaRequest request = new GetSchemaRequest
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
};
Schema expectedResponse = new Schema
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
Type = Schema.Types.Type.Unspecified,
Definition = "definition3b8b6130",
};
mockGrpcClient.Setup(x => x.GetSchema(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
Schema response = client.GetSchema(request.SchemaName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSchemaResourceNamesAsync()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
GetSchemaRequest request = new GetSchemaRequest
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
};
Schema expectedResponse = new Schema
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
Type = Schema.Types.Type.Unspecified,
Definition = "definition3b8b6130",
};
mockGrpcClient.Setup(x => x.GetSchemaAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Schema>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
Schema responseCallSettings = await client.GetSchemaAsync(request.SchemaName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Schema responseCancellationToken = await client.GetSchemaAsync(request.SchemaName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteSchemaRequestObject()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
DeleteSchemaRequest request = new DeleteSchemaRequest
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSchema(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteSchema(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteSchemaRequestObjectAsync()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
DeleteSchemaRequest request = new DeleteSchemaRequest
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSchemaAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteSchemaAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteSchemaAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteSchema()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
DeleteSchemaRequest request = new DeleteSchemaRequest
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSchema(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteSchema(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteSchemaAsync()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
DeleteSchemaRequest request = new DeleteSchemaRequest
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSchemaAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteSchemaAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteSchemaAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteSchemaResourceNames()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
DeleteSchemaRequest request = new DeleteSchemaRequest
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSchema(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteSchema(request.SchemaName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteSchemaResourceNamesAsync()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
DeleteSchemaRequest request = new DeleteSchemaRequest
{
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSchemaAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteSchemaAsync(request.SchemaName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteSchemaAsync(request.SchemaName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ValidateSchemaRequestObject()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
ValidateSchemaRequest request = new ValidateSchemaRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
Schema = new Schema(),
};
ValidateSchemaResponse expectedResponse = new ValidateSchemaResponse { };
mockGrpcClient.Setup(x => x.ValidateSchema(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
ValidateSchemaResponse response = client.ValidateSchema(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ValidateSchemaRequestObjectAsync()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
ValidateSchemaRequest request = new ValidateSchemaRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
Schema = new Schema(),
};
ValidateSchemaResponse expectedResponse = new ValidateSchemaResponse { };
mockGrpcClient.Setup(x => x.ValidateSchemaAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ValidateSchemaResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
ValidateSchemaResponse responseCallSettings = await client.ValidateSchemaAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ValidateSchemaResponse responseCancellationToken = await client.ValidateSchemaAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ValidateSchema()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
ValidateSchemaRequest request = new ValidateSchemaRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
Schema = new Schema(),
};
ValidateSchemaResponse expectedResponse = new ValidateSchemaResponse { };
mockGrpcClient.Setup(x => x.ValidateSchema(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
ValidateSchemaResponse response = client.ValidateSchema(request.Parent, request.Schema);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ValidateSchemaAsync()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
ValidateSchemaRequest request = new ValidateSchemaRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
Schema = new Schema(),
};
ValidateSchemaResponse expectedResponse = new ValidateSchemaResponse { };
mockGrpcClient.Setup(x => x.ValidateSchemaAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ValidateSchemaResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
ValidateSchemaResponse responseCallSettings = await client.ValidateSchemaAsync(request.Parent, request.Schema, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ValidateSchemaResponse responseCancellationToken = await client.ValidateSchemaAsync(request.Parent, request.Schema, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ValidateSchemaResourceNames()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
ValidateSchemaRequest request = new ValidateSchemaRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
Schema = new Schema(),
};
ValidateSchemaResponse expectedResponse = new ValidateSchemaResponse { };
mockGrpcClient.Setup(x => x.ValidateSchema(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
ValidateSchemaResponse response = client.ValidateSchema(request.ParentAsProjectName, request.Schema);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ValidateSchemaResourceNamesAsync()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
ValidateSchemaRequest request = new ValidateSchemaRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
Schema = new Schema(),
};
ValidateSchemaResponse expectedResponse = new ValidateSchemaResponse { };
mockGrpcClient.Setup(x => x.ValidateSchemaAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ValidateSchemaResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
ValidateSchemaResponse responseCallSettings = await client.ValidateSchemaAsync(request.ParentAsProjectName, request.Schema, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ValidateSchemaResponse responseCancellationToken = await client.ValidateSchemaAsync(request.ParentAsProjectName, request.Schema, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ValidateMessageRequestObject()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
ValidateMessageRequest request = new ValidateMessageRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
Schema = new Schema(),
Message = proto::ByteString.CopyFromUtf8("message0231e778"),
Encoding = Encoding.Json,
};
ValidateMessageResponse expectedResponse = new ValidateMessageResponse { };
mockGrpcClient.Setup(x => x.ValidateMessage(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
ValidateMessageResponse response = client.ValidateMessage(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ValidateMessageRequestObjectAsync()
{
moq::Mock<SchemaService.SchemaServiceClient> mockGrpcClient = new moq::Mock<SchemaService.SchemaServiceClient>(moq::MockBehavior.Strict);
ValidateMessageRequest request = new ValidateMessageRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
SchemaName = SchemaName.FromProjectSchema("[PROJECT]", "[SCHEMA]"),
Schema = new Schema(),
Message = proto::ByteString.CopyFromUtf8("message0231e778"),
Encoding = Encoding.Json,
};
ValidateMessageResponse expectedResponse = new ValidateMessageResponse { };
mockGrpcClient.Setup(x => x.ValidateMessageAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ValidateMessageResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SchemaServiceClient client = new SchemaServiceClientImpl(mockGrpcClient.Object, null);
ValidateMessageResponse responseCallSettings = await client.ValidateMessageAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ValidateMessageResponse responseCancellationToken = await client.ValidateMessageAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.FindSymbols;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
using System.Text;
using RefactoringEssentials.Xml;
namespace RefactoringEssentials.CSharp.Diagnostics
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class XmlDocAnalyzer : DiagnosticAnalyzer
{
static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
CSharpDiagnosticIDs.XmlDocAnalyzerID,
GettextCatalog.GetString("Validate Xml docs"),
"{0}",
DiagnosticAnalyzerCategories.CompilerWarnings,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.XmlDocAnalyzerID)
);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationStartAction(nodeContext => Analyze(nodeContext));
}
void Analyze(CompilationStartAnalysisContext compilationContext)
{
var compilation = compilationContext.Compilation;
compilationContext.RegisterSyntaxTreeAction(async delegate (SyntaxTreeAnalysisContext context)
{
try
{
if (!compilation.SyntaxTrees.Contains(context.Tree))
return;
var semanticModel = compilation.GetSemanticModel(context.Tree);
var root = await context.Tree.GetRootAsync(context.CancellationToken).ConfigureAwait(false);
var model = compilationContext.Compilation.GetSemanticModel(context.Tree);
if (model.IsFromGeneratedCode(compilationContext.CancellationToken))
return;
new GatherVisitor(context, semanticModel).Visit(root);
}
catch (OperationCanceledException) {}
});
}
class GatherVisitor : CSharpSyntaxWalker
{
readonly List<DocumentationCommentTriviaSyntax> storedXmlComment = new List<DocumentationCommentTriviaSyntax>();
readonly SyntaxTreeAnalysisContext context;
readonly StringBuilder xml = new StringBuilder();
SemanticModel semanticModel;
public GatherVisitor(SyntaxTreeAnalysisContext context, SemanticModel semanticModel)
{
this.context = context;
this.semanticModel = semanticModel;
}
public override void VisitDocumentationCommentTrivia(DocumentationCommentTriviaSyntax node)
{
storedXmlComment.Add(node);
}
void AddXmlIssue(int offset, int length, string str)
{
context.ReportDiagnostic(Diagnostic.Create(
descriptor,
Location .Create(context.Tree, new TextSpan(offset, length)),
str
));
}
void CheckForInvalid(SyntaxNode node)
{
context.CancellationToken.ThrowIfCancellationRequested();
foreach (var triva in node.GetLeadingTrivia())
{
if (triva.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia))
storedXmlComment.Add((DocumentationCommentTriviaSyntax)triva.GetStructure());
}
if (storedXmlComment.Count == 0)
return;
context.ReportDiagnostic(Diagnostic.Create(
descriptor,
Location .Create(context.Tree, storedXmlComment[0].FullSpan),
storedXmlComment.Skip(1).Select(cmt => Location .Create(context.Tree, cmt.FullSpan)),
GettextCatalog.GetString("Xml comment is not placed before a valid language element")
));
storedXmlComment.Clear();
}
public override void VisitNamespaceDeclaration(NamespaceDeclarationSyntax node)
{
CheckForInvalid(node);
base.VisitNamespaceDeclaration(node);
}
public override void VisitUsingDirective(UsingDirectiveSyntax node)
{
CheckForInvalid(node);
base.VisitUsingDirective(node);
}
public override void VisitExternAliasDirective(ExternAliasDirectiveSyntax node)
{
CheckForInvalid(node);
base.VisitExternAliasDirective(node);
}
const string firstline = "<root>\n";
class CRefVisistor : CSharpSyntaxWalker
{
GatherVisitor parent;
public CRefVisistor(GatherVisitor parent)
{
this.parent = parent;
}
public override void Visit(SyntaxNode node)
{
base.Visit(node);
}
public override void VisitNameMemberCref(NameMemberCrefSyntax node)
{
base.VisitNameMemberCref(node);
var sym = parent.semanticModel.GetSymbolInfo(node).Symbol;
if (sym == null)
parent.AddXmlIssue(node.Span.Start, node.Span.Length, string.Format(GettextCatalog.GetString("Cannot find reference '{0}'"), node.Name));
}
}
void CheckXmlDocForErrors(SyntaxNode node, ISymbol member)
{
context.CancellationToken.ThrowIfCancellationRequested();
foreach (var triva in node.GetLeadingTrivia())
{
if (triva.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia))
{
storedXmlComment.Add((DocumentationCommentTriviaSyntax)triva.GetStructure());
new CRefVisistor(this).Visit(triva.GetStructure ());
}
}
if (storedXmlComment.Count == 0)
return;
xml.Clear();
xml.Append(firstline);
List<int> OffsetTable = new List<int>();
foreach (var cmt in storedXmlComment)
{
OffsetTable.Add(xml.Length - firstline.Length);
xml.Append(cmt.Content + "\n");
}
xml.Append("</root>\n");
var doc = new AXmlParser().Parse(SourceText.From(xml.ToString()));
var stack = new Stack<AXmlObject>();
stack.Push(doc);
foreach (var err in doc.SyntaxErrors)
{
AddXmlIssue(CalculateRealStartOffset(OffsetTable, err.StartOffset), err.EndOffset - err.StartOffset, err.Description);
}
while (stack.Count > 0) {
var cur = stack.Pop();
var el = cur as AXmlElement;
if (el != null) {
switch (el.Name)
{
case "typeparam":
case "typeparamref":
var name = el.Attributes.FirstOrDefault(attr => attr.Name == "name");
if (name == null)
break;
if (member != null && member.IsKind(SymbolKind.NamedType))
{
var type = (INamedTypeSymbol)member;
if (!type.TypeArguments.Any(arg => arg.Name == name.Value))
{
AddXmlIssue(CalculateRealStartOffset(OffsetTable, name.ValueSegment.Start + 1), name.ValueSegment.Length - 2, string.Format(GettextCatalog.GetString("Type parameter '{0}' not found"), name.Value));
}
}
break;
case "param":
case "paramref":
name = el.Attributes.FirstOrDefault(attr => attr.Name == "name");
if (name == null)
break;
var m = member as IMethodSymbol;
if (m != null)
{
if (m.Parameters.Any(p => p.Name == name.Value))
break;
AddXmlIssue(CalculateRealStartOffset(OffsetTable, name.ValueSegment.Start + 1), name.ValueSegment.Length - 2, string.Format(GettextCatalog.GetString("Parameter '{0}' not found"), name.Value));
break;
}
var prop = member as IPropertySymbol;
if (prop != null)
{
if (prop.Parameters.Any(p => p.Name == name.Value))
break;
if (name.Value == "value")
break;
AddXmlIssue(CalculateRealStartOffset(OffsetTable, name.ValueSegment.Start + 1), name.ValueSegment.Length - 2, string.Format(GettextCatalog.GetString("Parameter '{0}' not found"), name.Value));
break;
}
var evt = member as IEventSymbol;
if (evt != null)
{
if (name.Value == "value")
break;
AddXmlIssue(CalculateRealStartOffset(OffsetTable, name.ValueSegment.Start + 1), name.ValueSegment.Length - 2, string.Format(GettextCatalog.GetString("Parameter '{0}' not found"), name.Value));
break;
}
AddXmlIssue(CalculateRealStartOffset(OffsetTable, name.ValueSegment.Start + 1), name.ValueSegment.Length - 2, string.Format(GettextCatalog.GetString("Parameter '{0}' not found"), name.Value));
break;
}
}
foreach (var child in cur.Children)
stack.Push(child);
}
storedXmlComment.Clear();
}
int CalculateRealStartOffset(List<int> OffsetTable, int offset)
{
int lineNumber = 0;
for (int i = 0; i < OffsetTable.Count; i++)
{
if (OffsetTable[i] > offset)
lineNumber = i - 1;
}
int realStartOffset = storedXmlComment[lineNumber].ParentTrivia.Span.Start + offset - firstline.Length - OffsetTable[lineNumber];
return realStartOffset;
}
public override void VisitClassDeclaration(ClassDeclarationSyntax node)
{
CheckXmlDocForErrors(node, semanticModel.GetDeclaredSymbol(node));
base.VisitClassDeclaration(node);
}
public override void VisitStructDeclaration(StructDeclarationSyntax node)
{
CheckXmlDocForErrors(node, semanticModel.GetDeclaredSymbol(node));
base.VisitStructDeclaration(node);
}
public override void VisitInterfaceDeclaration(InterfaceDeclarationSyntax node)
{
CheckXmlDocForErrors(node, semanticModel.GetDeclaredSymbol(node));
base.VisitInterfaceDeclaration(node);
}
public override void VisitEnumDeclaration(EnumDeclarationSyntax node)
{
CheckXmlDocForErrors(node, semanticModel.GetDeclaredSymbol(node));
base.VisitEnumDeclaration(node);
}
public override void VisitDelegateDeclaration(DelegateDeclarationSyntax node)
{
CheckXmlDocForErrors(node, semanticModel.GetDeclaredSymbol(node));
}
public override void VisitMethodDeclaration(MethodDeclarationSyntax node)
{
CheckXmlDocForErrors(node, semanticModel.GetDeclaredSymbol(node));
}
public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node)
{
CheckXmlDocForErrors(node, semanticModel.GetDeclaredSymbol(node));
}
public override void VisitEventDeclaration(EventDeclarationSyntax node)
{
CheckXmlDocForErrors(node, semanticModel.GetDeclaredSymbol(node));
}
public override void VisitEventFieldDeclaration(EventFieldDeclarationSyntax node)
{
CheckXmlDocForErrors(node, semanticModel.GetDeclaredSymbol(node.Declaration.Variables.FirstOrDefault()));
}
public override void VisitDestructorDeclaration(DestructorDeclarationSyntax node)
{
CheckXmlDocForErrors(node, semanticModel.GetDeclaredSymbol(node));
}
public override void VisitEnumMemberDeclaration(EnumMemberDeclarationSyntax node)
{
CheckXmlDocForErrors(node, semanticModel.GetDeclaredSymbol(node));
}
public override void VisitFieldDeclaration(FieldDeclarationSyntax node)
{
CheckXmlDocForErrors(node, semanticModel.GetDeclaredSymbol(node.Declaration.Variables.FirstOrDefault()));
}
public override void VisitIndexerDeclaration(IndexerDeclarationSyntax node)
{
CheckXmlDocForErrors(node, semanticModel.GetDeclaredSymbol(node));
}
public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node)
{
CheckXmlDocForErrors(node, semanticModel.GetDeclaredSymbol(node));
}
public override void VisitOperatorDeclaration(OperatorDeclarationSyntax node)
{
CheckXmlDocForErrors(node, semanticModel.GetDeclaredSymbol(node));
}
}
}
}
| |
// PreprocessorLineParser.cs
// Script#/Core/Compiler
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Collections;
using System.Diagnostics;
namespace ScriptSharp.Parser {
internal sealed class PreprocessorLineParser {
private PreprocessorLexer lexer;
private TextBuffer text;
private IDictionary defines;
private PreprocessorToken token;
public PreprocessorLineParser(NameTable symbolTable) {
lexer = new PreprocessorLexer(symbolTable);
lexer.OnError += new ErrorEventHandler(this.ReportError);
}
public event ErrorEventHandler OnError;
public PreprocessorLine ParseNextLine(TextBuffer text, IDictionary defines) {
PreprocessorLine line = null;
do {
lexer.SkipWhiteSpace();
if (lexer.EOF) {
line = new PreprocessorLine(PreprocessorTokenType.EndOfLine);
}
else if (text.PeekChar() != '#') {
lexer.IgnoreRestOfLine();
}
else {
line = Parse(text, defines);
}
} while (line == null);
return line;
}
public PreprocessorLine Parse(TextBuffer text, IDictionary defines) {
this.text = text;
this.defines = defines;
Debug.Assert(text.PeekChar() == '#');
text.NextChar();
PreprocessorToken token = NextToken();
PreprocessorTokenType type = token.Type;
switch (type) {
case PreprocessorTokenType.Define:
case PreprocessorTokenType.Undef:
token = Eat(PreprocessorTokenType.Identifier);
EatEndOfLine();
if (token != null) {
return new PreprocessorDeclarationLine(type, ((PreprocessorIdentifierToken)token).Value);
}
else {
return null;
}
case PreprocessorTokenType.Warning:
case PreprocessorTokenType.Error:
return new PreprocessorControlLine(type, lexer.GetRestOfLine());
case PreprocessorTokenType.Line:
// hidden, default
type = PeekType();
if (type == PreprocessorTokenType.Default || type == PreprocessorTokenType.Hidden) {
NextToken();
EatEndOfLine();
return new PreprocessorLine(type);
}
token = Eat(PreprocessorTokenType.Int);
if (token != null) {
int line = ((PreprocessorIntToken)token).Value;
string file = null;
if (PeekType() == PreprocessorTokenType.String) {
file = ((PreprocessorStringToken)NextToken()).Value;
}
EatEndOfLine();
return new PreprocessorLineNumberLine(line, file);
}
else {
lexer.IgnoreRestOfLine();
return null;
}
case PreprocessorTokenType.If:
case PreprocessorTokenType.Elif:
return new PreprocessorIfLine(type, EvalExpression());
case PreprocessorTokenType.Else:
case PreprocessorTokenType.Endif:
return new PreprocessorLine(type);
case PreprocessorTokenType.Region:
case PreprocessorTokenType.EndRegion:
lexer.IgnoreRestOfLine();
return new PreprocessorLine(type);
case PreprocessorTokenType.Pragma:
lexer.IgnoreRestOfLine();
return new PreprocessorLine(type);
default:
ReportError(PreprocessorError.UnexpectedDirective, token.Position);
return null;
}
}
private bool EvalExpression() {
bool value = EvalEqualsExpression();
EatEndOfLine();
return value;
}
private bool EvalEqualsExpression() {
bool value = EvalOrExpression();
PreprocessorTokenType type = PeekType();
while (type == PreprocessorTokenType.EqualEqual || type == PreprocessorTokenType.NotEqual) {
NextToken();
value = (value == EvalOrExpression());
if (type == PreprocessorTokenType.NotEqual) {
value = !value;
}
}
return value;
}
private bool EvalOrExpression() {
bool value = EvalAndExpression();
while (PeekType() == PreprocessorTokenType.Or) {
NextToken();
bool rightValue = EvalAndExpression();
value = (value || rightValue);
}
return value;
}
private bool EvalAndExpression() {
bool value = EvalUnaryExpression();
while (PeekType() == PreprocessorTokenType.And) {
NextToken();
bool rightValue = EvalUnaryExpression();
value = (value && rightValue);
}
return value;
}
private bool EvalUnaryExpression() {
if (PeekType() == PreprocessorTokenType.Not) {
NextToken();
return !EvalUnaryExpression();
}
else {
return EvalPrimaryExpression();
}
}
private bool EvalPrimaryExpression() {
bool value;
switch (PeekType()) {
case PreprocessorTokenType.OpenParen:
NextToken();
value = EvalEqualsExpression();
Eat(PreprocessorTokenType.CloseParen);
break;
case PreprocessorTokenType.True:
value = true;
NextToken();
break;
case PreprocessorTokenType.False:
value = false;
NextToken();
break;
case PreprocessorTokenType.Identifier:
value = this.defines.Contains(((PreprocessorIdentifierToken)NextToken()).Value.Text);
break;
case PreprocessorTokenType.CloseParen:
case PreprocessorTokenType.EndOfLine:
default:
ReportError(PreprocessorError.MisingPPExpression);
value = true;
break;
}
return value;
}
private void EatEndOfLine() {
if (Eat(PreprocessorTokenType.EndOfLine) == null) {
lexer.IgnoreRestOfLine();
}
}
private PreprocessorTokenType PeekType() {
if (token == null) {
token = NextToken();
}
return token.Type;
}
private PreprocessorToken NextToken() {
if (this.token == null) {
return lexer.NextToken(text);
}
else {
PreprocessorToken token = this.token;
this.token = null;
return token;
}
}
private PreprocessorToken Eat(PreprocessorTokenType type) {
if (PeekType() != type) {
ReportFormattedError(PreprocessorError.TokenExpected, PreprocessorToken.TypeString(type));
return null;
}
return NextToken();
}
private void ReportError(Error error) {
ReportError(error, token.Position);
}
private void ReportFormattedError(Error error, params object[] args) {
ReportError(error, token.Position, args);
}
private void ReportError(Error error, BufferPosition position, params object[] args) {
if (OnError != null) {
OnError(this, new ErrorEventArgs(error, position, args));
}
}
private void ReportError(object sender, ErrorEventArgs e) {
if (OnError != null) {
OnError(this, e);
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Peddler {
public class ListOfGeneratorTests {
private const int numberOfAttempts = 100;
[Fact]
public void Constructor_DefaultSizes_NullInnerGenerator() {
// Arrange
IGenerator<Object> inner = null;
// Act
var exception = Record.Exception(
() => new ListOfGenerator<Object>(inner)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Fact]
public void Constructor_ConstantSize_NullInnerGenerator() {
// Arrange
IGenerator<Object> inner = null;
// Act
var exception = Record.Exception(
() => new ListOfGenerator<Object>(inner, 10)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Fact]
public void Constructor_ConfiguredSizes_NullInnerGenerator() {
// Arrange
IGenerator<Object> inner = null;
// Act
var exception = Record.Exception(
() => new ListOfGenerator<Object>(inner, 5, 15)
);
// Assert
Assert.IsType<ArgumentNullException>(exception);
}
[Theory]
[InlineData(-1)]
[InlineData(Int32.MinValue)]
public void Constructor_NumberOfValues_LessThanZero(int numberOfValues) {
// Arrange
var inner = new StringGenerator();
// Act
var exception = Record.Exception(
() => new ListOfGenerator<String>(inner, numberOfValues)
);
// Assert
Assert.IsType<ArgumentOutOfRangeException>(exception);
Assert.Equal(
$"'numberOfValues' ({numberOfValues:N0}) must be greater " +
$"than or equal to zero, and less than Int32.MaxValue." +
Environment.NewLine + "Parameter name: numberOfValues",
exception.Message
);
}
[Theory]
[InlineData(-1)]
[InlineData(Int32.MinValue)]
[InlineData(Int32.MaxValue)]
public void Constructor_ConfiguredSizes_InvalidMinimumSize(int minimumSize) {
// Arrange
var inner = new StringGenerator();
// Act
var exception = Record.Exception(
() => new ListOfGenerator<String>(inner, minimumSize, 100)
);
// Assert
Assert.IsType<ArgumentOutOfRangeException>(exception);
Assert.Equal(
$"'minimumSize' ({minimumSize:N0}) must be greater " +
$"than or equal to zero, and less than Int32.MaxValue." +
Environment.NewLine + "Parameter name: minimumSize",
exception.Message
);
}
[Fact]
public void Constructor_ConfiguredSizes_BothAreInt32MaxValue() {
// Arrange
var inner = new StringGenerator();
// Act
var exception = Record.Exception(
() => new ListOfGenerator<String>(inner, Int32.MaxValue, Int32.MaxValue)
);
// Assert
Assert.IsType<ArgumentOutOfRangeException>(exception);
Assert.Equal(
$"'minimumSize' ({Int32.MaxValue:N0}) must be greater " +
$"than or equal to zero, and less than Int32.MaxValue." +
Environment.NewLine + "Parameter name: minimumSize",
exception.Message
);
}
[Theory]
[InlineData(-1)]
[InlineData(Int32.MinValue)]
[InlineData(Int32.MaxValue)]
public void Constructor_ConfiguredSizes_InvalidMaximumSize(int maximumSize) {
// Arrange
var inner = new StringGenerator();
// Act
var exception = Record.Exception(
() => new ListOfGenerator<String>(inner, 1, maximumSize)
);
// Assert
Assert.IsType<ArgumentOutOfRangeException>(exception);
Assert.Equal(
$"'maximumSize' ({maximumSize:N0}) must be greater " +
$"than or equal to zero, and less than Int32.MaxValue." +
Environment.NewLine + "Parameter name: maximumSize",
exception.Message
);
}
[Theory]
[InlineData(1, 0)]
[InlineData(10, 5)]
[InlineData(5, 2)]
public void Constructor_ConfiguredSizes_MinimumGreaterThanMaximum(
int minimumSize,
int maximumSize) {
// Arrange
var inner = new StringGenerator();
// Act
var exception = Record.Exception(
() => new ListOfGenerator<String>(inner, minimumSize, maximumSize)
);
// Assert
Assert.IsType<ArgumentException>(exception);
Assert.Equal(
$"The 'minimumSize' argument ({minimumSize:N0}) must not be " +
$"greater than the 'maximumSize' argument ({maximumSize:N0}).",
exception.Message
);
}
[Fact]
public void Next_DefaultsSizes() {
var generator =
new ListOfGenerator<String>(new StringGenerator());
for (var attempt = 0; attempt < numberOfAttempts; attempt++) {
var value = generator.Next();
Assert.NotNull(value);
AssertCountBetween(value, 1, 10);
AssertImmutable(value);
}
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
public void Next_ConstantSize(int numberOfValues) {
var generator =
new ListOfGenerator<String>(new StringGenerator(), numberOfValues);
for (var attempt = 0; attempt < numberOfAttempts; attempt++) {
var value = generator.Next();
Assert.NotNull(value);
AssertCountBetween(value, numberOfValues, numberOfValues);
AssertImmutable(value);
}
}
[Theory]
[InlineData(0, 0)]
[InlineData(0, 1)]
[InlineData(2, 4)]
[InlineData(1, 100)]
public void Next_ConfiguredSizes(int minimumSize, int maximumSize) {
var generator =
new ListOfGenerator<String>(new StringGenerator(), minimumSize, maximumSize);
for (var attempt = 0; attempt < numberOfAttempts; attempt++) {
var value = generator.Next();
Assert.NotNull(value);
AssertCountBetween(value, minimumSize, maximumSize);
AssertImmutable(value);
}
}
[Fact]
public async Task ThreadSafety() {
// Arrange
var generator = new ListOfGenerator<Int32>(new Int32Generator(), 0, 10);
var consecutiveZeroLengths = new ConcurrentStack<Int32>();
Action createThread =
() => this.ThreadSafetyImpl(generator, consecutiveZeroLengths);
// Act
var threads =
Enumerable
.Range(0, 10)
.Select(_ => Task.Run(createThread))
.ToArray();
await Task.WhenAll(threads);
// Assert
Assert.True(
consecutiveZeroLengths.Count < 50,
$"System.Random is not thread safe. If one of its .Next() " +
$"implementations is called simultaneously on several " +
$"threads, it breaks and starts returning zero exclusively. " +
$"The last {consecutiveZeroLengths.Count:N0} lists had " +
$"a length of zero, signifying its internal System.Random " +
$"is in a broken state."
);
}
private void ThreadSafetyImpl(
IGenerator<IList<Int32>> generator,
ConcurrentStack<Int32> consecutiveZeroLengths) {
var count = 0;
while (count++ < 10000) {
if (generator.Next().Count == 0) {
consecutiveZeroLengths.Push(0);
} else {
consecutiveZeroLengths.Clear();
}
}
}
private void AssertCountBetween<T>(IList<T> list, int low, int high) {
if (list == null) {
throw new ArgumentNullException(nameof(list));
}
Assert.True(
list.Count >= low,
$"Expected list to have a count that is greater than " +
$"or equal to {low:N0}, but it was {list.Count:N0}."
);
Assert.True(
list.Count <= high,
$"Expected list to have a count that is less than " +
$"or equal to {high:N0}, but it was {list.Count:N0}."
);
}
private void AssertImmutable(IList<String> list) {
if (list == null) {
throw new ArgumentNullException(nameof(list));
}
Assert.Throws<NotSupportedException>(
() => list.Add("Foo")
);
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using B2Lib.Enums;
using B2Lib.Exceptions;
using B2Lib.Objects;
using B2Lib.Utilities;
using Newtonsoft.Json;
namespace B2Lib.Client
{
public class B2Client
{
public string AuthorizationToken
{
get { return Communicator.AuthToken; }
private set { Communicator.AuthToken = value; }
}
public string AccountId { get; private set; }
public long MinimumPartSize { get; set; }
private readonly ConcurrentDictionary<string, ConcurrentBag<B2UploadConfiguration>> _uploadConfigsByBucket;
private readonly ConcurrentDictionary<string, ConcurrentBag<B2UploadPartConfiguration>> _uploadConfigsByLargeFile;
internal B2BucketCacher BucketCache { get; private set; }
internal B2Communicator Communicator { get; private set; }
public Uri ApiUri
{
get { return Communicator.ApiUri; }
private set { Communicator.ApiUri = value; }
}
public Uri DownloadUri
{
get { return Communicator.DownloadUri; }
private set { Communicator.DownloadUri = value; }
}
public TimeSpan TimeoutMeta
{
get { return Communicator.TimeoutMeta; }
set { Communicator.TimeoutMeta = value; }
}
public TimeSpan TimeoutData
{
get { return Communicator.TimeoutData; }
set { Communicator.TimeoutData = value; }
}
public B2Client()
{
_uploadConfigsByBucket = new ConcurrentDictionary<string, ConcurrentBag<B2UploadConfiguration>>();
_uploadConfigsByLargeFile = new ConcurrentDictionary<string, ConcurrentBag<B2UploadPartConfiguration>>();
BucketCache = new B2BucketCacher();
Communicator = new B2Communicator();
}
public void LoadState(B2SaveState state)
{
AccountId = state.AccountId;
AuthorizationToken = state.AuthorizationToken;
MinimumPartSize = state.MinimumPartSize;
ApiUri = state.ApiUrl;
DownloadUri = state.DownloadUrl;
BucketCache.LoadState(state.BucketCache);
}
public void LoadState(string file)
{
B2SaveState res = JsonConvert.DeserializeObject<B2SaveState>(File.ReadAllText(file));
LoadState(res);
}
public B2SaveState SaveState()
{
B2SaveState res = new B2SaveState();
res.AccountId = AccountId;
res.AuthorizationToken = AuthorizationToken;
res.MinimumPartSize = MinimumPartSize;
res.ApiUrl = ApiUri;
res.DownloadUrl = DownloadUri;
res.BucketCache = BucketCache.GetState();
return res;
}
public void SaveState(string file)
{
B2SaveState res = SaveState();
File.WriteAllText(file, JsonConvert.SerializeObject(res));
}
private void ThrowExceptionIfNotAuthorized()
{
if (String.IsNullOrEmpty(AccountId))
throw new B2MissingAuthenticationException("You must call Login() or LoadState() first");
}
internal void ReturnUploadConfig(B2UploadConfiguration config)
{
ConcurrentBag<B2UploadConfiguration> bag = _uploadConfigsByBucket.GetOrAdd(config.BucketId, s => new ConcurrentBag<B2UploadConfiguration>());
bag.Add(config);
}
internal void ReturnUploadConfig(B2UploadPartConfiguration config)
{
ConcurrentBag<B2UploadPartConfiguration> bag = _uploadConfigsByLargeFile.GetOrAdd(config.FileId, s => new ConcurrentBag<B2UploadPartConfiguration>());
bag.Add(config);
}
internal B2UploadConfiguration FetchUploadConfig(string bucketId)
{
ConcurrentBag<B2UploadConfiguration> bag = _uploadConfigsByBucket.GetOrAdd(bucketId, s => new ConcurrentBag<B2UploadConfiguration>());
B2UploadConfiguration config;
if (bag.TryTake(out config))
return config;
// Create new config
B2UploadConfiguration res;
try
{
res = Communicator.GetUploadUrl(bucketId).Result;
}
catch (AggregateException ex)
{
// Re-throw the inner exception
throw ex.InnerException;
}
return res;
}
internal B2UploadPartConfiguration FetchLargeFileUploadConfig(string fileId)
{
ConcurrentBag<B2UploadPartConfiguration> bag = _uploadConfigsByLargeFile.GetOrAdd(fileId, s => new ConcurrentBag<B2UploadPartConfiguration>());
B2UploadPartConfiguration config;
if (bag.TryTake(out config))
return config;
// Create new config
B2UploadPartConfiguration res;
try
{
res = Communicator.GetPartUploadUrl(fileId).Result;
}
catch (AggregateException ex)
{
// Re-throw the inner exception
throw ex.InnerException;
}
return res;
}
internal void MarkLargeFileDone(string fileId)
{
ConcurrentBag<B2UploadPartConfiguration> bag;
_uploadConfigsByLargeFile.TryRemove(fileId, out bag);
}
public async Task LoginAsync(string accountId, string applicationKey)
{
B2AuthenticationResponse result = await Communicator.AuthorizeAccount(accountId, applicationKey);
AccountId = result.AccountId;
AuthorizationToken = result.AuthorizationToken;
MinimumPartSize = result.MinimumPartSize;
ApiUri = result.ApiUrl;
DownloadUri = result.DownloadUrl;
}
public async Task<IEnumerable<B2Bucket>> GetBucketsAsync()
{
ThrowExceptionIfNotAuthorized();
List<B2BucketObject> buckets = await Communicator.ListBuckets(AccountId);
BucketCache.RecordBucket(buckets);
return buckets.Select(s => new B2Bucket(this, s));
}
public async Task<B2Bucket> CreateBucketAsync(string name, B2BucketType type)
{
ThrowExceptionIfNotAuthorized();
B2BucketObject bucket = await Communicator.CreateBucket(AccountId, name, type);
BucketCache.RecordBucket(bucket);
return new B2Bucket(this, bucket);
}
public async Task<B2Bucket> GetBucketByNameAsync(string name)
{
ThrowExceptionIfNotAuthorized();
if (BucketCache.GetByName(name) == null)
await GetBucketsAsync();
return new B2Bucket(this, BucketCache.GetByName(name));
}
public async Task<B2Bucket> GetBucketByIdAsync(string id)
{
ThrowExceptionIfNotAuthorized();
if (BucketCache.GetById(id) == null)
await GetBucketsAsync();
return new B2Bucket(this, BucketCache.GetById(id));
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// SampleCamera.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Storage;
#endregion
namespace MaterialsAndLightsSample
{
public enum SampleArcBallCameraMode
{
/// <summary>
/// A totally free-look arcball that orbits relative
/// to its orientation
/// </summary>
Free = 0,
/// <summary>
/// A camera constrained by roll so that orbits only
/// occur on latitude and longitude
/// </summary>
RollConstrained = 1
}
/// <summary>
/// An example arc ball camera
/// </summary>
public class SampleArcBallCamera
{
#region Helper Functions
/// <summary>
/// Uses a pair of keys to simulate a positive or negative axis input.
/// </summary>
public static float ReadKeyboardAxis(KeyboardState keyState, Keys downKey,
Keys upKey)
{
float value = 0;
if (keyState.IsKeyDown(downKey))
value -= 1.0f;
if (keyState.IsKeyDown(upKey))
value += 1.0f;
return value;
}
#endregion
#region Fields
/// <summary>
/// The location of the look-at target
/// </summary>
private Vector3 targetValue;
/// <summary>
/// The distance between the camera and the target
/// </summary>
private float distanceValue;
/// <summary>
/// The orientation of the camera relative to the target
/// </summary>
private Quaternion orientation;
private float inputDistanceRateValue;
private const float InputTurnRate = 3.0f;
private SampleArcBallCameraMode mode;
private float yaw, pitch;
#endregion
#region Constructors
/// <summary>
/// Create an arcball camera that allows free orbit around a target point.
/// </summary>
public SampleArcBallCamera(SampleArcBallCameraMode controlMode)
{
//orientation quaternion assumes a Pi rotation so you're facing the "front"
//of the model (looking down the +Z axis)
orientation = Quaternion.CreateFromAxisAngle(Vector3.Up, MathHelper.Pi);
mode = controlMode;
inputDistanceRateValue = 4.0f;
yaw = MathHelper.Pi;
pitch = 0;
}
#endregion
#region Calculated Camera Properties
/// <summary>
/// Get the forward direction vector of the camera.
/// </summary>
public Vector3 Direction
{
get
{
//R v R' where v = (0,0,-1,0)
//The equation can be reduced because we know the following things:
// 1. We're using unit quaternions
// 2. The initial aspect does not change
//The reduced form of the same equation follows
Vector3 dir = Vector3.Zero;
dir.X = -2.0f *
((orientation.X * orientation.Z) + (orientation.W * orientation.Y));
dir.Y = 2.0f *
((orientation.W * orientation.X) - (orientation.Y * orientation.Z));
dir.Z =
((orientation.X * orientation.X) + (orientation.Y * orientation.Y)) -
((orientation.Z * orientation.Z) + (orientation.W * orientation.W));
Vector3.Normalize(ref dir, out dir);
return dir;
}
}
/// <summary>
/// Get the right direction vector of the camera.
/// </summary>
public Vector3 Right
{
get
{
//R v R' where v = (1,0,0,0)
//The equation can be reduced because we know the following things:
// 1. We're using unit quaternions
// 2. The initial aspect does not change
//The reduced form of the same equation follows
Vector3 right = Vector3.Zero;
right.X =
((orientation.X * orientation.X) + (orientation.W * orientation.W)) -
((orientation.Z * orientation.Z) + (orientation.Y * orientation.Y));
right.Y = 2.0f *
((orientation.X * orientation.Y) + (orientation.Z * orientation.W));
right.Z = 2.0f *
((orientation.X * orientation.Z) - (orientation.Y * orientation.W));
return right;
}
}
/// <summary>
/// Get the up direction vector of the camera.
/// </summary>
public Vector3 Up
{
get
{
//R v R' where v = (0,1,0,0)
//The equation can be reduced because we know the following things:
// 1. We're using unit quaternions
// 2. The initial aspect does not change
//The reduced form of the same equation follows
Vector3 up = Vector3.Zero;
up.X = 2.0f *
((orientation.X * orientation.Y) - (orientation.Z * orientation.W));
up.Y =
((orientation.Y * orientation.Y) + (orientation.W * orientation.W)) -
((orientation.Z * orientation.Z) + (orientation.X * orientation.X));
up.Z = 2.0f *
((orientation.Y * orientation.Z) + (orientation.X * orientation.W));
return up;
}
}
/// <summary>
/// Get the View (look at) Matrix defined by the camera
/// </summary>
public Matrix ViewMatrix
{
get
{
return Matrix.CreateLookAt(targetValue -
(Direction * distanceValue), targetValue, Up);
}
}
public SampleArcBallCameraMode ControlMode
{
get { return mode; }
set
{
if (value != mode)
{
mode = value;
SetCamera(targetValue - (Direction* distanceValue),
targetValue, Vector3.Up);
}
}
}
#endregion
#region Position Controls
/// <summary>
/// Get or Set the current target of the camera
/// </summary>
public Vector3 Target
{
get
{ return targetValue; }
set
{ targetValue = value; }
}
/// <summary>
/// Get or Set the camera's distance to the target.
/// </summary>
public float Distance
{
get
{ return distanceValue; }
set
{ distanceValue = value; }
}
/// <summary>
/// Sets the rate of distance change
/// when automatically handling input
/// </summary>
public float InputDistanceRate
{
get
{ return inputDistanceRateValue; }
set
{ inputDistanceRateValue = value; }
}
/// <summary>
/// Get/Set the camera's current postion.
/// </summary>
public Vector3 Position
{
get
{
return targetValue - (Direction * Distance);
}
set
{
SetCamera(value, targetValue, Vector3.Up);
}
}
#endregion
#region Orbit Controls
/// <summary>
/// Orbit directly upwards in Free camera or on
/// the longitude line when roll constrained
/// </summary>
public void OrbitUp(float angle)
{
switch (mode)
{
case SampleArcBallCameraMode.Free:
//rotate the aspect by the angle
orientation = orientation *
Quaternion.CreateFromAxisAngle(Vector3.Right, -angle);
//normalize to reduce errors
Quaternion.Normalize(ref orientation, out orientation);
break;
case SampleArcBallCameraMode.RollConstrained:
//update the yaw
pitch -= angle;
//constrain pitch to vertical to avoid confusion
pitch = MathHelper.Clamp(pitch, -(MathHelper.PiOver2) + .0001f,
(MathHelper.PiOver2) - .0001f);
//create a new aspect based on pitch and yaw
orientation = Quaternion.CreateFromAxisAngle(Vector3.Up, -yaw) *
Quaternion.CreateFromAxisAngle(Vector3.Right, pitch);
break;
}
}
/// <summary>
/// Orbit towards the Right vector in Free camera
/// or on the latitude line when roll constrained
/// </summary>
public void OrbitRight(float angle)
{
switch (mode)
{
case SampleArcBallCameraMode.Free:
//rotate the aspect by the angle
orientation = orientation *
Quaternion.CreateFromAxisAngle(Vector3.Up, angle);
//normalize to reduce errors
Quaternion.Normalize(ref orientation, out orientation);
break;
case SampleArcBallCameraMode.RollConstrained:
//update the yaw
yaw -= angle;
//float mod yaw to avoid eventual precision errors
//as we move away from 0
yaw = yaw % MathHelper.TwoPi;
//create a new aspect based on pitch and yaw
orientation = Quaternion.CreateFromAxisAngle(Vector3.Up, -yaw) *
Quaternion.CreateFromAxisAngle(Vector3.Right, pitch);
//normalize to reduce errors
Quaternion.Normalize(ref orientation, out orientation);
break;
}
}
/// <summary>
/// Rotate around the Forward vector
/// in free-look camera only
/// </summary>
public void RotateClockwise(float angle)
{
switch (mode)
{
case SampleArcBallCameraMode.Free:
//rotate the orientation around the direction vector
orientation = orientation *
Quaternion.CreateFromAxisAngle(Vector3.Forward, angle);
Quaternion.Normalize(ref orientation, out orientation);
break;
case SampleArcBallCameraMode.RollConstrained:
//Do nothing, we don't want to roll at all to stay consistent
break;
}
}
/// <summary>
/// Sets up a quaternion & position from vector camera components
/// and oriented the camera up
/// </summary>
/// <param name="eye">The camera position</param>
/// <param name="lookAt">The camera's look-at point</param>
/// <param name="up"></param>
public void SetCamera(Vector3 position, Vector3 target, Vector3 up)
{
//Create a look at matrix, to simplify matters a bit
Matrix temp = Matrix.CreateLookAt(position, target, up);
//invert the matrix, since we're determining the
//orientation from the rotation matrix in RH coords
temp = Matrix.Invert(temp);
//set the postion
targetValue = target;
//create the new aspect from the look-at matrix
orientation = Quaternion.CreateFromRotationMatrix(temp);
//When setting a new eye-view direction
//in one of the gimble-locked modes, the yaw and
//pitch gimble must be calculated.
if (mode != SampleArcBallCameraMode.Free)
{
//first, get the direction projected on the x/z plne
Vector3 dir = Direction;
dir.Y = 0;
if (dir.Length() == 0f)
{
dir = Vector3.Forward;
}
dir.Normalize();
//find the yaw of the direction on the x/z plane
//and use the sign of the x-component since we have 360 degrees
//of freedom
yaw = (float)(Math.Acos(-dir.Z) * Math.Sign(dir.X));
//Get the pitch from the angle formed by the Up vector and the
//the forward direction, then subtracting Pi / 2, since
//we pitch is zero at Forward, not Up.
pitch = (float)-(Math.Acos(Vector3.Dot(Vector3.Up, Direction))
- MathHelper.PiOver2);
}
}
#endregion
#region Input Handlers
/// <summary>
/// Handle default keyboard input for a camera
/// </summary>
public void HandleDefaultKeyboardControls(KeyboardState kbState,
GameTime gameTime)
{
if (gameTime == null)
{
throw new ArgumentNullException("gameTime",
"GameTime parameter cannot be null.");
}
float elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
float dX = elapsedTime * ReadKeyboardAxis(
kbState, Keys.A, Keys.D) * InputTurnRate;
float dY = elapsedTime * ReadKeyboardAxis(
kbState, Keys.S, Keys.W) * InputTurnRate;
if (dY != 0) OrbitUp(dY);
if (dX != 0) OrbitRight(dX);
distanceValue += ReadKeyboardAxis(kbState, Keys.Z, Keys.X)
* inputDistanceRateValue * elapsedTime;
if (distanceValue < .001f) distanceValue = .001f;
if (mode != SampleArcBallCameraMode.Free)
{
float dR = elapsedTime * ReadKeyboardAxis(
kbState, Keys.Q, Keys.E) * InputTurnRate;
if (dR != 0) RotateClockwise(dR);
}
}
/// <summary>
/// Handle default gamepad input for a camera
/// </summary>
public void HandleDefaultGamepadControls(GamePadState gpState, GameTime gameTime)
{
if (gameTime == null)
{
throw new ArgumentNullException("gameTime",
"GameTime parameter cannot be null.");
}
if (gpState.IsConnected)
{
float elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
float dX = gpState.ThumbSticks.Right.X * elapsedTime * InputTurnRate;
float dY = gpState.ThumbSticks.Right.Y * elapsedTime * InputTurnRate;
float dR = gpState.Triggers.Right * elapsedTime * InputTurnRate;
dR-= gpState.Triggers.Left * elapsedTime * InputTurnRate;
//change orientation if necessary
if(dY != 0) OrbitUp(dY);
if(dX != 0) OrbitRight(dX);
if (dR != 0) RotateClockwise(dR);
//decrease distance to target (move forward)
if (gpState.Buttons.A == ButtonState.Pressed)
{
distanceValue -= elapsedTime * inputDistanceRateValue;
}
//increase distance to target (move back)
if (gpState.Buttons.B == ButtonState.Pressed)
{
distanceValue += elapsedTime * inputDistanceRateValue;
}
if (distanceValue < .001f) distanceValue = .001f;
}
}
#endregion
#region Misc Camera Controls
/// <summary>
/// Reset the camera to the defaults set in the constructor
/// </summary>
public void Reset()
{
//orientation quaternion assumes a Pi rotation so you're facing the "front"
//of the model (looking down the +Z axis)
orientation = Quaternion.CreateFromAxisAngle(Vector3.Up, MathHelper.Pi);
distanceValue = 3f;
targetValue = Vector3.Zero;
yaw = MathHelper.Pi;
pitch = 0;
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Inspections;
using FluentNHibernate.MappingModel;
using FluentNHibernate.MappingModel.ClassBased;
using FluentNHibernate.Utils;
using NUnit.Framework;
namespace FluentNHibernate.Testing.ConventionsTests.Inspection
{
[TestFixture, Category("Inspection DSL")]
public class DiscriminatorInspectorMapsToDiscriminatorMapping
{
private DiscriminatorMapping mapping;
private IDiscriminatorInspector inspector;
[SetUp]
public void CreateDsl()
{
mapping = new DiscriminatorMapping();
inspector = new DiscriminatorInspector(mapping);
}
[Test]
public void ColumnCollectionHasSameCountAsMapping()
{
mapping.AddColumn(new ColumnMapping());
inspector.Columns.Count().ShouldEqual(1);
}
[Test]
public void ColumnsCollectionOfInspectors()
{
mapping.AddColumn(new ColumnMapping());
inspector.Columns.First().ShouldBeOfType<IColumnInspector>();
}
[Test]
public void ColumnsCollectionIsEmpty()
{
inspector.Columns.IsEmpty().ShouldBeTrue();
}
[Test]
public void ForceMapped()
{
mapping.Force = true;
inspector.Force.ShouldBeTrue();
}
[Test]
public void ForceIsSet()
{
mapping.Force = true;
inspector.IsSet(Prop(x => x.Force))
.ShouldBeTrue();
}
[Test]
public void ForceIsNotSet()
{
inspector.IsSet(Prop(x => x.Force))
.ShouldBeFalse();
}
[Test]
public void FormulaMapped()
{
mapping.Formula = "e=mc^2";
inspector.Formula.ShouldEqual("e=mc^2");
}
[Test]
public void FormulaIsSet()
{
mapping.Formula = "e=mc^2";
inspector.IsSet(Prop(x => x.Formula))
.ShouldBeTrue();
}
[Test]
public void FormulaIsNotSet()
{
inspector.IsSet(Prop(x => x.Formula))
.ShouldBeFalse();
}
[Test]
public void InsertMapped()
{
mapping.Insert = true;
inspector.Insert.ShouldBeTrue();
}
[Test]
public void InsertIsSet()
{
mapping.Insert = true;
inspector.IsSet(Prop(x => x.Insert))
.ShouldBeTrue();
}
[Test]
public void InsertIsNotSet()
{
inspector.IsSet(Prop(x => x.Insert))
.ShouldBeFalse();
}
[Test]
public void TypeMapped()
{
mapping.Type = new TypeReference(typeof(string));
inspector.Type.ShouldEqual(new TypeReference(typeof(string)));
}
[Test]
public void TypeIsSet()
{
mapping.Type = new TypeReference(typeof(string));
inspector.IsSet(Prop(x => x.Type))
.ShouldBeTrue();
}
[Test]
public void TypeIsNotSet()
{
inspector.IsSet(Prop(x => x.Type))
.ShouldBeFalse();
}
[Test]
public void LengthMapped()
{
mapping.AddColumn(new ColumnMapping { Length = 100 });
inspector.Length.ShouldEqual(100);
}
[Test]
public void LengthIsSet()
{
mapping.AddColumn(new ColumnMapping { Length = 100 });
inspector.IsSet(Prop(x => x.Length))
.ShouldBeTrue();
}
[Test]
public void LengthIsNotSet()
{
inspector.IsSet(Prop(x => x.Length))
.ShouldBeFalse();
}
[Test]
public void PrecisionIsSet()
{
mapping.AddColumn(new ColumnMapping { Precision = 10 });
inspector.IsSet(Prop(x => x.Precision))
.ShouldBeTrue();
}
[Test]
public void PrecisionIsNotSet()
{
inspector.IsSet(Prop(x => x.Precision))
.ShouldBeFalse();
}
[Test]
public void ScaleMapped()
{
mapping.AddColumn(new ColumnMapping { Scale = 10 });
inspector.Scale.ShouldEqual(10);
}
[Test]
public void ScaleIsSet()
{
mapping.AddColumn(new ColumnMapping { Scale = 10 });
inspector.IsSet(Prop(x => x.Scale))
.ShouldBeTrue();
}
[Test]
public void ScaleIsNotSet()
{
inspector.IsSet(Prop(x => x.Scale))
.ShouldBeFalse();
}
[Test]
public void NullableMapped()
{
mapping.AddColumn(new ColumnMapping { NotNull = false });
inspector.Nullable.ShouldEqual(true);
}
[Test]
public void NullableIsSet()
{
mapping.AddColumn(new ColumnMapping { NotNull = false });
inspector.IsSet(Prop(x => x.Nullable))
.ShouldBeTrue();
}
[Test]
public void NullableIsNotSet()
{
inspector.IsSet(Prop(x => x.Nullable))
.ShouldBeFalse();
}
[Test]
public void UniqueMapped()
{
mapping.AddColumn(new ColumnMapping { Unique = true });
inspector.Unique.ShouldEqual(true);
}
[Test]
public void UniqueIsSet()
{
mapping.AddColumn(new ColumnMapping { Unique = true });
inspector.IsSet(Prop(x => x.Unique))
.ShouldBeTrue();
}
[Test]
public void UniqueIsNotSet()
{
inspector.IsSet(Prop(x => x.Unique))
.ShouldBeFalse();
}
[Test]
public void UniqueKeyMapped()
{
mapping.AddColumn(new ColumnMapping { UniqueKey = "key" });
inspector.UniqueKey.ShouldEqual("key");
}
[Test]
public void UniqueKeyIsSet()
{
mapping.AddColumn(new ColumnMapping { UniqueKey = "key" });
inspector.IsSet(Prop(x => x.UniqueKey))
.ShouldBeTrue();
}
[Test]
public void UniqueKeyIsNotSet()
{
inspector.IsSet(Prop(x => x.UniqueKey))
.ShouldBeFalse();
}
[Test]
public void SqlTypeMapped()
{
mapping.AddColumn(new ColumnMapping { SqlType = "sql" });
inspector.SqlType.ShouldEqual("sql");
}
[Test]
public void SqlTypeIsSet()
{
mapping.AddColumn(new ColumnMapping { SqlType = "sql" });
inspector.IsSet(Prop(x => x.SqlType))
.ShouldBeTrue();
}
[Test]
public void SqlTypeIsNotSet()
{
inspector.IsSet(Prop(x => x.SqlType))
.ShouldBeFalse();
}
[Test]
public void IndexMapped()
{
mapping.AddColumn(new ColumnMapping { Index = "index" });
inspector.Index.ShouldEqual("index");
}
[Test]
public void IndexIsSet()
{
mapping.AddColumn(new ColumnMapping { Index = "index" });
inspector.IsSet(Prop(x => x.Index))
.ShouldBeTrue();
}
[Test]
public void IndexIsNotSet()
{
inspector.IsSet(Prop(x => x.Index))
.ShouldBeFalse();
}
[Test]
public void CheckMapped()
{
mapping.AddColumn(new ColumnMapping { Check = "key" });
inspector.Check.ShouldEqual("key");
}
[Test]
public void CheckIsSet()
{
mapping.AddColumn(new ColumnMapping { Check = "key" });
inspector.IsSet(Prop(x => x.Check))
.ShouldBeTrue();
}
[Test]
public void CheckIsNotSet()
{
inspector.IsSet(Prop(x => x.Check))
.ShouldBeFalse();
}
[Test]
public void DefaultMapped()
{
mapping.AddColumn(new ColumnMapping { Default = "key" });
inspector.Default.ShouldEqual("key");
}
[Test]
public void DefaultIsSet()
{
mapping.AddColumn(new ColumnMapping { Default = "key" });
inspector.IsSet(Prop(x => x.Default))
.ShouldBeTrue();
}
[Test]
public void DefaultIsNotSet()
{
inspector.IsSet(Prop(x => x.Default))
.ShouldBeFalse();
}
#region Helpers
private PropertyInfo Prop(Expression<Func<IDiscriminatorInspector, object>> propertyExpression)
{
return ReflectionHelper.GetProperty(propertyExpression);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Globalization;
namespace HtmlHelp.ChmDecoding
{
/// <summary>
/// The class <c>BinaryReaderHelp</c> implements static helper methods for extracting binary data
/// from a binary reader object.
/// </summary>
internal class BinaryReaderHelp
{
/// <summary>
/// Internal helper method to extract null-terminated strings from a binary reader
/// </summary>
/// <param name="binReader">reference to the binary reader</param>
/// <param name="offset">offset in the stream</param>
/// <param name="noOffset">true if the offset value should be used</param>
/// <param name="encoder">encoder used for text encoding</param>
/// <returns>An extracted string value</returns>
internal static string ExtractString(ref BinaryReader binReader, int offset, bool noOffset, Encoding encoder)
{
string strReturn = "";
if(encoder == null)
encoder = Encoding.ASCII;
ArrayList nameBytes = new ArrayList();
byte curByte;
if(!noOffset)
binReader.BaseStream.Seek(offset, SeekOrigin.Begin);
if(binReader.BaseStream.Position >= binReader.BaseStream.Length)
return "";
curByte = binReader.ReadByte();
while( (curByte != (byte)0) && (binReader.BaseStream.Position < binReader.BaseStream.Length) )
{
nameBytes.Add( curByte );
curByte = binReader.ReadByte();
}
byte[] name = (byte[]) (nameBytes.ToArray(System.Type.GetType("System.Byte")));
strReturn = encoder.GetString(name,0,name.Length);
return strReturn;
}
/// <summary>
/// Internal helper method to extract a string with a specific length from the binary reader
/// </summary>
/// <param name="binReader">reference to the binary reader</param>
/// <param name="length">length of the string (number of bytes)</param>
/// <param name="offset">offset in the stream</param>
/// <param name="noOffset">true if the offset value should be used</param>
/// <param name="encoder">encoder used for text encoding</param>
/// <returns>An extracted string value</returns>
internal static string ExtractString(ref BinaryReader binReader, int length, int offset, bool noOffset, Encoding encoder)
{
string strReturn = "";
if(length == 0)
return "";
if(encoder == null)
encoder = Encoding.ASCII;
ArrayList nameBytes = new ArrayList();
byte curByte;
if(!noOffset)
binReader.BaseStream.Seek(offset, SeekOrigin.Begin);
if(binReader.BaseStream.Position >= binReader.BaseStream.Length)
return "";
curByte = binReader.ReadByte();
while( (curByte != (byte)0) && (nameBytes.Count < length) && (binReader.BaseStream.Position < binReader.BaseStream.Length) )
{
nameBytes.Add( curByte );
if(nameBytes.Count < length)
curByte = binReader.ReadByte();
}
byte[] name = (byte[]) (nameBytes.ToArray(System.Type.GetType("System.Byte")));
strReturn = encoder.GetString(name,0,name.Length);
return strReturn;
}
/// <summary>
/// Internal helper method to extract a string with a specific length from the binary reader
/// </summary>
/// <param name="binReader">reference to the binary reader</param>
/// <param name="bFoundTerminator">reference to a bool vairable which will receive true if the
/// string terminator \0 was found. false indicates that the end of the stream was reached.</param>
/// <param name="offset">offset in the stream</param>
/// <param name="noOffset">true if the offset value should be used</param>
/// <param name="encoder">encoder used for text encoding</param>
/// <returns>An extracted string value</returns>
internal static string ExtractString(ref BinaryReader binReader, ref bool bFoundTerminator, int offset, bool noOffset, Encoding encoder)
{
string strReturn = "";
ArrayList nameBytes = new ArrayList();
byte curByte;
if(encoder == null)
encoder = Encoding.ASCII;
if(!noOffset)
binReader.BaseStream.Seek(offset, SeekOrigin.Begin);
if(binReader.BaseStream.Position >= binReader.BaseStream.Length)
return "";
curByte = binReader.ReadByte();
while( (curByte != (byte)0) && (binReader.BaseStream.Position < binReader.BaseStream.Length) )
{
nameBytes.Add( curByte );
curByte = binReader.ReadByte();
if( curByte == (byte)0 )
{
bFoundTerminator = true;
}
}
byte[] name = (byte[]) (nameBytes.ToArray(System.Type.GetType("System.Byte")));
strReturn = encoder.GetString(name,0,name.Length);
return strReturn;
}
/// <summary>
/// Internal helper method to extract a null-terminated UTF-16/UCS-2 strings from a binary reader
/// </summary>
/// <param name="binReader">reference to the binary reader</param>
/// <param name="offset">offset in the stream</param>
/// <param name="noOffset">true if the offset value should be used</param>
/// <param name="encoder">encoder used for text encoding</param>
/// <returns>An extracted string value</returns>
internal static string ExtractUTF16String(ref BinaryReader binReader, int offset, bool noOffset, Encoding encoder)
{
string strReturn = "";
ArrayList nameBytes = new ArrayList();
byte curByte;
int lastByte=-1;
if(!noOffset)
binReader.BaseStream.Seek(offset, SeekOrigin.Begin);
if(binReader.BaseStream.Position >= binReader.BaseStream.Length)
return "";
if(encoder == null)
encoder = Encoding.Unicode;
curByte = binReader.ReadByte();
int nCnt = 0;
while( ((curByte != (byte)0) || (lastByte != 0) ) && (binReader.BaseStream.Position < binReader.BaseStream.Length) )
{
nameBytes.Add( curByte );
if(nCnt%2 == 0)
lastByte = (int)curByte;
curByte = binReader.ReadByte();
nCnt++;
}
byte[] name = (byte[]) (nameBytes.ToArray(System.Type.GetType("System.Byte")));
strReturn = Encoding.Unicode.GetString(name,0,name.Length);
// apply text encoding
name = Encoding.Default.GetBytes(strReturn);
strReturn = encoder.GetString(name);
return strReturn;
}
/// <summary>
/// Internal helper for reading ENCINT encoded integer values
/// </summary>
/// <param name="binReader">reference to the reader</param>
/// <returns>a long value</returns>
internal static long ReadENCINT(ref BinaryReader binReader)
{
long nRet = 0;
byte buffer = 0;
int shift = 0;
if(binReader.BaseStream.Position >= binReader.BaseStream.Length)
return nRet;
do
{
buffer = binReader.ReadByte();
nRet |= ((long)((buffer & (byte)0x7F))) << shift;
shift += 7;
}while ( (buffer & (byte)0x80) != 0);
return nRet;
}
/// <summary>
/// Reads an s/r encoded value from the byte array and decodes it into an integer
/// </summary>
/// <param name="wclBits">a byte array containing all bits (contains only 0 or 1 elements)</param>
/// <param name="s">scale param for encoding</param>
/// <param name="r">root param for encoding</param>
/// <param name="nBitIndex">current index in the wclBits array</param>
/// <returns>Returns an decoded integer value.</returns>
internal static int ReadSRItem(byte[] wclBits, int s, int r, ref int nBitIndex)
{
int nRet = 0;
int q = r;
int nPref1Cnt = 0;
while( wclBits[nBitIndex++] == 1)
{
nPref1Cnt++;
}
if(nPref1Cnt == 0)
{
int nMask = 0;
for(int nbits=0; nbits<q;nbits++)
{
nMask |= ( 0x01 & (int)wclBits[nBitIndex]) << (q-nbits-1);
nBitIndex++;
}
nRet = nMask;
}
else
{
q += (nPref1Cnt-1);
int nMask = 0;
int nRMaxValue = 0;
for(int nbits=0; nbits<q;nbits++)
{
nMask |= ( 0x01 & (int)wclBits[nBitIndex]) << (q-nbits-1);
nBitIndex++;
}
for(int nsv=0; nsv<r; nsv++)
{
nRMaxValue = nRMaxValue << 1;
nRMaxValue |= 0x1;
}
nRMaxValue++; // startvalue of s/r encoding with 1 prefixing '1'
nRMaxValue *= (int) Math.Pow((double)2, (double)(nPref1Cnt-1));
nRet = nRMaxValue + nMask;
}
return nRet;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Platform;
using osu.Framework.Threading;
using osu.Game.Graphics.UserInterface;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.IPC;
using osu.Game.Tournament.Models;
using osu.Game.Tournament.Screens.Gameplay.Components;
using osu.Game.Tournament.Screens.MapPool;
using osu.Game.Tournament.Screens.TeamWin;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tournament.Screens.Gameplay
{
public class GameplayScreen : BeatmapInfoScreen, IProvideVideo
{
private readonly BindableBool warmup = new BindableBool();
private readonly Bindable<TournamentMatch> currentMatch = new Bindable<TournamentMatch>();
public readonly Bindable<TourneyState> State = new Bindable<TourneyState>();
private OsuButton warmupButton;
private MatchIPCInfo ipc;
private readonly Color4 red = new Color4(186, 0, 18, 255);
private readonly Color4 blue = new Color4(17, 136, 170, 255);
[Resolved(canBeNull: true)]
private TournamentSceneManager sceneManager { get; set; }
[Resolved]
private TournamentMatchChatDisplay chat { get; set; }
[BackgroundDependencyLoader]
private void load(LadderInfo ladder, MatchIPCInfo ipc, Storage storage)
{
this.ipc = ipc;
AddRangeInternal(new Drawable[]
{
new TourneyVideo("gameplay")
{
Loop = true,
RelativeSizeAxes = Axes.Both,
},
new MatchHeader(),
new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Y = 5,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
new Box
{
// chroma key area for stable gameplay
Name = "chroma",
RelativeSizeAxes = Axes.X,
Height = 512,
Colour = new Color4(0, 255, 0, 255),
},
new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Y = -4,
Children = new Drawable[]
{
new Circle
{
Name = "top bar red",
RelativeSizeAxes = Axes.X,
Height = 8,
Width = 0.5f,
Colour = red,
},
new Circle
{
Name = "top bar blue",
RelativeSizeAxes = Axes.X,
Height = 8,
Width = 0.5f,
Colour = blue,
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
},
}
},
}
},
scoreDisplay = new MatchScoreDisplay
{
Y = -60,
Scale = new Vector2(0.8f),
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre,
},
new ControlPanel
{
Children = new Drawable[]
{
warmupButton = new TourneyButton
{
RelativeSizeAxes = Axes.X,
Text = "Toggle warmup",
Action = () => warmup.Toggle()
},
new TourneyButton
{
RelativeSizeAxes = Axes.X,
Text = "Toggle chat",
Action = () => { State.Value = State.Value == TourneyState.Idle ? TourneyState.Playing : TourneyState.Idle; }
}
}
}
});
State.BindTo(ipc.State);
State.BindValueChanged(stateChanged, true);
currentMatch.BindValueChanged(m =>
{
warmup.Value = m.NewValue.Team1Score.Value + m.NewValue.Team2Score.Value == 0;
scheduledOperation?.Cancel();
});
currentMatch.BindTo(ladder.CurrentMatch);
warmup.BindValueChanged(w => warmupButton.Alpha = !w.NewValue ? 0.5f : 1, true);
}
private ScheduledDelegate scheduledOperation;
private MatchScoreDisplay scoreDisplay;
private TourneyState lastState;
private void stateChanged(ValueChangedEvent<TourneyState> state)
{
try
{
if (state.NewValue == TourneyState.Ranking)
{
if (warmup.Value) return;
if (ipc.Score1.Value > ipc.Score2.Value)
currentMatch.Value.Team1Score.Value++;
else
currentMatch.Value.Team2Score.Value++;
}
scheduledOperation?.Cancel();
void expand()
{
chat?.Expand();
using (BeginDelayedSequence(300, true))
{
scoreDisplay.FadeIn(100);
SongBar.Expanded = true;
}
}
void contract()
{
SongBar.Expanded = false;
scoreDisplay.FadeOut(100);
using (chat?.BeginDelayedSequence(500))
chat?.Contract();
}
switch (state.NewValue)
{
case TourneyState.Idle:
contract();
const float delay_before_progression = 4000;
// if we've returned to idle and the last screen was ranking
// we should automatically proceed after a short delay
if (lastState == TourneyState.Ranking && !warmup.Value)
{
if (currentMatch.Value?.Completed.Value == true)
scheduledOperation = Scheduler.AddDelayed(() => { sceneManager?.SetScreen(typeof(TeamWinScreen)); }, delay_before_progression);
else if (currentMatch.Value?.Completed.Value == false)
scheduledOperation = Scheduler.AddDelayed(() => { sceneManager?.SetScreen(typeof(MapPoolScreen)); }, delay_before_progression);
}
break;
case TourneyState.Ranking:
scheduledOperation = Scheduler.AddDelayed(contract, 10000);
break;
default:
chat.Expand();
expand();
break;
}
}
finally
{
lastState = state.NewValue;
}
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Text.RegularExpressions;
using Axiom.MathLib;
namespace Multiverse.Serialization.Collada
{
public class Controller
{
protected GeometrySet target;
protected Matrix4 bindShapeMatrix = Matrix4.Identity;
protected string name;
public Controller( string name )
{
this.name = name;
this.bindShapeMatrix = Matrix4.Identity;
}
public GeometrySet Target
{
get { return target; }
set { target = value; }
}
public string Name
{
get { return name; }
}
public Matrix4 BindShapeMatrix
{
get { return bindShapeMatrix; }
set { bindShapeMatrix = value; }
}
}
public class RigidController : Controller
{
public string parentBone;
public RigidController( string name, string parentBone )
: base( name )
{
this.parentBone = parentBone;
}
public string ParentBone
{
get { return parentBone; }
}
}
/// <summary>
/// A SkinController supports mesh deformation by binding mesh vertices
/// to a hierarchy of transform nodes. A vertex can be associated with
/// more than one transform; it has a weight for each affecting transform.
/// </summary>
public class SkinController : Controller
{
// The input sources that will override those in the mesh geometry object.
// (e.g. bind_shape_position and bind_shape_normal vector data)
// This is a mapping from input index to list of input sources
// (which may in turn be compound sources like vertex)
public Dictionary<int, List<InputSourceCollection>> InputSources
{
get { return m_InputSources; }
}
Dictionary<int, List<InputSourceCollection>> m_InputSources;
// The inverse bind matrices for the nodes that influence this skin
// These bind matrices are interpreted in the unitless context of
// the collada file. Unit conversion will happen later.
public Dictionary<string, Matrix4> InverseBindMatrices
{
get { return m_InverseBindMatrices; }
}
Dictionary<string, Matrix4> m_InverseBindMatrices;
/// <summary>
/// A skinned mesh may also be deformed by a set of morphs. This is
/// the set of morphs applied to the skin; null if there are no morphs.
/// </summary>
public MorphController Morph
{
get { return m_Morph; }
set { m_Morph = value; }
}
MorphController m_Morph;
public SkinController( string name )
: base( name )
{
m_InputSources = new Dictionary<int, List<InputSourceCollection>>();
m_InverseBindMatrices = new Dictionary<string, Matrix4>();
}
// Get a list containing all the entries in the various input source lists
public List<InputSource> GetAllInputSources()
{
List<InputSource> sources = new List<InputSource>();
foreach( List<InputSourceCollection> tmpList in m_InputSources.Values )
{
foreach( InputSourceCollection tmp in tmpList )
{
sources.AddRange( tmp.GetSources() );
}
}
return sources;
}
}
/// <summary>
/// Provides for a linear combination of different poses, each of
/// which has the same number of vertices. I think that this
/// covers both the Axiom "morph animation" and "pose animation".
/// If method is "NORMALIZE", it's more like a morph animation.
/// <summary>
public class MorphController : Controller
{
// One of "NORMALIZED" or "RELATIVE"
public string Method
{
get { return m_Method; }
}
protected string m_Method;
// Correspondence between a semantic ("MORPH_TARGET" or "MORPH_WEIGHT") and
// the name of a source.
public Dictionary<int, List<InputSourceCollection>> InputSources
{
get { return m_InputSources; }
}
Dictionary<int, List<InputSourceCollection>> m_InputSources;
public MorphController( string name, string method )
: base( name )
{
this.m_Method = method;
m_InputSources = new Dictionary<int, List<InputSourceCollection>>();
}
public static int GetTargetAttributeIndex( string targetAttribute )
{
Regex rx = new Regex( "\\((\\d)\\)" );
Match m = rx.Match( targetAttribute );
Debug.Assert( m.Groups.Count == 2 );
return int.Parse( m.Groups[ 1 ].Value );
}
public InputSource GetInputSource( string targetComponent )
{
foreach( List<InputSourceCollection> inputs in InputSources.Values )
{
foreach( InputSourceCollection input in inputs )
{
foreach( InputSource source in input.GetSources() )
{
if( source.Source == targetComponent )
{
return source;
}
}
}
}
return null;
}
public InputSource GetInputSourceBySemantic( string semantic )
{
foreach( List<InputSourceCollection> inputs in InputSources.Values )
{
foreach( InputSourceCollection input in inputs )
{
foreach( InputSource source in input.GetSources() )
{
if( source.Semantic == semantic )
{
return source;
}
}
}
}
return null;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using Microsoft.Win32;
using System.Collections.Generic;
using KabMan.Forms;
using KabMan;
using KabMan.Data;
namespace Utils
{
public class Common
{
#region Constants
private const string REGISTRY_PATH = "Software\\KabMan\\";
#endregion
private readonly int maxx = 640;
private readonly int maxy = 480;
private RegistryKey creg;
public Common()
{
maxy = Screen.PrimaryScreen.WorkingArea.Height;
maxx = Screen.PrimaryScreen.WorkingArea.Width;
}
public static string RemoveSpaces(string str)
{
string result;
Regex regulEx = new Regex(@"[\s]+");
result = regulEx.Replace(str, " ");
return result;
}
public static string ReplaceString(string value)
{
string newValue;
if (value == String.Empty)
return value;
newValue = value.Replace("'", " ");
newValue = newValue.Replace("\"", " ");
return newValue;
}
public static int TimeConvertToMinute(TimeEdit tm)
{
DateTime dt = Convert.ToDateTime(tm.EditValue);
return dt.Hour * 60 + dt.Minute;
}
public static int TimeConvertToMinute(TimeEdit tm1, TimeEdit tm2)
{
DateTime dt = Convert.ToDateTime(tm1.EditValue);
int first = dt.Hour * 60 + dt.Minute;
dt = Convert.ToDateTime(tm2.EditValue);
int last = dt.Hour * 60 + dt.Minute;
return last - first;
}
public static object ValueControl(string fieldValue)
{
if (fieldValue != String.Empty)
return fieldValue;
else
return null;
}
public static object DBValueControl(string fieldValue)
{
if (fieldValue != String.Empty)
return fieldValue;
else
return DBNull.Value;
}
public static object DBValueControl(object fieldValue)
{
if (fieldValue != null)
return fieldValue;
else
return DBNull.Value;
}
public static void FillLookup(LookUpEdit objName, string procName, string displayMember, string valueMember)
{
objName.Properties.DataSource = DBAssistant.ExecProcedure(procName).Tables[0];
objName.Properties.DisplayMember = displayMember;
objName.Properties.ValueMember = valueMember;
}
public static void FillLookup(LookUpEdit objName, string procName, SqlParameter[] prm, string displayMember, string valueMember)
{
objName.Properties.DataSource = DBAssistant.ExecProcedure(procName, prm).Tables[0];
objName.Properties.DisplayMember = displayMember;
objName.Properties.ValueMember = valueMember;
}
public static void FillLookup(RepositoryItemLookUpEdit objName, string procName, string displayMember, string valueMember)
{
objName.DataSource = DBAssistant.ExecProcedure(procName).Tables[0];
objName.DisplayMember = displayMember;
objName.ValueMember = valueMember;
}
public static void FillLookup2(RepositoryItemLookUpEdit objName, string queryString, string displayMember, string valueMember)
{
objName.DataSource = DBAssistant.RunQuery(queryString).Tables[0];
objName.DisplayMember = displayMember;
objName.ValueMember = valueMember;
}
public static void FillLookup2(LookUpEdit objName, string queryString, string displayMember, string valueMember)
{
objName.Properties.DataSource = DBAssistant.RunQuery(queryString).Tables[0];
objName.Properties.DisplayMember = displayMember;
objName.Properties.ValueMember = valueMember;
}
public static void FillLookUpEdit(LookUpEdit argLookUpEdit, string argProcedureName, string argDisplayMember, string argValueMember)
{
FillLookUpEdit(argLookUpEdit, argProcedureName, null, argDisplayMember, argValueMember);
}
public static void FillLookUpEdit(LookUpEdit argLookUpEdit, string argProcedureName, object[] argParameters, string argDisplayMember, string argValueMember)
{
DataSet ds = DBAssistant.ExecProcedure(argProcedureName, argParameters);
argLookUpEdit.Properties.DataSource = ds.Tables[0];
argLookUpEdit.Properties.DisplayMember = argDisplayMember;
argLookUpEdit.Properties.ValueMember = argValueMember;
}
// Load/save window positions
public void SaveWinPos(XtraForm swin, string sname)
{
try
{
creg = Registry.CurrentUser.CreateSubKey(REGISTRY_PATH + "Windows\\" + sname);
creg.SetValue("Left", swin.Left, RegistryValueKind.DWord);
creg.SetValue("Top", swin.Top, RegistryValueKind.DWord);
creg.SetValue("Width", swin.Width, RegistryValueKind.DWord);
creg.SetValue("Height", swin.Height, RegistryValueKind.DWord);
creg.Close();
}
catch (Exception)
{
}
;
}
public void LoadWinPos(XtraForm swin, string sname, bool getsize)
{
try
{
creg = Registry.CurrentUser.OpenSubKey(REGISTRY_PATH + "Windows\\" + sname);
swin.Left = (int)creg.GetValue("Left", swin.Left);
swin.Top = (int)creg.GetValue("Top", swin.Top);
if (getsize)
{
swin.Width = (int)creg.GetValue("Width", swin.Width);
swin.Height = (int)creg.GetValue("Height", swin.Height);
if (swin.Width <= 32) swin.Width = 32;
if (swin.Width > maxx) swin.Width = maxx;
if (swin.Height <= 16) swin.Height = 16;
if (swin.Height > maxy) swin.Height = maxy;
}
creg.Close();
}
catch (Exception)
{
}
;
if ((swin.Top < 0) || (swin.Top > maxx)) swin.Top = 8;
if ((swin.Left < 0) || (swin.Left > maxx)) swin.Left = 8;
}
// Load/save ListView columns
public void SaveViewCols(GridView view, string sname)
{
try
{
Registry.CurrentUser.DeleteSubKeyTree(REGISTRY_PATH + "Grids\\" + sname);
}
catch (Exception)
{
}
;
try
{
creg = Registry.CurrentUser.CreateSubKey(REGISTRY_PATH + "Grids\\" + sname);
int i;
for (i = 0; i < view.Columns.Count; i++)
{
creg.SetValue("Col" + string.Format("{0:d3}", i), view.Columns[i].Width, RegistryValueKind.DWord);
}
creg.Close();
}
catch (Exception)
{
}
;
}
public void LoadViewCols(GridView view, string sname)
{
try
{
creg = Registry.CurrentUser.OpenSubKey(REGISTRY_PATH + "Grids\\" + sname);
int i;
for (i = 0; i < view.Columns.Count; i++)
{
view.Columns[i].Width =
(int)creg.GetValue("Col" + string.Format("{0:d3}", i), view.Columns[i].Width);
}
creg.Close();
}
catch (Exception)
{
}
;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Orleans.Runtime
{
internal class AssemblyLoader
{
private readonly Dictionary<string, SearchOption> dirEnumArgs;
private readonly HashSet<AssemblyLoaderPathNameCriterion> pathNameCriteria;
private readonly HashSet<AssemblyLoaderReflectionCriterion> reflectionCriteria;
private readonly ILogger logger;
internal bool SimulateExcludeCriteriaFailure { get; set; }
internal bool SimulateLoadCriteriaFailure { get; set; }
internal bool SimulateReflectionOnlyLoadFailure { get; set; }
internal bool RethrowDiscoveryExceptions { get; set; }
private AssemblyLoader(
Dictionary<string, SearchOption> dirEnumArgs,
HashSet<AssemblyLoaderPathNameCriterion> pathNameCriteria,
HashSet<AssemblyLoaderReflectionCriterion> reflectionCriteria,
ILogger logger)
{
this.dirEnumArgs = dirEnumArgs;
this.pathNameCriteria = pathNameCriteria;
this.reflectionCriteria = reflectionCriteria;
this.logger = logger;
SimulateExcludeCriteriaFailure = false;
SimulateLoadCriteriaFailure = false;
SimulateReflectionOnlyLoadFailure = false;
RethrowDiscoveryExceptions = false;
}
/// <summary>
/// Loads assemblies according to caller-defined criteria.
/// </summary>
/// <param name="dirEnumArgs">A list of arguments that are passed to Directory.EnumerateFiles().
/// The sum of the DLLs found from these searches is used as a base set of assemblies for
/// criteria to evaluate.</param>
/// <param name="pathNameCriteria">A list of criteria that are used to disqualify
/// assemblies from being loaded based on path name alone (e.g.
/// AssemblyLoaderCriteria.ExcludeFileNames) </param>
/// <param name="reflectionCriteria">A list of criteria that are used to identify
/// assemblies to be loaded based on examination of their ReflectionOnly type
/// information (e.g. AssemblyLoaderCriteria.LoadTypesAssignableFrom).</param>
/// <param name="logger">A logger to provide feedback to.</param>
/// <returns>List of discovered assemblies</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")]
public static List<Assembly> LoadAssemblies(
Dictionary<string, SearchOption> dirEnumArgs,
IEnumerable<AssemblyLoaderPathNameCriterion> pathNameCriteria,
IEnumerable<AssemblyLoaderReflectionCriterion> reflectionCriteria,
ILogger logger)
{
var loader =
NewAssemblyLoader(
dirEnumArgs,
pathNameCriteria,
reflectionCriteria,
logger);
var loadedAssemblies = new List<Assembly>();
List<string> discoveredAssemblyLocations = loader.DiscoverAssemblies();
foreach (var pathName in discoveredAssemblyLocations)
{
loader.logger.Info("Loading assembly {0}...", pathName);
// It is okay to use LoadFrom here because we are loading application assemblies deployed to the specific directory.
// Such application assemblies should not be deployed somewhere else, e.g. GAC, so this is safe.
try
{
loadedAssemblies.Add(loader.LoadAssemblyFromProbingPath(pathName));
}
catch (Exception exception)
{
loader.logger.Warn(ErrorCode.Loader_AssemblyLoadError, $"Failed to load assembly {pathName}.", exception);
}
}
loader.logger.Info("{0} assemblies loaded.", loadedAssemblies.Count);
return loadedAssemblies;
}
public static T LoadAndCreateInstance<T>(string assemblyName, ILogger logger, IServiceProvider serviceProvider) where T : class
{
try
{
var assembly = Assembly.Load(new AssemblyName(assemblyName));
var foundType = TypeUtils.GetTypes(assembly, type => typeof(T).IsAssignableFrom(type), logger).First();
return (T)ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider, foundType);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Loader_LoadAndCreateInstance_Failure, exc.Message, exc);
throw;
}
}
// this method is internal so that it can be accessed from unit tests, which only test the discovery
// process-- not the actual loading of assemblies.
internal static AssemblyLoader NewAssemblyLoader(
Dictionary<string, SearchOption> dirEnumArgs,
IEnumerable<AssemblyLoaderPathNameCriterion> pathNameCriteria,
IEnumerable<AssemblyLoaderReflectionCriterion> reflectionCriteria,
ILogger logger)
{
if (null == dirEnumArgs)
throw new ArgumentNullException("dirEnumArgs");
if (dirEnumArgs.Count == 0)
throw new ArgumentException("At least one directory is necessary in order to search for assemblies.");
HashSet<AssemblyLoaderPathNameCriterion> pathNameCriteriaSet = null == pathNameCriteria
? new HashSet<AssemblyLoaderPathNameCriterion>()
: new HashSet<AssemblyLoaderPathNameCriterion>(pathNameCriteria.Distinct());
if (null == reflectionCriteria || !reflectionCriteria.Any())
throw new ArgumentException("No assemblies will be loaded unless reflection criteria are specified.");
var reflectionCriteriaSet = new HashSet<AssemblyLoaderReflectionCriterion>(reflectionCriteria.Distinct());
if (null == logger)
throw new ArgumentNullException("logger");
return new AssemblyLoader(
dirEnumArgs,
pathNameCriteriaSet,
reflectionCriteriaSet,
logger);
}
// this method is internal so that it can be accessed from unit tests, which only test the discovery
// process-- not the actual loading of assemblies.
internal List<string> DiscoverAssemblies()
{
try
{
if (dirEnumArgs.Count == 0)
throw new InvalidOperationException("Please specify a directory to search using the AddDirectory or AddRoot methods.");
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CachedReflectionOnlyTypeResolver.OnReflectionOnlyAssemblyResolve;
// the following explicit loop ensures that the finally clause is invoked
// after we're done enumerating.
return EnumerateApprovedAssemblies();
}
finally
{
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= CachedReflectionOnlyTypeResolver.OnReflectionOnlyAssemblyResolve;
}
}
private List<string> EnumerateApprovedAssemblies()
{
var assemblies = new List<string>();
foreach (var i in dirEnumArgs)
{
var pathName = i.Key;
var searchOption = i.Value;
if (!Directory.Exists(pathName))
{
logger.Warn(ErrorCode.Loader_DirNotFound, "Unable to find directory {0}; skipping.", pathName);
continue;
}
logger.Info(
searchOption == SearchOption.TopDirectoryOnly ?
"Searching for assemblies in {0}..." :
"Recursively searching for assemblies in {0}...",
pathName);
var candidates =
Directory.EnumerateFiles(pathName, "*.dll", searchOption)
.Select(Path.GetFullPath)
.Where(p => p.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
.Distinct()
.ToArray();
// This is a workaround for the behavior of ReflectionOnlyLoad/ReflectionOnlyLoadFrom
// that appear not to automatically resolve dependencies.
// We are trying to pre-load all dlls we find in the folder, so that if one of these
// assemblies happens to be a dependency of an assembly we later on call
// Assembly.DefinedTypes on, the dependency will be already loaded and will get
// automatically resolved. Ugly, but seems to solve the problem.
foreach (var j in candidates)
{
try
{
var complaints = default(string[]);
if (IsCompatibleWithCurrentProcess(j, out complaints))
{
TryReflectionOnlyLoadFromOrFallback(j);
}
else
{
if (logger.IsEnabled(LogLevel.Information)) logger.Info("{0} is not compatible with current process, loading is skipped.", j);
}
}
catch (Exception)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Failed to pre-load assembly {0} in reflection-only context.", j);
}
}
foreach (var j in candidates)
{
if (AssemblyPassesLoadCriteria(j))
assemblies.Add(j);
}
}
return assemblies;
}
private Assembly TryReflectionOnlyLoadFromOrFallback(string assembly)
{
if (TypeUtils.CanUseReflectionOnly)
{
return Assembly.ReflectionOnlyLoadFrom(assembly);
}
return this.LoadAssemblyFromProbingPath(assembly);
}
private bool ShouldExcludeAssembly(string pathName)
{
foreach (var criterion in pathNameCriteria)
{
IEnumerable<string> complaints;
bool shouldExclude;
try
{
shouldExclude = !criterion.EvaluateCandidate(pathName, out complaints);
}
catch (Exception ex)
{
complaints = ReportUnexpectedException(ex);
if (RethrowDiscoveryExceptions)
throw;
shouldExclude = true;
}
if (shouldExclude)
{
LogComplaints(pathName, complaints);
return true;
}
}
return false;
}
private static Assembly MatchWithLoadedAssembly(AssemblyName searchFor, IEnumerable<Assembly> assemblies)
{
foreach (var assembly in assemblies)
{
var searchForFullName = searchFor.FullName;
var candidateFullName = assembly.FullName;
if (String.Equals(candidateFullName, searchForFullName, StringComparison.OrdinalIgnoreCase))
{
return assembly;
}
}
return null;
}
private static Assembly MatchWithLoadedAssembly(AssemblyName searchFor, AppDomain appDomain)
{
return
MatchWithLoadedAssembly(searchFor, appDomain.GetAssemblies()) ??
MatchWithLoadedAssembly(searchFor, appDomain.ReflectionOnlyGetAssemblies());
}
private static Assembly MatchWithLoadedAssembly(AssemblyName searchFor)
{
return MatchWithLoadedAssembly(searchFor, AppDomain.CurrentDomain);
}
private static bool InterpretFileLoadException(string asmPathName, out string[] complaints)
{
var matched = default(Assembly);
try
{
matched = MatchWithLoadedAssembly(AssemblyName.GetAssemblyName(asmPathName));
}
catch (BadImageFormatException)
{
// this can happen when System.Reflection.Metadata or System.Collections.Immutable assembly version is different (one requires the other) and there is no correct binding redirect in the app.config
complaints = null;
return false;
}
if (null == matched)
{
// something unexpected has occurred. rethrow until we know what we're catching.
complaints = null;
return false;
}
if (matched.Location != asmPathName)
{
complaints = new string[] {String.Format("A conflicting assembly has already been loaded from {0}.", matched.Location)};
// exception was anticipated.
return true;
}
// we've been asked to not log this because it's not indicative of a problem.
complaints = null;
//complaints = new string[] {"Assembly has already been loaded into current application domain."};
// exception was anticipated.
return true;
}
private string[] ReportUnexpectedException(Exception exception)
{
const string msg = "An unexpected exception occurred while attempting to load an assembly.";
logger.Error(ErrorCode.Loader_UnexpectedException, msg, exception);
return new string[] {msg};
}
private bool ReflectionOnlyLoadAssembly(string pathName, out Assembly assembly, out string[] complaints)
{
try
{
if (SimulateReflectionOnlyLoadFailure)
throw NewTestUnexpectedException();
if (IsCompatibleWithCurrentProcess(pathName, out complaints))
{
assembly = TryReflectionOnlyLoadFromOrFallback(pathName);
}
else
{
assembly = null;
return false;
}
}
catch (FileLoadException ex)
{
assembly = null;
if (!InterpretFileLoadException(pathName, out complaints))
complaints = ReportUnexpectedException(ex);
if (RethrowDiscoveryExceptions)
throw;
return false;
}
catch (Exception ex)
{
assembly = null;
complaints = ReportUnexpectedException(ex);
if (RethrowDiscoveryExceptions)
throw;
return false;
}
complaints = null;
return true;
}
private static bool IsCompatibleWithCurrentProcess(string fileName, out string[] complaints)
{
complaints = null;
Stream peImage = null;
try
{
peImage = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
using (var peReader = new PEReader(peImage, PEStreamOptions.PrefetchMetadata))
{
peImage = null;
if (peReader.HasMetadata)
{
var processorArchitecture = ProcessorArchitecture.MSIL;
var isPureIL = (peReader.PEHeaders.CorHeader.Flags & CorFlags.ILOnly) != 0;
if (peReader.PEHeaders.PEHeader.Magic == PEMagic.PE32Plus)
processorArchitecture = ProcessorArchitecture.Amd64;
else if ((peReader.PEHeaders.CorHeader.Flags & CorFlags.Requires32Bit) != 0 || !isPureIL)
processorArchitecture = ProcessorArchitecture.X86;
var isLoadable = (isPureIL && processorArchitecture == ProcessorArchitecture.MSIL) ||
(Environment.Is64BitProcess && processorArchitecture == ProcessorArchitecture.Amd64) ||
(!Environment.Is64BitProcess && processorArchitecture == ProcessorArchitecture.X86);
if (!isLoadable)
{
complaints = new[] { $"The file {fileName} is not loadable into this process, either it is not an MSIL assembly or the compliled for a different processor architecture." };
}
return isLoadable;
}
else
{
complaints = new[] { $"The file {fileName} does not contain any CLR metadata, probably it is a native file." };
return false;
}
}
}
catch (IOException)
{
return false;
}
catch (BadImageFormatException)
{
return false;
}
catch (UnauthorizedAccessException)
{
return false;
}
catch (MissingMethodException)
{
complaints = new[] { "MissingMethodException occured. Please try to add a BindingRedirect for System.Collections.ImmutableCollections to the App.config file to correct this error." };
return false;
}
catch (Exception ex)
{
complaints = new[] { LogFormatter.PrintException(ex) };
return false;
}
finally
{
peImage?.Dispose();
}
}
private void LogComplaint(string pathName, string complaint)
{
LogComplaints(pathName, new string[] { complaint });
}
private void LogComplaints(string pathName, IEnumerable<string> complaints)
{
var distinctComplaints = complaints.Distinct();
// generate feedback so that the operator can determine why her DLL didn't load.
var msg = new StringBuilder();
string bullet = Environment.NewLine + "\t* ";
msg.Append($"User assembly ignored: {pathName}");
int count = 0;
foreach (var i in distinctComplaints)
{
msg.Append(bullet);
msg.Append(i);
++count;
}
if (0 == count)
throw new InvalidOperationException("No complaint provided for assembly.");
// we can't use an error code here because we want each log message to be displayed.
logger.Info(msg.ToString());
}
private static AggregateException NewTestUnexpectedException()
{
var inner = new Exception[] { new OrleansException("Inner Exception #1"), new OrleansException("Inner Exception #2") };
return new AggregateException("Unexpected AssemblyLoader Exception Used for Unit Tests", inner);
}
private bool ShouldLoadAssembly(string pathName)
{
Assembly assembly;
string[] loadComplaints;
if (!ReflectionOnlyLoadAssembly(pathName, out assembly, out loadComplaints))
{
if (loadComplaints == null || loadComplaints.Length == 0)
return false;
LogComplaints(pathName, loadComplaints);
return false;
}
if (assembly.IsDynamic)
{
LogComplaint(pathName, "Assembly is dynamic (not supported).");
return false;
}
var criteriaComplaints = new List<string>();
foreach (var i in reflectionCriteria)
{
IEnumerable<string> complaints;
try
{
if (SimulateLoadCriteriaFailure)
throw NewTestUnexpectedException();
if (i.EvaluateCandidate(assembly, out complaints))
return true;
}
catch (Exception ex)
{
complaints = ReportUnexpectedException(ex);
if (RethrowDiscoveryExceptions)
throw;
}
criteriaComplaints.AddRange(complaints);
}
LogComplaints(pathName, criteriaComplaints);
return false;
}
private bool AssemblyPassesLoadCriteria(string pathName)
{
return !ShouldExcludeAssembly(pathName) && ShouldLoadAssembly(pathName);
}
private Assembly LoadAssemblyFromProbingPath(string path)
{
var assemblyName = GetAssemblyNameFromMetadata(path);
return Assembly.Load(assemblyName);
}
private static AssemblyName GetAssemblyNameFromMetadata(string path)
{
using (var stream = File.OpenRead(path))
using (var peFile = new PEReader(stream))
{
var reader = peFile.GetMetadataReader();
var definition = reader.GetAssemblyDefinition();
var name = reader.GetString(definition.Name);
return new AssemblyName(name);
}
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Javax.Security.Cert.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 Javax.Security.Cert
{
/// <summary>
/// <para>The exception that is thrown when a <c> Certificate </c> is not yet valid. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/CertificateNotYetValidException
/// </java-name>
[Dot42.DexImport("javax/security/cert/CertificateNotYetValidException", AccessFlags = 33)]
public partial class CertificateNotYetValidException : global::Javax.Security.Cert.CertificateException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> CertificateNotYetValidException </c> with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CertificateNotYetValidException(string msg) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> CertificateNotYetValidException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CertificateNotYetValidException() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Abstract base class for X.509 certificates. </para><para>This represents a standard way for accessing the attributes of X.509 v1 certificates. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/X509Certificate
/// </java-name>
[Dot42.DexImport("javax/security/cert/X509Certificate", AccessFlags = 1057)]
public abstract partial class X509Certificate : global::Javax.Security.Cert.Certificate
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> X509Certificate </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public X509Certificate() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> X509Certificate </c> and initializes it from the specified input stream.</para><para></para>
/// </summary>
/// <returns>
/// <para>the certificate initialized from the specified input stream </para>
/// </returns>
/// <java-name>
/// getInstance
/// </java-name>
[Dot42.DexImport("getInstance", "(Ljava/io/InputStream;)Ljavax/security/cert/X509Certificate;", AccessFlags = 25)]
public static global::Javax.Security.Cert.X509Certificate GetInstance(global::Java.Io.InputStream inStream) /* MethodBuilder.Create */
{
return default(global::Javax.Security.Cert.X509Certificate);
}
/// <summary>
/// <para>Creates a new <c> X509Certificate </c> and initializes it from the specified input stream.</para><para></para>
/// </summary>
/// <returns>
/// <para>the certificate initialized from the specified input stream </para>
/// </returns>
/// <java-name>
/// getInstance
/// </java-name>
[Dot42.DexImport("getInstance", "([B)Ljavax/security/cert/X509Certificate;", AccessFlags = 25)]
public static global::Javax.Security.Cert.X509Certificate GetInstance(sbyte[] inStream) /* MethodBuilder.Create */
{
return default(global::Javax.Security.Cert.X509Certificate);
}
/// <summary>
/// <para>Creates a new <c> X509Certificate </c> and initializes it from the specified input stream.</para><para></para>
/// </summary>
/// <returns>
/// <para>the certificate initialized from the specified input stream </para>
/// </returns>
/// <java-name>
/// getInstance
/// </java-name>
[Dot42.DexImport("getInstance", "([B)Ljavax/security/cert/X509Certificate;", AccessFlags = 25, IgnoreFromJava = true)]
public static global::Javax.Security.Cert.X509Certificate GetInstance(byte[] inStream) /* MethodBuilder.Create */
{
return default(global::Javax.Security.Cert.X509Certificate);
}
/// <summary>
/// <para>Checks whether the certificate is currently valid. </para><para>The validity defined in ASN.1:</para><para><pre>
/// validity Validity
///
/// Validity ::= SEQUENCE {
/// notBefore CertificateValidityDate,
/// notAfter CertificateValidityDate }
///
/// CertificateValidityDate ::= CHOICE {
/// utcTime UTCTime,
/// generalTime GeneralizedTime }
/// </pre></para><para></para>
/// </summary>
/// <java-name>
/// checkValidity
/// </java-name>
[Dot42.DexImport("checkValidity", "()V", AccessFlags = 1025)]
public abstract void CheckValidity() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Checks whether the certificate is valid at the specified date.</para><para><para>checkValidity() </para></para>
/// </summary>
/// <java-name>
/// checkValidity
/// </java-name>
[Dot42.DexImport("checkValidity", "(Ljava/util/Date;)V", AccessFlags = 1025)]
public abstract void CheckValidity(global::Java.Util.Date date) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the certificates <c> version </c> (version number). </para><para>The version defined is ASN.1:</para><para><pre>
/// Version ::= INTEGER { v1(0), v2(1), v3(2) }
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the version number. </para>
/// </returns>
/// <java-name>
/// getVersion
/// </java-name>
[Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)]
public abstract int GetVersion() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the <c> serialNumber </c> of the certificate. </para><para>The ASN.1 definition of <c> serialNumber </c> :</para><para><pre>
/// CertificateSerialNumber ::= INTEGER
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the serial number. </para>
/// </returns>
/// <java-name>
/// getSerialNumber
/// </java-name>
[Dot42.DexImport("getSerialNumber", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
public abstract global::Java.Math.BigInteger GetSerialNumber() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the <c> issuer </c> (issuer distinguished name) as an implementation specific <c> Principal </c> object. </para><para>The ASN.1 definition of <c> issuer </c> :</para><para><pre>
/// issuer Name
///
/// Name ::= CHOICE {
/// RDNSequence }
///
/// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
///
/// RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
///
/// AttributeTypeAndValue ::= SEQUENCE {
/// type AttributeType,
/// value AttributeValue }
///
/// AttributeType ::= OBJECT IDENTIFIER
///
/// AttributeValue ::= ANY DEFINED BY AttributeType
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the <c> issuer </c> as an implementation specific <c> Principal </c> . </para>
/// </returns>
/// <java-name>
/// getIssuerDN
/// </java-name>
[Dot42.DexImport("getIssuerDN", "()Ljava/security/Principal;", AccessFlags = 1025)]
public abstract global::Java.Security.IPrincipal GetIssuerDN() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the <c> subject </c> (subject distinguished name) as an implementation specific <c> Principal </c> object. </para><para>The ASN.1 definition of <c> subject </c> :</para><para><pre>
/// subject Name
///
/// Name ::= CHOICE {
/// RDNSequence }
///
/// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
///
/// RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
///
/// AttributeTypeAndValue ::= SEQUENCE {
/// type AttributeType,
/// value AttributeValue }
///
/// AttributeType ::= OBJECT IDENTIFIER
///
/// AttributeValue ::= ANY DEFINED BY AttributeType
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the <c> subject </c> (subject distinguished name). </para>
/// </returns>
/// <java-name>
/// getSubjectDN
/// </java-name>
[Dot42.DexImport("getSubjectDN", "()Ljava/security/Principal;", AccessFlags = 1025)]
public abstract global::Java.Security.IPrincipal GetSubjectDN() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the <c> notBefore </c> date from the validity period of the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the start of the validity period. </para>
/// </returns>
/// <java-name>
/// getNotBefore
/// </java-name>
[Dot42.DexImport("getNotBefore", "()Ljava/util/Date;", AccessFlags = 1025)]
public abstract global::Java.Util.Date GetNotBefore() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the <c> notAfter </c> date of the validity period of the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the end of the validity period. </para>
/// </returns>
/// <java-name>
/// getNotAfter
/// </java-name>
[Dot42.DexImport("getNotAfter", "()Ljava/util/Date;", AccessFlags = 1025)]
public abstract global::Java.Util.Date GetNotAfter() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the name of the algorithm for the certificate signature.</para><para></para>
/// </summary>
/// <returns>
/// <para>the signature algorithm name. </para>
/// </returns>
/// <java-name>
/// getSigAlgName
/// </java-name>
[Dot42.DexImport("getSigAlgName", "()Ljava/lang/String;", AccessFlags = 1025)]
public abstract string GetSigAlgName() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the OID of the signature algorithm from the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the OID of the signature algorithm. </para>
/// </returns>
/// <java-name>
/// getSigAlgOID
/// </java-name>
[Dot42.DexImport("getSigAlgOID", "()Ljava/lang/String;", AccessFlags = 1025)]
public abstract string GetSigAlgOID() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the parameters of the signature algorithm in DER-encoded format.</para><para></para>
/// </summary>
/// <returns>
/// <para>the parameters of the signature algorithm, or null if none are used. </para>
/// </returns>
/// <java-name>
/// getSigAlgParams
/// </java-name>
[Dot42.DexImport("getSigAlgParams", "()[B", AccessFlags = 1025)]
public abstract sbyte[] JavaGetSigAlgParams() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the parameters of the signature algorithm in DER-encoded format.</para><para></para>
/// </summary>
/// <returns>
/// <para>the parameters of the signature algorithm, or null if none are used. </para>
/// </returns>
/// <java-name>
/// getSigAlgParams
/// </java-name>
[Dot42.DexImport("getSigAlgParams", "()[B", AccessFlags = 1025, IgnoreFromJava = true)]
public abstract byte[] GetSigAlgParams() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the certificates <c> version </c> (version number). </para><para>The version defined is ASN.1:</para><para><pre>
/// Version ::= INTEGER { v1(0), v2(1), v3(2) }
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the version number. </para>
/// </returns>
/// <java-name>
/// getVersion
/// </java-name>
public int Version
{
[Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)]
get{ return GetVersion(); }
}
/// <summary>
/// <para>Returns the <c> serialNumber </c> of the certificate. </para><para>The ASN.1 definition of <c> serialNumber </c> :</para><para><pre>
/// CertificateSerialNumber ::= INTEGER
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the serial number. </para>
/// </returns>
/// <java-name>
/// getSerialNumber
/// </java-name>
public global::Java.Math.BigInteger SerialNumber
{
[Dot42.DexImport("getSerialNumber", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
get{ return GetSerialNumber(); }
}
/// <summary>
/// <para>Returns the <c> issuer </c> (issuer distinguished name) as an implementation specific <c> Principal </c> object. </para><para>The ASN.1 definition of <c> issuer </c> :</para><para><pre>
/// issuer Name
///
/// Name ::= CHOICE {
/// RDNSequence }
///
/// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
///
/// RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
///
/// AttributeTypeAndValue ::= SEQUENCE {
/// type AttributeType,
/// value AttributeValue }
///
/// AttributeType ::= OBJECT IDENTIFIER
///
/// AttributeValue ::= ANY DEFINED BY AttributeType
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the <c> issuer </c> as an implementation specific <c> Principal </c> . </para>
/// </returns>
/// <java-name>
/// getIssuerDN
/// </java-name>
public global::Java.Security.IPrincipal IssuerDN
{
[Dot42.DexImport("getIssuerDN", "()Ljava/security/Principal;", AccessFlags = 1025)]
get{ return GetIssuerDN(); }
}
/// <summary>
/// <para>Returns the <c> subject </c> (subject distinguished name) as an implementation specific <c> Principal </c> object. </para><para>The ASN.1 definition of <c> subject </c> :</para><para><pre>
/// subject Name
///
/// Name ::= CHOICE {
/// RDNSequence }
///
/// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
///
/// RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
///
/// AttributeTypeAndValue ::= SEQUENCE {
/// type AttributeType,
/// value AttributeValue }
///
/// AttributeType ::= OBJECT IDENTIFIER
///
/// AttributeValue ::= ANY DEFINED BY AttributeType
/// </pre></para><para></para>
/// </summary>
/// <returns>
/// <para>the <c> subject </c> (subject distinguished name). </para>
/// </returns>
/// <java-name>
/// getSubjectDN
/// </java-name>
public global::Java.Security.IPrincipal SubjectDN
{
[Dot42.DexImport("getSubjectDN", "()Ljava/security/Principal;", AccessFlags = 1025)]
get{ return GetSubjectDN(); }
}
/// <summary>
/// <para>Returns the <c> notBefore </c> date from the validity period of the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the start of the validity period. </para>
/// </returns>
/// <java-name>
/// getNotBefore
/// </java-name>
public global::Java.Util.Date NotBefore
{
[Dot42.DexImport("getNotBefore", "()Ljava/util/Date;", AccessFlags = 1025)]
get{ return GetNotBefore(); }
}
/// <summary>
/// <para>Returns the <c> notAfter </c> date of the validity period of the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the end of the validity period. </para>
/// </returns>
/// <java-name>
/// getNotAfter
/// </java-name>
public global::Java.Util.Date NotAfter
{
[Dot42.DexImport("getNotAfter", "()Ljava/util/Date;", AccessFlags = 1025)]
get{ return GetNotAfter(); }
}
/// <summary>
/// <para>Returns the name of the algorithm for the certificate signature.</para><para></para>
/// </summary>
/// <returns>
/// <para>the signature algorithm name. </para>
/// </returns>
/// <java-name>
/// getSigAlgName
/// </java-name>
public string SigAlgName
{
[Dot42.DexImport("getSigAlgName", "()Ljava/lang/String;", AccessFlags = 1025)]
get{ return GetSigAlgName(); }
}
/// <summary>
/// <para>Returns the OID of the signature algorithm from the certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the OID of the signature algorithm. </para>
/// </returns>
/// <java-name>
/// getSigAlgOID
/// </java-name>
public string SigAlgOID
{
[Dot42.DexImport("getSigAlgOID", "()Ljava/lang/String;", AccessFlags = 1025)]
get{ return GetSigAlgOID(); }
}
/// <summary>
/// <para>Returns the parameters of the signature algorithm in DER-encoded format.</para><para></para>
/// </summary>
/// <returns>
/// <para>the parameters of the signature algorithm, or null if none are used. </para>
/// </returns>
/// <java-name>
/// getSigAlgParams
/// </java-name>
public byte[] SigAlgParams
{
[Dot42.DexImport("getSigAlgParams", "()[B", AccessFlags = 1025, IgnoreFromJava = true)]
get{ return GetSigAlgParams(); }
}
}
/// <summary>
/// <para>The base class for all <c> Certificate </c> related exceptions. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/CertificateException
/// </java-name>
[Dot42.DexImport("javax/security/cert/CertificateException", AccessFlags = 33)]
public partial class CertificateException : global::System.Exception
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> CertificateException </c> with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CertificateException(string msg) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> CertificateException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CertificateException() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>The exception that is thrown when a <c> Certificate </c> can not be parsed. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/CertificateParsingException
/// </java-name>
[Dot42.DexImport("javax/security/cert/CertificateParsingException", AccessFlags = 33)]
public partial class CertificateParsingException : global::Javax.Security.Cert.CertificateException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> CertificateParsingException </c> with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CertificateParsingException(string msg) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> CertificateParsingException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CertificateParsingException() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Abstract class to represent identity certificates. It represents a way to verify the binding of a Principal and its public key. Examples are X.509, PGP, and SDSI. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/Certificate
/// </java-name>
[Dot42.DexImport("javax/security/cert/Certificate", AccessFlags = 1057)]
public abstract partial class Certificate
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> Certificate </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public Certificate() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Compares the argument to this Certificate. If both have the same bytes they are assumed to be equal.</para><para><para>hashCode </para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if <c> obj </c> is the same as this <c> Certificate </c> , <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)]
public override bool Equals(object obj) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns an integer hash code for the receiver. Any two objects which return <code>true</code> when passed to <code>equals</code> must answer the same value for this method.</para><para><para>equals </para></para>
/// </summary>
/// <returns>
/// <para>the receiver's hash </para>
/// </returns>
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "()I", AccessFlags = 1)]
public override int GetHashCode() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Returns the encoded representation for this certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the encoded representation for this certificate. </para>
/// </returns>
/// <java-name>
/// getEncoded
/// </java-name>
[Dot42.DexImport("getEncoded", "()[B", AccessFlags = 1025)]
public abstract sbyte[] JavaGetEncoded() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the encoded representation for this certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the encoded representation for this certificate. </para>
/// </returns>
/// <java-name>
/// getEncoded
/// </java-name>
[Dot42.DexImport("getEncoded", "()[B", AccessFlags = 1025, IgnoreFromJava = true)]
public abstract byte[] GetEncoded() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Verifies that this certificate was signed with the given public key.</para><para></para>
/// </summary>
/// <java-name>
/// verify
/// </java-name>
[Dot42.DexImport("verify", "(Ljava/security/PublicKey;)V", AccessFlags = 1025)]
public abstract void Verify(global::Java.Security.IPublicKey key) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Verifies that this certificate was signed with the given public key. Uses the signature algorithm given by the provider.</para><para></para>
/// </summary>
/// <java-name>
/// verify
/// </java-name>
[Dot42.DexImport("verify", "(Ljava/security/PublicKey;Ljava/lang/String;)V", AccessFlags = 1025)]
public abstract void Verify(global::Java.Security.IPublicKey key, string sigProvider) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns a string containing a concise, human-readable description of the receiver.</para><para></para>
/// </summary>
/// <returns>
/// <para>a printable representation for the receiver. </para>
/// </returns>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1025)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the public key corresponding to this certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the public key corresponding to this certificate. </para>
/// </returns>
/// <java-name>
/// getPublicKey
/// </java-name>
[Dot42.DexImport("getPublicKey", "()Ljava/security/PublicKey;", AccessFlags = 1025)]
public abstract global::Java.Security.IPublicKey GetPublicKey() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the encoded representation for this certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the encoded representation for this certificate. </para>
/// </returns>
/// <java-name>
/// getEncoded
/// </java-name>
public byte[] Encoded
{
[Dot42.DexImport("getEncoded", "()[B", AccessFlags = 1025, IgnoreFromJava = true)]
get{ return GetEncoded(); }
}
/// <summary>
/// <para>Returns the public key corresponding to this certificate.</para><para></para>
/// </summary>
/// <returns>
/// <para>the public key corresponding to this certificate. </para>
/// </returns>
/// <java-name>
/// getPublicKey
/// </java-name>
public global::Java.Security.IPublicKey PublicKey
{
[Dot42.DexImport("getPublicKey", "()Ljava/security/PublicKey;", AccessFlags = 1025)]
get{ return GetPublicKey(); }
}
}
/// <summary>
/// <para>The exception that is thrown when an error occurs while a <c> Certificate </c> is being encoded. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/CertificateEncodingException
/// </java-name>
[Dot42.DexImport("javax/security/cert/CertificateEncodingException", AccessFlags = 33)]
public partial class CertificateEncodingException : global::Javax.Security.Cert.CertificateException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> CertificateEncodingException </c> with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CertificateEncodingException(string msg) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> CertificateEncodingException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CertificateEncodingException() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>The exception that is thrown when a <c> Certificate </c> has expired. </para><para>Note: This package is provided only for compatibility reasons. It contains a simplified version of the java.security.cert package that was previously used by JSSE (Java SSL package). All applications that do not have to be compatible with older versions of JSSE (that is before Java SDK 1.5) should only use java.security.cert. </para>
/// </summary>
/// <java-name>
/// javax/security/cert/CertificateExpiredException
/// </java-name>
[Dot42.DexImport("javax/security/cert/CertificateExpiredException", AccessFlags = 33)]
public partial class CertificateExpiredException : global::Javax.Security.Cert.CertificateException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new <c> CertificateExpiredException </c> with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CertificateExpiredException(string msg) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new <c> CertificateExpiredException </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CertificateExpiredException() /* MethodBuilder.Create */
{
}
}
}
| |
// 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.
#pragma warning disable 0420
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// SlimManualResetEvent.cs
//
//
// An manual-reset event that mixes a little spinning with a true Win32 event.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
using System.Runtime.InteropServices;
using Internal.Runtime.Augments;
namespace System.Threading
{
// ManualResetEventSlim wraps a manual-reset event internally with a little bit of
// spinning. When an event will be set imminently, it is often advantageous to avoid
// a 4k+ cycle context switch in favor of briefly spinning. Therefore we layer on to
// a brief amount of spinning that should, on the average, make using the slim event
// cheaper than using Win32 events directly. This can be reset manually, much like
// a Win32 manual-reset would be.
//
// Notes:
// We lazily allocate the Win32 event internally. Therefore, the caller should
// always call Dispose to clean it up, just in case. This API is a no-op of the
// event wasn't allocated, but if it was, ensures that the event goes away
// eagerly, instead of waiting for finalization.
/// <summary>
/// Provides a slimmed down version of <see cref="T:System.Threading.ManualResetEvent"/>.
/// </summary>
/// <remarks>
/// All public and protected members of <see cref="ManualResetEventSlim"/> are thread-safe and may be used
/// concurrently from multiple threads, with the exception of Dispose, which
/// must only be used when all other operations on the <see cref="ManualResetEventSlim"/> have
/// completed, and Reset, which should only be used when no other threads are
/// accessing the event.
/// </remarks>
[DebuggerDisplay("Set = {IsSet}")]
public class ManualResetEventSlim : IDisposable
{
// These are the default spin counts we use on single-proc and MP machines.
private const int DEFAULT_SPIN_SP = 1;
private const int DEFAULT_SPIN_MP = 10;
private volatile Lock m_lock;
private volatile Condition m_condition;
// A lock used for waiting and pulsing. Lazily initialized via EnsureLockObjectCreated()
private volatile ManualResetEvent m_eventObj; // A true Win32 event used for waiting.
// -- State -- //
//For a packed word a uint would seem better, but Interlocked.* doesn't support them as uint isn't CLS-compliant.
private volatile int m_combinedState; //ie a UInt32. Used for the state items listed below.
//1-bit for signalled state
private const int SignalledState_BitMask = unchecked((int)0x80000000);//1000 0000 0000 0000 0000 0000 0000 0000
private const int SignalledState_ShiftCount = 31;
//1-bit for disposed state
private const int Dispose_BitMask = unchecked((int)0x40000000);//0100 0000 0000 0000 0000 0000 0000 0000
//11-bits for m_spinCount
private const int SpinCountState_BitMask = unchecked((int)0x3FF80000); //0011 1111 1111 1000 0000 0000 0000 0000
private const int SpinCountState_ShiftCount = 19;
private const int SpinCountState_MaxValue = (1 << 11) - 1; //2047
//19-bits for m_waiters. This allows support of 512K threads waiting which should be ample
private const int NumWaitersState_BitMask = unchecked((int)0x0007FFFF); // 0000 0000 0000 0111 1111 1111 1111 1111
private const int NumWaitersState_ShiftCount = 0;
private const int NumWaitersState_MaxValue = (1 << 19) - 1; //512K-1
// ----------- //
#if DEBUG
private static int s_nextId; // The next id that will be given out.
private int m_id = Interlocked.Increment(ref s_nextId); // A unique id for debugging purposes only.
private long m_lastSetTime;
private long m_lastResetTime;
#endif
/// <summary>
/// Gets the underlying <see cref="T:System.Threading.WaitHandle"/> object for this <see
/// cref="ManualResetEventSlim"/>.
/// </summary>
/// <value>The underlying <see cref="T:System.Threading.WaitHandle"/> event object fore this <see
/// cref="ManualResetEventSlim"/>.</value>
/// <remarks>
/// Accessing this property forces initialization of an underlying event object if one hasn't
/// already been created. To simply wait on this <see cref="ManualResetEventSlim"/>,
/// the public Wait methods should be preferred.
/// </remarks>
public WaitHandle WaitHandle
{
get
{
ThrowIfDisposed();
if (m_eventObj == null)
{
// Lazily initialize the event object if needed.
LazyInitializeEvent();
}
return m_eventObj;
}
}
/// <summary>
/// Gets whether the event is set.
/// </summary>
/// <value>true if the event has is set; otherwise, false.</value>
public bool IsSet
{
get
{
return 0 != ExtractStatePortion(m_combinedState, SignalledState_BitMask);
}
private set
{
UpdateStateAtomically(((value) ? 1 : 0) << SignalledState_ShiftCount, SignalledState_BitMask);
}
}
/// <summary>
/// Gets the number of spin waits that will be occur before falling back to a true wait.
/// </summary>
public int SpinCount
{
get
{
return ExtractStatePortionAndShiftRight(m_combinedState, SpinCountState_BitMask, SpinCountState_ShiftCount);
}
private set
{
Debug.Assert(value >= 0, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
Debug.Assert(value <= SpinCountState_MaxValue, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
// Don't worry about thread safety because it's set one time from the constructor
m_combinedState = (m_combinedState & ~SpinCountState_BitMask) | (value << SpinCountState_ShiftCount);
}
}
/// <summary>
/// How many threads are waiting.
/// </summary>
private int Waiters
{
get
{
return ExtractStatePortionAndShiftRight(m_combinedState, NumWaitersState_BitMask, NumWaitersState_ShiftCount);
}
set
{
//setting to <0 would indicate an internal flaw, hence Assert is appropriate.
Debug.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error.");
// it is possible for the max number of waiters to be exceeded via user-code, hence we use a real exception here.
if (value >= NumWaitersState_MaxValue)
throw new InvalidOperationException(String.Format(SR.ManualResetEventSlim_ctor_TooManyWaiters, NumWaitersState_MaxValue));
UpdateStateAtomically(value << NumWaitersState_ShiftCount, NumWaitersState_BitMask);
}
}
//-----------------------------------------------------------------------------------
// Constructs a new event, optionally specifying the initial state and spin count.
// The defaults are that the event is unsignaled and some reasonable default spin.
//
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEventSlim"/>
/// class with an initial state of nonsignaled.
/// </summary>
public ManualResetEventSlim()
: this(false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEventSlim"/>
/// class with a Boolen value indicating whether to set the intial state to signaled.
/// </summary>
/// <param name="initialState">true to set the initial state signaled; false to set the initial state
/// to nonsignaled.</param>
public ManualResetEventSlim(bool initialState)
{
// Specify the defualt spin count, and use default spin if we're
// on a multi-processor machine. Otherwise, we won't.
Initialize(initialState, DEFAULT_SPIN_MP);
}
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEventSlim"/>
/// class with a Boolen value indicating whether to set the intial state to signaled and a specified
/// spin count.
/// </summary>
/// <param name="initialState">true to set the initial state to signaled; false to set the initial state
/// to nonsignaled.</param>
/// <param name="spinCount">The number of spin waits that will occur before falling back to a true
/// wait.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="spinCount"/> is less than
/// 0 or greater than the maximum allowed value.</exception>
public ManualResetEventSlim(bool initialState, int spinCount)
{
if (spinCount < 0)
{
throw new ArgumentOutOfRangeException(nameof(spinCount));
}
if (spinCount > SpinCountState_MaxValue)
{
throw new ArgumentOutOfRangeException(
nameof(spinCount),
String.Format(SR.ManualResetEventSlim_ctor_SpinCountOutOfRange, SpinCountState_MaxValue));
}
// We will suppress default spin because the user specified a count.
Initialize(initialState, spinCount);
}
/// <summary>
/// Initializes the internal state of the event.
/// </summary>
/// <param name="initialState">Whether the event is set initially or not.</param>
/// <param name="spinCount">The spin count that decides when the event will block.</param>
private void Initialize(bool initialState, int spinCount)
{
m_combinedState = initialState ? (1 << SignalledState_ShiftCount) : 0;
//the spinCount argument has been validated by the ctors.
//but we now sanity check our predefined constants.
Debug.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
Debug.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
SpinCount = PlatformHelper.IsSingleProcessor ? DEFAULT_SPIN_SP : spinCount;
}
/// <summary>
/// Helper to ensure the lock object is created before first use.
/// </summary>
private void EnsureLockObjectCreated()
{
if (m_lock == null)
{
Lock newObj = new Lock();
Interlocked.CompareExchange(ref m_lock, newObj, null); // failure is benign.. someone else won the race.
}
if (m_condition == null)
{
Condition newCond = new Condition(m_lock);
Interlocked.CompareExchange(ref m_condition, newCond, null);
}
}
/// <summary>
/// This method lazily initializes the event object. It uses CAS to guarantee that
/// many threads racing to call this at once don't result in more than one event
/// being stored and used. The event will be signaled or unsignaled depending on
/// the state of the thin-event itself, with synchronization taken into account.
/// </summary>
/// <returns>True if a new event was created and stored, false otherwise.</returns>
private bool LazyInitializeEvent()
{
bool preInitializeIsSet = IsSet;
ManualResetEvent newEventObj = new ManualResetEvent(preInitializeIsSet);
// We have to CAS this in case we are racing with another thread. We must
// guarantee only one event is actually stored in this field.
if (Interlocked.CompareExchange(ref m_eventObj, newEventObj, null) != null)
{
// We raced with someone else and lost. Destroy the garbage event.
newEventObj.Dispose();
return false;
}
else
{
// Now that the event is published, verify that the state hasn't changed since
// we snapped the preInitializeState. Another thread could have done that
// between our initial observation above and here. The barrier incurred from
// the CAS above (in addition to m_state being volatile) prevents this read
// from moving earlier and being collapsed with our original one.
bool currentIsSet = IsSet;
if (currentIsSet != preInitializeIsSet)
{
Debug.Assert(currentIsSet,
"The only safe concurrent transition is from unset->set: detected set->unset.");
// We saw it as unsignaled, but it has since become set.
lock (newEventObj)
{
// If our event hasn't already been disposed of, we must set it.
if (m_eventObj == newEventObj)
{
newEventObj.Set();
}
}
}
return true;
}
}
/// <summary>
/// Sets the state of the event to signaled, which allows one or more threads waiting on the event to
/// proceed.
/// </summary>
public void Set()
{
Set(false);
}
/// <summary>
/// Private helper to actually perform the Set.
/// </summary>
/// <param name="duringCancellation">Indicates whether we are calling Set() during cancellation.</param>
/// <exception cref="T:System.OperationCanceledException">The object has been canceled.</exception>
private void Set(bool duringCancellation)
{
// We need to ensure that IsSet=true does not get reordered past the read of m_eventObj
// This would be a legal movement according to the .NET memory model.
// The code is safe as IsSet involves an Interlocked.CompareExchange which provides a full memory barrier.
IsSet = true;
// If there are waiting threads, we need to pulse them.
if (Waiters > 0)
{
Debug.Assert(m_lock != null && m_condition != null); //if waiters>0, then m_lock has already been created.
using (LockHolder.Hold(m_lock))
{
m_condition.SignalAll();
}
}
ManualResetEvent eventObj = m_eventObj;
//Design-decision: do not set the event if we are in cancellation -> better to deadlock than to wake up waiters incorrectly
//It would be preferable to wake up the event and have it throw OCE. This requires MRE to implement cancellation logic
if (eventObj != null && !duringCancellation)
{
// We must surround this call to Set in a lock. The reason is fairly subtle.
// Sometimes a thread will issue a Wait and wake up after we have set m_state,
// but before we have gotten around to setting m_eventObj (just below). That's
// because Wait first checks m_state and will only access the event if absolutely
// necessary. However, the coding pattern { event.Wait(); event.Dispose() } is
// quite common, and we must support it. If the waiter woke up and disposed of
// the event object before the setter has finished, however, we would try to set a
// now-disposed Win32 event. Crash! To deal with this race, we use a lock to
// protect access to the event object when setting and disposing of it. We also
// double-check that the event has not become null in the meantime when in the lock.
lock (eventObj)
{
if (m_eventObj != null)
{
// If somebody is waiting, we must set the event.
m_eventObj.Set();
}
}
}
#if DEBUG
m_lastSetTime = Environment.TickCount;
#endif
}
/// <summary>
/// Sets the state of the event to nonsignaled, which causes threads to block.
/// </summary>
/// <remarks>
/// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Reset()"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
public void Reset()
{
ThrowIfDisposed();
// If there's an event, reset it.
if (m_eventObj != null)
{
m_eventObj.Reset();
}
// There is a race here. If another thread Sets the event, we will get into a state
// where m_state will be unsignaled, yet the Win32 event object will have been signaled.
// This could cause waiting threads to wake up even though the event is in an
// unsignaled state. This is fine -- those that are calling Reset concurrently are
// responsible for doing "the right thing" -- e.g. rechecking the condition and
// resetting the event manually.
// And finally set our state back to unsignaled.
IsSet = false;
#if DEBUG
m_lastResetTime = DateTime.Now.Ticks;
#endif
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
/// <remarks>
/// The caller of this method blocks indefinitely until the current instance is set. The caller will
/// return immediately if the event is currently in a set state.
/// </remarks>
public void Wait()
{
Wait(Timeout.Infinite, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> receives a signal,
/// while observing a <see cref="T:System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
/// observe.</param>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
/// <exception cref="T:System.OperationCanceledExcepton"><paramref name="cancellationToken"/> was
/// canceled.</exception>
/// <remarks>
/// The caller of this method blocks indefinitely until the current instance is set. The caller will
/// return immediately if the event is currently in a set state.
/// </remarks>
public void Wait(CancellationToken cancellationToken)
{
Wait(Timeout.Infinite, cancellationToken);
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// <see cref="T:System.TimeSpan"/> to measure the time interval.
/// </summary>
/// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds
/// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely.
/// </param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative
/// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater
/// than <see cref="System.Int32.MaxValue"/>.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
public bool Wait(TimeSpan timeout)
{
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(timeout));
}
return Wait((int)totalMilliseconds, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// <see cref="T:System.TimeSpan"/> to measure the time interval, while observing a <see
/// cref="T:System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds
/// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely.
/// </param>
/// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
/// observe.</param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative
/// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater
/// than <see cref="System.Int32.MaxValue"/>.</exception>
/// <exception cref="T:System.Threading.OperationCanceledException"><paramref
/// name="cancellationToken"/> was canceled.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
public bool Wait(TimeSpan timeout, CancellationToken cancellationToken)
{
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(timeout));
}
return Wait((int)totalMilliseconds, cancellationToken);
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// 32-bit signed integer to measure the time interval.
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
/// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
/// negative number other than -1, which represents an infinite time-out.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
public bool Wait(int millisecondsTimeout)
{
return Wait(millisecondsTimeout, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// 32-bit signed integer to measure the time interval, while observing a <see
/// cref="T:System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
/// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
/// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
/// observe.</param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
/// negative number other than -1, which represents an infinite time-out.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
/// <exception cref="T:System.Threading.OperationCanceledException"><paramref
/// name="cancellationToken"/> was canceled.</exception>
public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)
{
ThrowIfDisposed();
cancellationToken.ThrowIfCancellationRequested(); // an early convenience check
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout));
}
if (!IsSet)
{
if (millisecondsTimeout == 0)
{
// For 0-timeouts, we just return immediately.
return false;
}
// We spin briefly before falling back to allocating and/or waiting on a true event.
uint startTime = 0;
bool bNeedTimeoutAdjustment = false;
int realMillisecondsTimeout = millisecondsTimeout; //this will be adjusted if necessary.
if (millisecondsTimeout != Timeout.Infinite)
{
// We will account for time spent spinning, so that we can decrement it from our
// timeout. In most cases the time spent in this section will be negligible. But
// we can't discount the possibility of our thread being switched out for a lengthy
// period of time. The timeout adjustments only take effect when and if we actually
// decide to block in the kernel below.
startTime = TimeoutHelper.GetTime();
bNeedTimeoutAdjustment = true;
}
//spin
int HOW_MANY_SPIN_BEFORE_YIELD = 10;
int HOW_MANY_YIELD_EVERY_SLEEP_0 = 5;
int HOW_MANY_YIELD_EVERY_SLEEP_1 = 20;
int spinCount = SpinCount;
for (int i = 0; i < spinCount; i++)
{
if (IsSet)
{
return true;
}
else if (i < HOW_MANY_SPIN_BEFORE_YIELD)
{
if (i == HOW_MANY_SPIN_BEFORE_YIELD / 2)
{
RuntimeThread.Yield();
}
else
{
RuntimeThread.SpinWait(PlatformHelper.ProcessorCount * (4 << i));
}
}
else if (i % HOW_MANY_YIELD_EVERY_SLEEP_1 == 0)
{
RuntimeThread.Sleep(1);
}
else if (i % HOW_MANY_YIELD_EVERY_SLEEP_0 == 0)
{
RuntimeThread.Sleep(0);
}
else
{
RuntimeThread.Yield();
}
if (i >= 100 && i % 10 == 0) // check the cancellation token if the user passed a very large spin count
cancellationToken.ThrowIfCancellationRequested();
}
// Now enter the lock and wait.
EnsureLockObjectCreated();
// We must register and unregister the token outside of the lock, to avoid deadlocks.
using (cancellationToken.InternalRegisterWithoutEC(s_cancellationTokenCallback, this))
{
using (LockHolder.Hold(m_lock))
{
// Loop to cope with spurious wakeups from other waits being canceled
while (!IsSet)
{
// If our token was canceled, we must throw and exit.
cancellationToken.ThrowIfCancellationRequested();
//update timeout (delays in wait commencement are due to spinning and/or spurious wakeups from other waits being canceled)
if (bNeedTimeoutAdjustment)
{
realMillisecondsTimeout = TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout);
if (realMillisecondsTimeout <= 0)
return false;
}
// There is a race that Set will fail to see that there are waiters as Set does not take the lock,
// so after updating waiters, we must check IsSet again.
// Also, we must ensure there cannot be any reordering of the assignment to Waiters and the
// read from IsSet. This is guaranteed as Waiters{set;} involves an Interlocked.CompareExchange
// operation which provides a full memory barrier.
// If we see IsSet=false, then we are guaranteed that Set() will see that we are
// waiting and will pulse the monitor correctly.
Waiters = Waiters + 1;
if (IsSet) //This check must occur after updating Waiters.
{
Waiters--; //revert the increment.
return true;
}
// Now finally perform the wait.
try
{
// ** the actual wait **
if (!m_condition.Wait(realMillisecondsTimeout))
return false; //return immediately if the timeout has expired.
}
finally
{
// Clean up: we're done waiting.
Waiters = Waiters - 1;
}
// Now just loop back around, and the right thing will happen. Either:
// 1. We had a spurious wake-up due to some other wait being canceled via a different cancellationToken (rewait)
// or 2. the wait was successful. (the loop will break)
}
}
}
} // automatically disposes (and unregisters) the callback
return true; //done. The wait was satisfied.
}
/// <summary>
/// Releases all resources used by the current instance of <see cref="ManualResetEventSlim"/>.
/// </summary>
/// <remarks>
/// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose()"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// When overridden in a derived class, releases the unmanaged resources used by the
/// <see cref="ManualResetEventSlim"/>, and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources;
/// false to release only unmanaged resources.</param>
/// <remarks>
/// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose(Boolean)"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
protected virtual void Dispose(bool disposing)
{
if ((m_combinedState & Dispose_BitMask) != 0)
return; // already disposed
m_combinedState |= Dispose_BitMask; //set the dispose bit
if (disposing)
{
// We will dispose of the event object. We do this under a lock to protect
// against the race condition outlined in the Set method above.
ManualResetEvent eventObj = m_eventObj;
if (eventObj != null)
{
lock (eventObj)
{
eventObj.Dispose();
m_eventObj = null;
}
}
}
}
/// <summary>
/// Throw ObjectDisposedException if the MRES is disposed
/// </summary>
private void ThrowIfDisposed()
{
if ((m_combinedState & Dispose_BitMask) != 0)
throw new ObjectDisposedException(SR.ManualResetEventSlim_Disposed);
}
/// <summary>
/// Private helper method to wake up waiters when a cancellationToken gets canceled.
/// </summary>
private static Action<object> s_cancellationTokenCallback = new Action<object>(CancellationTokenCallback);
private static void CancellationTokenCallback(object obj)
{
ManualResetEventSlim mre = obj as ManualResetEventSlim;
Debug.Assert(mre != null, "Expected a ManualResetEventSlim");
Debug.Assert(mre.m_lock != null); //the lock should have been created before this callback is registered for use.
using (LockHolder.Hold(mre.m_lock))
{
mre.m_condition.SignalAll(); // awaken all waiters
}
}
/// <summary>
/// Private helper method for updating parts of a bit-string state value.
/// Mainly called from the IsSet and Waiters properties setters
/// </summary>
/// <remarks>
/// Note: the parameter types must be int as CompareExchange cannot take a Uint
/// </remarks>
/// <param name="newBits">The new value</param>
/// <param name="updateBitsMask">The mask used to set the bits</param>
private void UpdateStateAtomically(int newBits, int updateBitsMask)
{
SpinWait sw = new SpinWait();
Debug.Assert((newBits | updateBitsMask) == updateBitsMask, "newBits do not fall within the updateBitsMask.");
do
{
int oldState = m_combinedState; // cache the old value for testing in CAS
// Procedure:(1) zero the updateBits. eg oldState = [11111111] flag= [00111000] newState = [11000111]
// then (2) map in the newBits. eg [11000111] newBits=00101000, newState=[11101111]
int newState = (oldState & ~updateBitsMask) | newBits;
if (Interlocked.CompareExchange(ref m_combinedState, newState, oldState) == oldState)
{
return;
}
sw.SpinOnce();
} while (true);
}
/// <summary>
/// Private helper method - performs Mask and shift, particular helpful to extract a field from a packed word.
/// eg ExtractStatePortionAndShiftRight(0x12345678, 0xFF000000, 24) => 0x12, ie extracting the top 8-bits as a simple integer
///
/// ?? is there a common place to put this rather than being private to MRES?
/// </summary>
/// <param name="state"></param>
/// <param name="mask"></param>
/// <param name="rightBitShiftCount"></param>
/// <returns></returns>
private static int ExtractStatePortionAndShiftRight(int state, int mask, int rightBitShiftCount)
{
//convert to uint before shifting so that right-shift does not replicate the sign-bit,
//then convert back to int.
return unchecked((int)(((uint)(state & mask)) >> rightBitShiftCount));
}
/// <summary>
/// Performs a Mask operation, but does not perform the shift.
/// This is acceptable for boolean values for which the shift is unnecessary
/// eg (val & Mask) != 0 is an appropriate way to extract a boolean rather than using
/// ((val & Mask) >> shiftAmount) == 1
///
/// ?? is there a common place to put this rather than being private to MRES?
/// </summary>
/// <param name="state"></param>
/// <param name="mask"></param>
private static int ExtractStatePortion(int state, int mask)
{
return state & mask;
}
}
}
| |
using System;
using Shouldly;
using Veggerby.Algorithm.Calculus;
using Xunit;
namespace Veggerby.Algorithm.Tests.Calculus
{
public class CalculusExtensionsTests
{
[Theory]
[InlineData("x!", typeof(Factorial), 0)]
[InlineData("x^2", typeof(Power), 1)]
[InlineData("x/2", typeof(Division), 2)]
[InlineData("x*2", typeof(Multiplication), 3)]
[InlineData("x-2", typeof(Subtraction), 4)]
[InlineData("x+2", typeof(Addition), 5)]
[InlineData("sin(x)", typeof(Sine), null)]
[InlineData("cos(x)", typeof(Cosine), null)]
[InlineData("exp(x)", typeof(Exponential), null)]
[InlineData("ln(x)", typeof(Logarithm), null)]
[InlineData("log(x)", typeof(LogarithmBase), null)]
[InlineData("2", typeof(ValueConstant), null)]
[InlineData("x", typeof(Variable), null)]
[InlineData("pi", typeof(NamedConstant), null)]
[InlineData("-x", typeof(Negative), null)]
public void Should_return_correct_priority(string f, Type type, int? expected)
{
// arrange
Operand func = f;
// act
var actual = func.GetPriority();
// assert
func.ShouldBeOfType(type);
actual.ShouldBe(expected);
}
[Theory]
[InlineData("x!", typeof(Factorial), true)]
[InlineData("x^2", typeof(Power), true)]
[InlineData("x/2", typeof(Division), true)]
[InlineData("x*2", typeof(Multiplication), true)]
[InlineData("x-2", typeof(Subtraction), true)]
[InlineData("x+2", typeof(Addition), true)]
[InlineData("sin(x)", typeof(Sine), false)]
[InlineData("cos(x)", typeof(Cosine), false)]
[InlineData("exp(x)", typeof(Exponential), false)]
[InlineData("ln(x)", typeof(Logarithm), false)]
[InlineData("log(x)", typeof(LogarithmBase), false)]
[InlineData("2", typeof(ValueConstant), false)]
[InlineData("x", typeof(Variable), false)]
[InlineData("pi", typeof(NamedConstant), false)]
[InlineData("-x", typeof(Negative), false)]
public void Should_return_could_use_parenthesis(string f, Type type, bool expected)
{
// arrange
Operand func = f;
// act
var actual = func.CouldUseParenthesis();
// assert
func.ShouldBeOfType(type);
actual.ShouldBe(expected);
}
[Theory]
[InlineData("x!", typeof(Factorial), false)]
[InlineData("x^2", typeof(Power), false)]
[InlineData("x/2", typeof(Division), false)]
[InlineData("x*2", typeof(Multiplication), false)]
[InlineData("x-2", typeof(Subtraction), false)]
[InlineData("x+2", typeof(Addition), false)]
[InlineData("sin(x)", typeof(Sine), false)]
[InlineData("cos(x)", typeof(Cosine), false)]
[InlineData("exp(x)", typeof(Exponential), false)]
[InlineData("ln(x)", typeof(Logarithm), false)]
[InlineData("log(x)", typeof(LogarithmBase), false)]
[InlineData("2", typeof(ValueConstant), true)]
[InlineData("x", typeof(Variable), false)]
[InlineData("pi", typeof(NamedConstant), false)]
[InlineData("-x", typeof(Negative), false)]
public void Should_return_is_constant(string f, Type type, bool expected)
{
// arrange
Operand func = f;
// act
var actual = func.IsConstant();
// assert
func.ShouldBeOfType(type);
actual.ShouldBe(expected);
}
[Theory]
[InlineData("x!", typeof(Factorial), false)]
[InlineData("x^2", typeof(Power), false)]
[InlineData("x/2", typeof(Division), false)]
[InlineData("x*2", typeof(Multiplication), false)]
[InlineData("x-2", typeof(Subtraction), false)]
[InlineData("x+2", typeof(Addition), false)]
[InlineData("sin(x)", typeof(Sine), false)]
[InlineData("cos(x)", typeof(Cosine), false)]
[InlineData("exp(x)", typeof(Exponential), false)]
[InlineData("ln(x)", typeof(Logarithm), false)]
[InlineData("log(x)", typeof(LogarithmBase), false)]
[InlineData("2", typeof(ValueConstant), false)]
[InlineData("x", typeof(Variable), true)]
[InlineData("pi", typeof(NamedConstant), false)]
[InlineData("-x", typeof(Negative), false)]
public void Should_return_is_variable(string f, Type type, bool expected)
{
// arrange
Operand func = f;
// act
var actual = func.IsVariable();
// assert
func.ShouldBeOfType(type);
actual.ShouldBe(expected);
}
[Theory]
[InlineData("x!", typeof(Factorial), false)]
[InlineData("x^2", typeof(Power), false)]
[InlineData("x/2", typeof(Division), false)]
[InlineData("x*2", typeof(Multiplication), false)]
[InlineData("x-2", typeof(Subtraction), false)]
[InlineData("x+2", typeof(Addition), false)]
[InlineData("sin(x)", typeof(Sine), false)]
[InlineData("cos(x)", typeof(Cosine), false)]
[InlineData("exp(x)", typeof(Exponential), false)]
[InlineData("ln(x)", typeof(Logarithm), false)]
[InlineData("log(x)", typeof(LogarithmBase), false)]
[InlineData("2", typeof(ValueConstant), false)]
[InlineData("x", typeof(Variable), false)]
[InlineData("pi", typeof(NamedConstant), false)]
[InlineData("-x", typeof(Negative), true)]
public void Should_return_is_negative(string f, Type type, bool expected)
{
// arrange
Operand func = f;
// act
var actual = func.IsNegative();
// assert
func.ShouldBeOfType(type);
actual.ShouldBe(expected);
}
/* [Fact]
public void Should_return_simple_flatten()
{
// arrange
var f = (IAssociativeOperation)Multiplication.Create(Variable.x, Constant.Pi);
var expected = new HashSet<Operand> { f.Left, f.Right };
// act
var actual = f.FlattenAssociative();
// assert
actual.ShouldBe(expected);
}
[Fact]
public void Should_return_flatten_from_string()
{
// arrange
Operand f = "(2*pi*cos(x)*x)*2";
var expected = new Operand[] { Constant.Create(2), Constant.Pi, Cosine.Create(Variable.x), Variable.x, Constant.Create(2) };
// act
var actual = ((IAssociativeOperation)f).FlattenAssociative();
// assert
actual.ShouldBe(expected);
}
[Fact]
public void Should_return_flatten_nested()
{
// arrange
var f = (IAssociativeBinaryOperation)Multiplication.Create(
Multiplication.Create(
Variable.x,
Sine.Create(Variable.x)),
Multiplication.Create(
Multiplication.Create(
Cosine.Create(Variable.x),
Logarithm.Create(Variable.x)
),
Addition.Create(
Constant.One,
Variable.x
)));
var expected = new HashSet<Operand>
{
Variable.x,
Sine.Create(Variable.x),
Cosine.Create(Variable.x),
Logarithm.Create(Variable.x),
Addition.Create(Constant.One, Variable.x)
};
// act
var actual = f.FlattenAssociative();
// assert
actual.ShouldBe(expected);
}*/
[Fact]
public void Should_return_simple_latex()
{
// arrange
var operand = Sine.Create(Variable.x);
// act
var actual = operand.ToLaTeXString();
// assert
actual.ShouldBe(@"\sin\left(x\right)");
}
[Theory]
[InlineData(0.1, false)]
[InlineData(1.000000000, true)]
[InlineData(5d, true)]
[InlineData(4/2, true)]
public void Should_return_expected(double value, bool expected)
{
// arrange
var constant = ValueConstant.Create(value);
// act
var actual = constant.IsInteger();
// assert
actual.ShouldBe(expected);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
namespace AGO.Core.Controllers
{
public static class MimeAssistant
{
private static readonly Dictionary<string, string> MimeTypesDictionary
= new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase)
{
{"ai", "application/postscript"},
{"aif", "audio/x-aiff"},
{"aifc", "audio/x-aiff"},
{"aiff", "audio/x-aiff"},
{"asc", "text/plain"},
{"atom", "application/atom+xml"},
{"au", "audio/basic"},
{"avi", "video/x-msvideo"},
{"bcpio", "application/x-bcpio"},
{"bin", "application/octet-stream"},
{"bmp", "image/bmp"},
{"cdf", "application/x-netcdf"},
{"cgm", "image/cgm"},
{"class", "application/octet-stream"},
{"cpio", "application/x-cpio"},
{"cpt", "application/mac-compactpro"},
{"csh", "application/x-csh"},
{"css", "text/css"},
{"dcr", "application/x-director"},
{"dif", "video/x-dv"},
{"dir", "application/x-director"},
{"djv", "image/vnd.djvu"},
{"djvu", "image/vnd.djvu"},
{"dll", "application/octet-stream"},
{"dmg", "application/octet-stream"},
{"dms", "application/octet-stream"},
{"doc", "application/msword"},
{"docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{"dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
{"docm","application/vnd.ms-word.document.macroEnabled.12"},
{"dotm","application/vnd.ms-word.template.macroEnabled.12"},
{"dtd", "application/xml-dtd"},
{"dv", "video/x-dv"},
{"dvi", "application/x-dvi"},
{"dxr", "application/x-director"},
{"eps", "application/postscript"},
{"etx", "text/x-setext"},
{"exe", "application/octet-stream"},
{"ez", "application/andrew-inset"},
{"gif", "image/gif"},
{"gram", "application/srgs"},
{"grxml", "application/srgs+xml"},
{"gtar", "application/x-gtar"},
{"hdf", "application/x-hdf"},
{"hqx", "application/mac-binhex40"},
{"htm", "text/html"},
{"html", "text/html"},
{"ice", "x-conference/x-cooltalk"},
{"ico", "image/x-icon"},
{"ics", "text/calendar"},
{"ief", "image/ief"},
{"ifb", "text/calendar"},
{"iges", "model/iges"},
{"igs", "model/iges"},
{"jnlp", "application/x-java-jnlp-file"},
{"jp2", "image/jp2"},
{"jpe", "image/jpeg"},
{"jpeg", "image/jpeg"},
{"jpg", "image/jpeg"},
{"js", "application/x-javascript"},
{"kar", "audio/midi"},
{"latex", "application/x-latex"},
{"lha", "application/octet-stream"},
{"lzh", "application/octet-stream"},
{"m3u", "audio/x-mpegurl"},
{"m4a", "audio/mp4a-latm"},
{"m4b", "audio/mp4a-latm"},
{"m4p", "audio/mp4a-latm"},
{"m4u", "video/vnd.mpegurl"},
{"m4v", "video/x-m4v"},
{"mac", "image/x-macpaint"},
{"man", "application/x-troff-man"},
{"mathml", "application/mathml+xml"},
{"me", "application/x-troff-me"},
{"mesh", "model/mesh"},
{"mid", "audio/midi"},
{"midi", "audio/midi"},
{"mif", "application/vnd.mif"},
{"mov", "video/quicktime"},
{"movie", "video/x-sgi-movie"},
{"mp2", "audio/mpeg"},
{"mp3", "audio/mpeg"},
{"mp4", "video/mp4"},
{"mpe", "video/mpeg"},
{"mpeg", "video/mpeg"},
{"mpg", "video/mpeg"},
{"mpga", "audio/mpeg"},
{"ms", "application/x-troff-ms"},
{"msh", "model/mesh"},
{"mxu", "video/vnd.mpegurl"},
{"nc", "application/x-netcdf"},
{"oda", "application/oda"},
{"ogg", "application/ogg"},
{"pbm", "image/x-portable-bitmap"},
{"pct", "image/pict"},
{"pdb", "chemical/x-pdb"},
{"pdf", "application/pdf"},
{"pgm", "image/x-portable-graymap"},
{"pgn", "application/x-chess-pgn"},
{"pic", "image/pict"},
{"pict", "image/pict"},
{"png", "image/png"},
{"pnm", "image/x-portable-anymap"},
{"pnt", "image/x-macpaint"},
{"pntg", "image/x-macpaint"},
{"ppm", "image/x-portable-pixmap"},
{"ppt", "application/vnd.ms-powerpoint"},
{"pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{"potx","application/vnd.openxmlformats-officedocument.presentationml.template"},
{"ppsx","application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
{"ppam","application/vnd.ms-powerpoint.addin.macroEnabled.12"},
{"pptm","application/vnd.ms-powerpoint.presentation.macroEnabled.12"},
{"potm","application/vnd.ms-powerpoint.template.macroEnabled.12"},
{"ppsm","application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},
{"ps", "application/postscript"},
{"qt", "video/quicktime"},
{"qti", "image/x-quicktime"},
{"qtif", "image/x-quicktime"},
{"ra", "audio/x-pn-realaudio"},
{"ram", "audio/x-pn-realaudio"},
{"ras", "image/x-cmu-raster"},
{"rdf", "application/rdf+xml"},
{"rgb", "image/x-rgb"},
{"rm", "application/vnd.rn-realmedia"},
{"roff", "application/x-troff"},
{"rtf", "text/rtf"},
{"rtx", "text/richtext"},
{"sgm", "text/sgml"},
{"sgml", "text/sgml"},
{"sh", "application/x-sh"},
{"shar", "application/x-shar"},
{"silo", "model/mesh"},
{"sit", "application/x-stuffit"},
{"skd", "application/x-koan"},
{"skm", "application/x-koan"},
{"skp", "application/x-koan"},
{"skt", "application/x-koan"},
{"smi", "application/smil"},
{"smil", "application/smil"},
{"snd", "audio/basic"},
{"so", "application/octet-stream"},
{"spl", "application/x-futuresplash"},
{"src", "application/x-wais-source"},
{"sv4cpio", "application/x-sv4cpio"},
{"sv4crc", "application/x-sv4crc"},
{"svg", "image/svg+xml"},
{"swf", "application/x-shockwave-flash"},
{"t", "application/x-troff"},
{"tar", "application/x-tar"},
{"tcl", "application/x-tcl"},
{"tex", "application/x-tex"},
{"texi", "application/x-texinfo"},
{"texinfo", "application/x-texinfo"},
{"tif", "image/tiff"},
{"tiff", "image/tiff"},
{"tr", "application/x-troff"},
{"tsv", "text/tab-separated-values"},
{"txt", "text/plain"},
{"ustar", "application/x-ustar"},
{"vcd", "application/x-cdlink"},
{"vrml", "model/vrml"},
{"vxml", "application/voicexml+xml"},
{"wav", "audio/x-wav"},
{"wbmp", "image/vnd.wap.wbmp"},
{"wbmxl", "application/vnd.wap.wbxml"},
{"wml", "text/vnd.wap.wml"},
{"wmlc", "application/vnd.wap.wmlc"},
{"wmls", "text/vnd.wap.wmlscript"},
{"wmlsc", "application/vnd.wap.wmlscriptc"},
{"wrl", "model/vrml"},
{"xbm", "image/x-xbitmap"},
{"xht", "application/xhtml+xml"},
{"xhtml", "application/xhtml+xml"},
{"xls", "application/vnd.ms-excel"},
{"xml", "application/xml"},
{"xpm", "image/x-xpixmap"},
{"xsl", "application/xml"},
{"xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{"xltx","application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
{"xlsm","application/vnd.ms-excel.sheet.macroEnabled.12"},
{"xltm","application/vnd.ms-excel.template.macroEnabled.12"},
{"xlam","application/vnd.ms-excel.addin.macroEnabled.12"},
{"xlsb","application/vnd.ms-excel.sheet.binary.macroEnabled.12"},
{"xslt", "application/xslt+xml"},
{"xul", "application/vnd.mozilla.xul+xml"},
{"xwd", "image/x-xwindowdump"},
{"xyz", "chemical/x-xyz"},
{"zip", "application/zip"}
};
public static string GetMimeType(string fileName)
{
var result = "application/octet-stream";
if (!fileName.IsNullOrWhiteSpace())
{
var extension = Path.GetExtension(fileName).TrimSafe().RemovePrefix(".");
if (MimeTypesDictionary.ContainsKey(extension))
result = MimeTypesDictionary[extension];
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using TBS.ScreenManager;
namespace TBS.Screens
{
class MapEditorScreen : GameScreen
{
ContentManager _content;
float _pauseAlpha;
private const int CameraSpeed = 5;
private readonly Vector2 _nullCursor;
private Sprite _cursor, _move, _attack;
private int _gridWidth, _gridHeight;
private readonly Terrain[] _terrains;
private readonly Dictionary<string, Sprite> _texturesBuildings = new Dictionary<string, Sprite>();
private readonly Dictionary<string, Sprite> _texturesUnitsSmall = new Dictionary<string, Sprite>();
private readonly Dictionary<string, Sprite> _texturesUnitsPreview = new Dictionary<string, Sprite>();
private readonly Dictionary<string, Sprite> _texturesUnitsBig = new Dictionary<string, Sprite>();
private Texture2D _backgroundTexture;
private SpriteFont _font, _fontDebug, _fontPopup;
private Sprite _fontLife, _capturing;
private Vector2 _cursorPos;
private readonly int _mapHeight, _mapWidth;
private Sprite _popupLeft, _popupMid, _popupRight, _popupLeftOn, _popupMidOn, _popupRightOn;
private Vector2 _camera;
private readonly Player[] _players;
private readonly Terrain[,] _mapTerrains;
private readonly Building[,] _mapBuildings;
private readonly List<Unit> _units;
private bool _showContextMenu;
private string _contextMenuContext;
private string[] _contextMenus;
private Point _contextMenuPos;
private int _contextMaxWidth;
public MapEditorScreen(string map)
{
TransitionOnTime = TimeSpan.FromSeconds(1.5);
TransitionOffTime = TimeSpan.FromSeconds(0.5);
UnitCreator.Initialize();
_nullCursor = new Vector2(-1, -1);
_terrains = new[]
{
new Terrain("Plains", false, 1, 1, 1, 2, 1, 1, 1, -1, -1),
new Terrain("Road", false, 0, 1, 1, 1, 1, 1, 1, -1, -1),
new Terrain("Wood", true, 3, 1, 1, 3, 3, 2, 1, -1, -1),
new Terrain("Mountain", false, 4, 2, 1, -1, -1, -1, 1, -1, -1),
new Terrain("Wasteland", false, 2, 1, 1, 3, 3, 2, 1, -1, -1),
new Terrain("Ruins", true, 1, 1, 1, 2, 1, 1, 1, -1, -1),
new Terrain("Sea", false, 0, -1, -1, -1, -1, -1, 1, 1, 1),
new Terrain("BridgeSea", false, 0, 1, 1, 1, 1, 1, 1, 1, 1),
new Terrain("BridgeRiver", false, 0, 1, 1, 1, 1, 1, 1, 1, 1),
new Terrain("River", false, 0, 2, 1, -1, -1, -1, 1, -1, -1),
new Terrain("Beach", false, 0, 1, 1, 2, 2, 1, 1, -1, 1),
new Terrain("Rough Sea", false, 0, -1, -1, -1, -1, -1, 1, 2, 2),
new Terrain("Mist", true, 0, -1, -1, -1, -1, -1, 1, 1, 1),
new Terrain("Reef", true, 0, -1, -1, -1, -1, -1, 1, 2, 2)
};
// Load map data from TXT file
var flines = File.ReadLines("Content/Maps/" + map + ".txt")
.Where(l => l.Length != 0 && !l.StartsWith("#"))
.ToList();
//_mapName = flines[0].Trim();
_mapWidth = Convert.ToInt32(flines[1].Trim());
_mapHeight = Convert.ToInt32(flines[2].Trim());
var plyers = flines.GetRange(3, 4).Where(l => !l.StartsWith("0")).ToArray();
_players = new Player[plyers.Length];
for (var i = 0; i < _players.Length; ++i)
_players[i] = new Player(i + 1, Convert.ToInt32(plyers[i].Trim()));
var terrainLines = new string[_mapHeight];
var read = 0;
for (var i = 7; i < _mapHeight + 7; ++i)
{
var line = flines[i].Trim();
terrainLines[read++] = line;
}
var buildings = flines;
buildings.RemoveRange(0, _mapHeight + 7);
// Generate terrain according to map data
_mapTerrains = new Terrain[_mapHeight, _mapWidth];
for (var y = 0; y < _mapHeight; ++y)
for (var x = 0; x < _mapWidth; ++x)
{
var type = terrainLines[y][x] >= '0' && terrainLines[y][x] <= '9'
? terrainLines[y][x] - '0'
: terrainLines[y][x] - 'a' + 10;
_mapTerrains[y, x] = _terrains[type];
}
var bOrder = new[] { "Headquarter", "City", "Factory", "Port", "Airport" };
_mapBuildings = new Building[_mapHeight, _mapWidth];
_units = new List<Unit>();
foreach (var data in buildings.Select(b => b.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)))
{
var p = Convert.ToInt32(data[2]);
if (data.Length == 5)
{
var u = UnitCreator.Unit(
data[3],
_players[p - 1],
new Vector2(
Convert.ToInt32(data[1]),
Convert.ToInt32(data[0])));
u.Life = Convert.ToInt32(data[4]) * 10;
_units.Add(u);
}
else if (data.Length == 4)
{
var x = Convert.ToInt32(data[1]);
var y = Convert.ToInt32(data[0]);
_mapBuildings[y, x] = new Building(bOrder[Convert.ToInt32(data[3])], p == 0 ? null : _players[p - 1], new Vector2(x, y));
}
}
_camera = new Vector2(-50, -80);
}
/// <summary>
/// Load graphics content for the game.
/// </summary>
public override void LoadContent()
{
if (_content == null)
_content = new ContentManager(ScreenManager.Game.Services, "Content");
_backgroundTexture = _content.Load<Texture2D>("Menu/Background");
_cursor = new Sprite(_content.Load<Texture2D>("Terrains/Medium/Cursor"), 1, 2);
_move = new Sprite(_content.Load<Texture2D>("Terrains/Medium/Move"));
_attack = new Sprite(_content.Load<Texture2D>("Terrains/Medium/Attack"));
_capturing = new Sprite(_content.Load<Texture2D>("Capturing"));
_terrains[0].Texture = new Sprite(_content.Load<Texture2D>("Terrains/Medium/Plains"));
_terrains[1].Texture = new Sprite(_content.Load<Texture2D>("Terrains/Medium/Road"), 16);
_terrains[2].Texture = new Sprite(_content.Load<Texture2D>("Terrains/Medium/Wood"));
_terrains[3].Texture = new Sprite(_content.Load<Texture2D>("Terrains/Medium/Mountain"));
_terrains[4].Texture = new Sprite(_content.Load<Texture2D>("Terrains/Medium/Wasteland"));
_terrains[5].Texture = new Sprite(_content.Load<Texture2D>("Terrains/Medium/Ruins"));
_terrains[6].Texture = new Sprite(_content.Load<Texture2D>("Terrains/Medium/Sea"), 16);
_terrains[7].Texture = new Sprite(_content.Load<Texture2D>("Terrains/Medium/Bridge"), 16);
_terrains[8].Texture = new Sprite(_content.Load<Texture2D>("Terrains/Medium/Bridge"), 16);
_terrains[9].Texture = new Sprite(_content.Load<Texture2D>("Terrains/Medium/River"), 16);
_terrains[10].Texture = new Sprite(_content.Load<Texture2D>("Terrains/Medium/Beach"));
_terrains[11].Texture = new Sprite(_content.Load<Texture2D>("Terrains/Medium/RoughSea"));
_terrains[12].Texture = new Sprite(_content.Load<Texture2D>("Terrains/Medium/Mist"));
_terrains[13].Texture = new Sprite(_content.Load<Texture2D>("Terrains/Medium/Reef"));
_gridWidth = _terrains[0].Texture.Texture.Width;
_gridHeight = _terrains[0].Texture.Texture.Width;
_texturesBuildings.Add("Headquarter", new Sprite(_content.Load<Texture2D>("Buildings/Headquarter"), 6, 4));
_texturesBuildings.Add("City", new Sprite(_content.Load<Texture2D>("Buildings/City"), 6, 4));
_texturesBuildings.Add("Factory", new Sprite(_content.Load<Texture2D>("Buildings/Factory"), 6, 4));
_texturesBuildings.Add("Port", new Sprite(_content.Load<Texture2D>("Buildings/Port"), 6, 4));
_texturesBuildings.Add("Airport", new Sprite(_content.Load<Texture2D>("Buildings/Airport"), 6, 4));
var units = new[]
{
new Tuple<string,string>("Anti-Air", "AntiAir"),
new Tuple<string,string>("Anti-Tank", "AntiTank"),
new Tuple<string,string>("Artillery", "Artillery"),
new Tuple<string,string>("Mech", "Bazooka1"),
new Tuple<string,string>("Bomber", "Bomber"),
new Tuple<string,string>("Fighter", "Fighter"),
new Tuple<string,string>("Battle Copter", "FightHeli"),
new Tuple<string,string>("Flare", "Flare"),
new Tuple<string,string>("Infantry", "Inf1"),
new Tuple<string,string>("Medium Tank", "MediumTank"),
new Tuple<string,string>("Missiles", "Missiles"),
new Tuple<string,string>("Bike", "Moto1"),
new Tuple<string,string>("Recon", "Recon"),
new Tuple<string,string>("Rig", "Rig"),
new Tuple<string,string>("Rockets", "Rockets"),
new Tuple<string,string>("Tank", "Tank"),
new Tuple<string,string>("Transport Copter", "TransHeli")
};
foreach (var u in units)
{
//_texturesUnitsSmall.Add(u.Item1, new Sprite(_content.Load<Texture2D>("Units/Small/" + u.Item2), 6, 3, 200));
_texturesUnitsPreview.Add(u.Item1, new Sprite(_content.Load<Texture2D>("Units/Preview/" + u.Item2), 2, 3, 400));
_texturesUnitsBig.Add(u.Item1, new Sprite(_content.Load<Texture2D>("Units/Big/" + u.Item2), 6, 3, 200));
}
_font = _content.Load<SpriteFont>("Fonts/Game");
_fontDebug = _content.Load<SpriteFont>("Fonts/Debug");
_fontPopup = _content.Load<SpriteFont>("Fonts/Popup");
_fontLife = new Sprite(_content.Load<Texture2D>("Fonts/Life"), 12);
_popupLeft = new Sprite(_content.Load<Texture2D>("Popup/Left"));
_popupLeftOn = new Sprite(_content.Load<Texture2D>("Popup/LeftOn"));
_popupMid = new Sprite(_content.Load<Texture2D>("Popup/Mid"));
_popupMidOn = new Sprite(_content.Load<Texture2D>("Popup/MidOn"));
_popupRight = new Sprite(_content.Load<Texture2D>("Popup/Right"));
_popupRightOn = new Sprite(_content.Load<Texture2D>("Popup/RightOn"));
GC.Collect();
ScreenManager.Game.ResetElapsedTime();
}
/// <summary>
/// Unload graphics content used by the game.
/// </summary>
public override void UnloadContent()
{
_content.Unload();
}
/// <summary>
/// Updates the state of the game. This method checks the GameScreen.IsActive
/// property, so the game will stop updating when the pause menu is active,
/// or if you tab away to a different application.
/// </summary>
public override void Update(GameTime gameTime, bool otherScreenHasFocus,
bool coveredByOtherScreen)
{
base.Update(gameTime, otherScreenHasFocus, false);
// Gradually fade in or out depending on whether we are covered by the pause screen.
_pauseAlpha = coveredByOtherScreen
? Math.Min(_pauseAlpha + 1f / 32, 1)
: Math.Max(_pauseAlpha - 1f / 32, 0);
if (!IsActive)
return;
// Update textures for animations
for (var i = 0; i < _terrains.GetLength(0); ++i)
_terrains[i].Texture.Update(gameTime);
for (var i = 0; i < _texturesBuildings.Count; ++i)
_texturesBuildings.Values.ElementAt(i).Update(gameTime);
for (var i = 0; i < _texturesUnitsBig.Count; ++i)
_texturesUnitsBig.Values.ElementAt(i).Update(gameTime);
for (var i = 0; i < _texturesUnitsPreview.Count; ++i)
_texturesUnitsPreview.Values.ElementAt(i).Update(gameTime);
for (var i = 0; i < _texturesUnitsSmall.Count; ++i)
_texturesUnitsSmall.Values.ElementAt(i).Update(gameTime);
_cursor.Update(gameTime);
// Context menu
var oldShow = _showContextMenu;
var noSelect = false;
if (_showContextMenu && Souris.Get().Clicked(MouseButton.Left))
{
var rect = new Rectangle(_contextMenuPos.X + 2 - (int)_camera.X, _contextMenuPos.Y + 2 - (int)_camera.Y, _contextMaxWidth + 2 + _popupLeft.Width + _popupRight.Width, 16 * _contextMenus.Length);
if (rect.Contains(Souris.Get().Position))
{
var index = (int)Math.Floor((double)(Souris.Get().Y - rect.Y) / 16f);
var selected = _contextMenus[index];
}
_showContextMenu = false;
noSelect = true;
}
// Update cursor position
if (!_showContextMenu)
{
var curPos = new Vector2((int)((Souris.Get().X + _camera.X) / _gridWidth), (int)((Souris.Get().Y + _camera.Y) / _gridHeight));
_cursorPos = Souris.Get().X + _camera.X >= 0 && Souris.Get().Y + _camera.Y >= 0
&& curPos.X < _mapWidth && curPos.Y < _mapHeight
? curPos
: _nullCursor;
}
// Mouse click
if (Souris.Get().Clicked(MouseButton.Left) && _cursorPos != _nullCursor && !noSelect)
{
var unitUnder = _units.FirstOrDefault(t =>
Math.Abs(t.Position.X - _cursorPos.X) < 0.1
&& Math.Abs(t.Position.Y - _cursorPos.Y) < 0.1);
var buildingUnder = _mapBuildings[(int)_cursorPos.Y, (int)_cursorPos.X];
}
}
/// <summary>
/// Lets the game respond to player input. Unlike the Update method,
/// this will only be called when the gameplay screen is active.
/// </summary>
public override void HandleInput(InputState input)
{
if (input == null)
throw new ArgumentNullException("input");
// Look up inputs for the active player profile.
var playerIndex = ControllingPlayer != null ? (int)ControllingPlayer.Value : 0;
var gamePadState = input.CurrentGamePadStates[playerIndex];
// The game pauses either if the user presses the pause button, or if
// they unplug the active gamepad. This requires us to keep track of
// whether a gamepad was ever plugged in, because we don't want to pause
// on PC if they are playing with a keyboard and have no gamepad at all!
var gamePadDisconnected = !gamePadState.IsConnected
&& input.GamePadWasConnected[playerIndex];
if (input.IsPauseGame(ControllingPlayer) || gamePadDisconnected)
ScreenManager.AddScreen(new PauseMenuScreen(), ControllingPlayer);
else
{
// Camera movement
var movement = Vector2.Zero;
movement.X += gamePadState.ThumbSticks.Left.X;
movement.Y += gamePadState.ThumbSticks.Left.Y;
if (Clavier.Get().Pressed(Keys.Left))
movement.X--;
if (Clavier.Get().Pressed(Keys.Right))
movement.X++;
if (Clavier.Get().Pressed(Keys.Up))
movement.Y--;
if (Clavier.Get().Pressed(Keys.Down))
movement.Y++;
_camera += movement * CameraSpeed;
}
}
/// <summary>
/// Draws the gameplay screen.
/// </summary>
public override void Draw(GameTime gameTime)
{
var graphics = ScreenManager.GraphicsDevice;
var spriteBatch = ScreenManager.SpriteBatch;
graphics.Clear(ClearOptions.Target, Color.CornflowerBlue, 0, 0);
spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);
spriteBatch.Draw(_backgroundTexture, new Rectangle(0, 0, graphics.Viewport.Width, graphics.Viewport.Height), Color.White);
// Draw terrain and bridges
for (var y = 0; y < _mapHeight; ++y)
for (var x = 0; x < _mapWidth; ++x)
{
var terrain = _mapTerrains[y, x];
var tex = terrain.Type == "Mist" || terrain.Type == "BridgeSea"
? _terrains[6].Texture
: (terrain.Type == "BridgeRiver"
? _terrains[9].Texture
: (terrain.Type == "Road"
? _terrains[0].Texture
: terrain.Texture));
var number = 0;
if (terrain.Type == "Sea" || terrain.Type == "BridgeSea")
number = (y > 0 && !_mapTerrains[y - 1, x].IsSea() ? 8 : 0)
+ (x < _mapWidth - 1 && !_mapTerrains[y, x + 1].IsSea() ? 4 : 0)
+ (y < _mapHeight - 1 && !_mapTerrains[y + 1, x].IsSea() ? 2 : 0)
+ (x > 0 && !_mapTerrains[y, x - 1].IsSea() ? 1 : 0);
else if (terrain.Type == "River" || terrain.Type == "BridgeRiver")
number = (y > 0 && !_mapTerrains[y - 1, x].IsRiver() ? 8 : 0)
+ (x < _mapWidth - 1 && !_mapTerrains[y, x + 1].IsRiver() ? 4 : 0)
+ (y < _mapHeight - 1 && !_mapTerrains[y + 1, x].IsRiver() ? 2 : 0)
+ (x > 0 && !_mapTerrains[y, x - 1].IsRiver() ? 1 : 0);
tex.Draw(
spriteBatch,
y / 100f + 0.1f,
new Vector2(
_gridWidth * x - _camera.X,
_gridHeight * y - _camera.Y + _gridHeight - _mapTerrains[y, x].Texture.Height),
number);
if ((terrain.Type == "Mist" || terrain.Type == "BridgeSea"
|| terrain.Type == "BridgeRiver" || terrain.Type == "Road")
&& _mapBuildings[y, x] == null)
_mapTerrains[y, x].Texture.Draw(
spriteBatch,
y / 100f + 0.101f,
new Vector2(
_gridWidth * x - _camera.X,
_gridHeight * y - _camera.Y + _gridHeight - _mapTerrains[y, x].Texture.Height),
terrain.Type == "Road" || terrain.Type == "BridgeSea" || terrain.Type == "BridgeRiver"
? (y > 0 && !_mapTerrains[y - 1, x].IsRoad() ? 8 : 0)
+ (x < _mapWidth - 1 && !_mapTerrains[y, x + 1].IsRoad() ? 4 : 0)
+ (y < _mapHeight - 1 && !_mapTerrains[y + 1, x].IsRoad() ? 2 : 0)
+ (x > 0 && !_mapTerrains[y, x - 1].IsRoad() ? 1 : 0)
: 0);
}
// Draw buildings
for (var y = 0; y < _mapHeight; ++y)
for (var x = 0; x < _mapWidth; ++x)
if (_mapBuildings[y, x] != null)
{
var texture = _texturesBuildings[_mapBuildings[y, x].Type];
var pos = new Vector2(
_gridWidth * x - _camera.X + (int)Math.Floor((double)(_gridWidth + texture.Width) / 2) - _gridWidth,
_gridHeight * y - texture.Height + _gridHeight - _camera.Y);
texture.Draw(
spriteBatch,
y / 100f + 0.103f,
pos,
_mapBuildings[y, x].Player == null ? 0 : _mapBuildings[y, x].Player.Version);
if (_mapBuildings[y, x].CaptureStatus < 20)
_capturing.Draw(spriteBatch, 0.91f, pos + new Vector2(0, texture.Height - 8));
}
// Draw units
foreach (var u in _units)
_texturesUnitsPreview[u.Type].Draw(
spriteBatch,
u.Position.Y / 100f + 0.106f,
_gridWidth * u.Position - _camera,
u.Player.Version - 1,
Color.White,
u.Player.Number == 1 ? SpriteEffects.FlipHorizontally : SpriteEffects.None);
// User Interface (15px per number)
// Context menu (popup)
if (_showContextMenu)
{
for (var i = 0; i < _contextMenus.Length; ++i)
{
var on = new Rectangle(_contextMenuPos.X + 2 - (int)_camera.X, _contextMenuPos.Y + 2 + 16 * i - (int)_camera.Y, _contextMaxWidth + 2 + _popupLeft.Width + _popupRight.Width, 16).Contains(Souris.Get().Position);
var dec = on ? 0.001f : 0;
(on ? _popupLeftOn : _popupLeft).Draw(spriteBatch, 0.94f + dec, new Vector2(_contextMenuPos.X, _contextMenuPos.Y + 16 * i) - _camera);
for (var j = 0; j < _contextMaxWidth + 2; ++j)
(on ? _popupMidOn : _popupMid).Draw(spriteBatch, 0.94f + dec, new Vector2(_contextMenuPos.X + j + _popupLeft.Width, _contextMenuPos.Y + 16 * i) - _camera);
(on ? _popupRightOn : _popupRight).Draw(spriteBatch, 0.94f + dec, new Vector2(_contextMenuPos.X + _contextMaxWidth + 2 + _popupLeft.Width, _contextMenuPos.Y + 16 * i) - _camera);
spriteBatch.DrawString(_fontPopup, _contextMenus[i], new Vector2(_contextMenuPos.X + 9, _contextMenuPos.Y + 16 * i + 3) - _camera, Color.Black, 0f, Vector2.Zero, 1.0f, SpriteEffects.None, 0.95f);
spriteBatch.DrawString(_fontPopup, _contextMenus[i], new Vector2(_contextMenuPos.X + 8, _contextMenuPos.Y + 16 * i + 2) - _camera, Color.White, 0f, Vector2.Zero, 1.0f, SpriteEffects.None, 0.96f);
}
}
// Cursor
if (_cursorPos != _nullCursor)
_cursor.Draw(spriteBatch, 0.899f, _cursorPos * _gridWidth - _camera);
spriteBatch.End();
// If the game is transitioning on or off, fade it out to black.
if (TransitionPosition > 0 || _pauseAlpha > 0)
ScreenManager.FadeBackBufferToBlack(MathHelper.Lerp(1f - TransitionAlpha, 1f, _pauseAlpha / 2));
}
private void SetContextMenu(string context, params string[] menus)
{
_contextMenuContext = context;
_contextMenus = menus;
_showContextMenu = true;
_contextMenuPos = new Point(Souris.Get().X + (int)_camera.X, Souris.Get().Y + (int)_camera.Y);
_contextMaxWidth = 0;
foreach (var m in menus)
{
var len = (int)_fontPopup.MeasureString(m).X;
if (len > _contextMaxWidth)
_contextMaxWidth = len;
}
}
}
}
| |
// Copyright (c) 2013 SharpYaml - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// -------------------------------------------------------------------------------
// SharpYaml is a fork of YamlDotNet https://github.com/aaubry/YamlDotNet
// published with the following license:
// -------------------------------------------------------------------------------
//
// Copyright (c) 2008, 2009, 2010, 2011, 2012 Antoine Aubry
//
// 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;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using NUnit.Framework;
using SharpYaml.Events;
using SharpYaml.Serialization;
using SharpYaml.Serialization.Serializers;
namespace SharpYaml.Tests.Serialization
{
public class SerializationTests : YamlTest
{
[Test]
public void Roundtrip()
{
var settings = new SerializerSettings();
settings.RegisterAssembly(typeof(SerializationTests).Assembly);
var serializer = new Serializer(settings);
var buffer = new StringWriter();
var original = new X();
serializer.Serialize(buffer, original);
Dump.WriteLine(buffer);
var bufferText = buffer.ToString();
var copy = serializer.Deserialize<X>(bufferText);
foreach (var property in typeof(X).GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (property.CanRead && property.CanWrite)
{
Assert.AreEqual(
property.GetValue(original, null),
property.GetValue(copy, null));
}
}
}
[Test]
public void RoundtripWithDefaults()
{
var settings = new SerializerSettings() {EmitDefaultValues = true};
settings.RegisterAssembly(typeof(SerializationTests).Assembly);
var serializer = new Serializer(settings);
var buffer = new StringWriter();
var original = new X();
serializer.Serialize(buffer, original);
Dump.WriteLine(buffer);
var bufferText = buffer.ToString();
var copy = serializer.Deserialize<X>(bufferText);
foreach (var property in typeof(X).GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (property.CanRead && property.CanWrite)
{
Assert.AreEqual(
property.GetValue(original, null),
property.GetValue(copy, null));
}
}
}
[Test]
public void CircularReference()
{
var serializer = new Serializer();
var buffer = new StringWriter();
var original = new Y();
original.Child = new Y {
Child = original,
Child2 = original
};
serializer.Serialize(buffer, original, typeof(Y));
Dump.WriteLine(buffer);
}
private class Y
{
public Y Child { get; set; }
public Y Child2 { get; set; }
}
[Test]
public void DeserializeScalar()
{
var sut = new Serializer();
var result = sut.Deserialize(YamlFile("test2.yaml"), typeof(object));
Assert.AreEqual("a scalar", result);
}
[Test]
public void DeserializeExplicitType()
{
var settings = new SerializerSettings();
settings.RegisterAssembly(typeof(SerializationTests).Assembly);
var serializer = new Serializer();
object result = serializer.Deserialize(YamlFile("explicitType.yaml"), typeof(object));
Assert.True(typeof(Z).IsAssignableFrom(result.GetType()));
Assert.AreEqual("bbb", ((Z)result).aaa);
}
[Test]
public void DeserializeDictionary()
{
var serializer = new Serializer();
var result = serializer.Deserialize(YamlFile("dictionary.yaml"));
Assert.True(typeof(IDictionary<object, object>).IsAssignableFrom(result.GetType()), "The deserialized object has the wrong type.");
var dictionary = (IDictionary<object, object>)result;
Assert.AreEqual("value1", dictionary["key1"]);
Assert.AreEqual("value2", dictionary["key2"]);
}
[Test]
public void DeserializeExplicitDictionary()
{
var serializer = new Serializer();
object result = serializer.Deserialize(YamlFile("dictionaryExplicit.yaml"));
Assert.True(typeof(IDictionary<string, int>).IsAssignableFrom(result.GetType()), "The deserialized object has the wrong type.");
var dictionary = (IDictionary<string, int>)result;
Assert.AreEqual(1, dictionary["key1"]);
Assert.AreEqual(2, dictionary["key2"]);
}
[Test]
public void DeserializeListOfDictionaries()
{
var serializer = new Serializer();
var result = serializer.Deserialize(YamlFile("listOfDictionaries.yaml"), typeof(List<Dictionary<string, string>>));
Assert.IsInstanceOf<List<Dictionary<string, string>>>(result);
var list = (List<Dictionary<string, string>>)result;
Assert.AreEqual("conn1", list[0]["connection"]);
Assert.AreEqual("path1", list[0]["path"]);
Assert.AreEqual("conn2", list[1]["connection"]);
Assert.AreEqual("path2", list[1]["path"]);
}
[Test]
public void DeserializeList()
{
var serializer = new Serializer();
var result = serializer.Deserialize(YamlFile("list.yaml"));
Assert.True(typeof(IList).IsAssignableFrom(result.GetType()));
var list = (IList)result;
Assert.AreEqual("one", list[0]);
Assert.AreEqual("two", list[1]);
Assert.AreEqual("three", list[2]);
}
[Test]
public void DeserializeExplicitList()
{
var serializer = new Serializer();
var result = serializer.Deserialize(YamlFile("listExplicit.yaml"));
Assert.True(typeof(IList<int>).IsAssignableFrom(result.GetType()));
var list = (IList<int>)result;
Assert.AreEqual(3, list[0]);
Assert.AreEqual(4, list[1]);
Assert.AreEqual(5, list[2]);
}
[Test]
public void DeserializeEnumerable()
{
var settings = new SerializerSettings();
settings.RegisterAssembly(typeof(SerializationTests).Assembly);
var serializer = new Serializer(settings);
var buffer = new StringWriter();
var z = new[] { new Z { aaa = "Yo" }};
serializer.Serialize(buffer, z);
var bufferAsText = buffer.ToString();
var result = (IEnumerable<Z>)serializer.Deserialize(bufferAsText, typeof(IEnumerable<Z>));
Assert.AreEqual(1, result.Count());
Assert.AreEqual("Yo", result.First().aaa);
}
[Test]
public void RoundtripList()
{
var serializer = new Serializer();
var buffer = new StringWriter();
var original = new List<int> { 2, 4, 6 };
serializer.Serialize(buffer, original, typeof(List<int>));
Dump.WriteLine(buffer);
var copy = (List<int>) serializer.Deserialize(new StringReader(buffer.ToString()), typeof(List<int>));
Assert.AreEqual(original.Count, copy.Count);
for (int i = 0; i < original.Count; ++i)
{
Assert.AreEqual(original[i], copy[i]);
}
}
[Test]
public void DeserializeArray()
{
var serializer = new Serializer();
var result = serializer.Deserialize(YamlFile("list.yaml"), typeof(String[]));
Assert.True(result is String[]);
var array = (String[])result;
Assert.AreEqual("one", array[0]);
Assert.AreEqual("two", array[1]);
Assert.AreEqual("three", array[2]);
}
[Test]
public void Enums()
{
var settings = new SerializerSettings();
settings.RegisterAssembly(typeof(StringFormatFlags).Assembly);
var serializer = new Serializer(settings);
var flags = StringFormatFlags.NoClip | StringFormatFlags.NoFontFallback;
var buffer = new StringWriter();
serializer.Serialize(buffer, flags);
var bufferAsText = buffer.ToString();
var deserialized = (StringFormatFlags)serializer.Deserialize(bufferAsText, typeof(StringFormatFlags));
Assert.AreEqual(flags, deserialized);
}
[Test]
public void CustomTags()
{
var settings = new SerializerSettings();
settings.RegisterTagMapping("tag:yaml.org,2002:point", typeof(Point));
var serializer = new Serializer(settings);
var result = serializer.Deserialize(YamlFile("tags.yaml"));
Assert.AreEqual(typeof(Point), result.GetType());
var value = (Point)result;
Assert.AreEqual(10, value.X);
Assert.AreEqual(20, value.Y);
}
// Convertible are not supported
//[Test]
//public void DeserializeConvertible()
//{
// var settings = new SerializerSettings();
// settings.RegisterAssembly(typeof(SerializationTests).Assembly);
// settings.RegisterSerializerFactory(new TypeConverterSerializerFactory());
// var serializer = new Serializer(settings);
// var result = serializer.Deserialize(YamlFile("convertible.yaml"), typeof(Z));
// Assert.True(typeof(Z).IsAssignableFrom(result.GetType()));
// Assert.AreEqual("[hello, world]", ((Z)result).aaa);
//}
[Test]
public void RoundtripWithTypeConverter()
{
var buffer = new StringWriter();
var x = new SomeCustomType("Yo");
var settings = new SerializerSettings();
settings.RegisterSerializerFactory(new CustomTypeConverter());
var serializer = new Serializer(settings);
serializer.Serialize(buffer, x);
Dump.WriteLine(buffer);
var bufferText = buffer.ToString();
var copy = serializer.Deserialize<SomeCustomType>(bufferText);
Assert.AreEqual("Yo", copy.Value);
}
class SomeCustomType {
// Test specifically with no parameterless, supposed to fail unless a type converter is specified
public SomeCustomType(string value) { Value = value; }
public string Value;
}
public class CustomTypeConverter : ScalarSerializerBase, IYamlSerializableFactory {
public IYamlSerializable TryCreate(SerializerContext context, ITypeDescriptor typeDescriptor)
{
return typeDescriptor.Type == typeof (SomeCustomType) ? this : null;
}
public override object ConvertFrom(ref ObjectContext context, Scalar fromScalar)
{
return new SomeCustomType(fromScalar.Value);
}
public override string ConvertTo(ref ObjectContext objectContext)
{
return ((SomeCustomType) objectContext.Instance).Value;
}
}
[Test]
public void RoundtripDictionary()
{
var entries = new Dictionary<string, string>
{
{ "key1", "value1" },
{ "key2", "value2" },
{ "key3", "value3" },
};
var buffer = new StringWriter();
var serializer = new Serializer();
serializer.Serialize(buffer, entries);
Dump.WriteLine(buffer);
var deserialized = serializer.Deserialize<Dictionary<string, string>>(new StringReader(buffer.ToString()));
foreach (var pair in deserialized)
{
Assert.AreEqual(entries[pair.Key], pair.Value);
}
}
[Test]
public void SerializeAnonymousType()
{
var data = new { Key = 3 };
var serializer = new Serializer();
var buffer = new StringWriter();
serializer.Serialize(buffer, data);
Dump.WriteLine(buffer);
var bufferText = buffer.ToString();
var parsed = serializer.Deserialize<Dictionary<string, string>>(bufferText);
Assert.NotNull(parsed);
Assert.AreEqual(1, parsed.Count);
Assert.True(parsed.ContainsKey("Key"));
Assert.AreEqual(parsed["Key"], "3");
}
[Test]
public void SerializationIncludesDefaultValueWhenAsked()
{
var settings = new SerializerSettings() {EmitDefaultValues = true};
settings.RegisterAssembly(typeof(X).Assembly);
var serializer = new Serializer(settings);
var buffer = new StringWriter();
var original = new X();
serializer.Serialize(buffer, original, typeof(X));
Dump.WriteLine(buffer);
var bufferText = buffer.ToString();
Assert.True(bufferText.Contains("MyString"));
}
[Test]
public void SerializationDoesNotIncludeDefaultValueWhenNotAsked()
{
var settings = new SerializerSettings() { EmitDefaultValues = false };
settings.RegisterAssembly(typeof(X).Assembly);
var serializer = new Serializer(settings);
var buffer = new StringWriter();
var original = new X();
serializer.Serialize(buffer, original, typeof(X));
Dump.WriteLine(buffer);
var bufferText = buffer.ToString();
Assert.False(bufferText.Contains("MyString"));
}
[Test]
public void SerializationOfNullWorksInJson()
{
var settings = new SerializerSettings() { EmitDefaultValues = true, EmitJsonComptible = true };
settings.RegisterAssembly(typeof(X).Assembly);
var serializer = new Serializer(settings);
var buffer = new StringWriter();
var original = new X { MyString = null };
serializer.Serialize(buffer, original, typeof(X));
Dump.WriteLine(buffer);
var bufferText = buffer.ToString();
Assert.True(bufferText.Contains("MyString"));
}
[Test]
public void DeserializationOfNullWorksInJson()
{
var settings = new SerializerSettings() { EmitDefaultValues = true, EmitJsonComptible = true };
settings.RegisterAssembly(typeof(X).Assembly);
var serializer = new Serializer(settings);
var buffer = new StringWriter();
var original = new X { MyString = null };
serializer.Serialize(buffer, original, typeof(X));
Dump.WriteLine(buffer);
var bufferText = buffer.ToString();
var copy = (X) serializer.Deserialize(bufferText, typeof(X));
Assert.Null(copy.MyString);
}
[Test]
public void SerializationRespectsYamlIgnoreAttribute()
{
var settings = new SerializerSettings();
settings.RegisterAssembly(typeof(ContainsIgnore).Assembly);
var serializer = new Serializer(settings);
var buffer = new StringWriter();
var orig = new ContainsIgnore();
serializer.Serialize(buffer, orig);
Dump.WriteLine(buffer);
var copy = (ContainsIgnore) serializer.Deserialize(new StringReader(buffer.ToString()), typeof(ContainsIgnore));
Assert.Throws<NotImplementedException>(() =>
{
if (copy.IgnoreMe == null)
{
}
});
}
class ContainsIgnore
{
[YamlIgnore]
public String IgnoreMe
{
get { throw new NotImplementedException("Accessing a [YamlIgnore] property"); }
set { throw new NotImplementedException("Accessing a [YamlIgnore] property"); }
}
}
[Test]
public void SerializeArrayOfIdenticalObjects()
{
var obj1 = new Z { aaa = "abc" };
var objects = new[] { obj1, obj1, obj1 };
var result = SerializeThenDeserialize(objects);
Assert.NotNull(result);
Assert.AreEqual(3, result.Length);
Assert.AreEqual(obj1.aaa, result[0].aaa);
Assert.AreEqual(obj1.aaa, result[1].aaa);
Assert.AreEqual(obj1.aaa, result[2].aaa);
Assert.AreSame(result[0], result[1]);
Assert.AreSame(result[1], result[2]);
}
private T SerializeThenDeserialize<T>(T input)
{
var serializer = new Serializer();
var writer = new StringWriter();
serializer.Serialize(writer, input, typeof(T));
var serialized = writer.ToString();
Dump.WriteLine("serialized =\n-----\n{0}", serialized);
return serializer.Deserialize<T>(new StringReader(serialized));
}
public class Z {
public string aaa { get; set; }
}
[Test]
public void RoundtripAlias()
{
var input = new ConventionTest { AliasTest = "Fourth" };
var serializer = new Serializer();
var writer = new StringWriter();
serializer.Serialize(writer, input, input.GetType());
var serialized = writer.ToString();
// Ensure serialisation is correct
Assert.True(serialized.Contains("fourthTest: Fourth"));
var output = serializer.Deserialize<ConventionTest>(serialized);
// Ensure round-trip retains value
Assert.AreEqual(input.AliasTest, output.AliasTest);
}
private class ConventionTest {
[DefaultValue(null)]
public string FirstTest { get; set; }
[DefaultValue(null)]
public string SecondTest { get; set; }
[DefaultValue(null)]
public string ThirdTest { get; set; }
[YamlMember("fourthTest")]
public string AliasTest { get; set; }
[YamlIgnore]
public string fourthTest { get; set; }
}
[Test]
public void DefaultValueAttributeIsUsedWhenPresentWithoutEmitDefaults()
{
var input = new HasDefaults { Value = HasDefaults.DefaultValue };
var serializer = new Serializer();
var writer = new StringWriter();
serializer.Serialize(writer, input);
var serialized = writer.ToString();
Dump.WriteLine(serialized);
Assert.False(serialized.Contains("Value"));
}
[Test]
public void DefaultValueAttributeIsIgnoredWhenPresentWithEmitDefaults()
{
var input = new HasDefaults { Value = HasDefaults.DefaultValue };
var serializer = new Serializer(new SerializerSettings() { EmitDefaultValues = true});
var writer = new StringWriter();
serializer.Serialize(writer, input);
var serialized = writer.ToString();
Dump.WriteLine(serialized);
Assert.True(serialized.Contains("Value"));
}
[Test]
public void DefaultValueAttributeIsIgnoredWhenValueIsDifferent()
{
var input = new HasDefaults { Value = "non-default" };
var serializer = new Serializer();
var writer = new StringWriter();
serializer.Serialize(writer, input);
var serialized = writer.ToString();
Dump.WriteLine(serialized);
Assert.True(serialized.Contains("Value"));
}
public class HasDefaults {
public const string DefaultValue = "myDefault";
[DefaultValue(DefaultValue)]
public string Value { get; set; }
}
[Test]
public void NullValuesInListsAreAlwaysEmittedWithoutEmitDefaults()
{
var input = new[] { "foo", null, "bar" };
var serializer = new Serializer(new SerializerSettings() { LimitPrimitiveFlowSequence = 0 });
var writer = new StringWriter();
serializer.Serialize(writer, input);
var serialized = writer.ToString();
Dump.WriteLine(serialized);
Assert.AreEqual(3, Regex.Matches(serialized, "-").Count);
}
[Test]
public void NullValuesInListsAreAlwaysEmittedWithEmitDefaults()
{
var input = new[] { "foo", null, "bar" };
var serializer = new Serializer(new SerializerSettings() { EmitDefaultValues = true, LimitPrimitiveFlowSequence = 0});
var writer = new StringWriter();
serializer.Serialize(writer, input);
var serialized = writer.ToString();
Dump.WriteLine(serialized);
Assert.AreEqual(3, Regex.Matches(serialized, "-").Count);
}
[Test]
public void DeserializeTwoDocuments()
{
var yaml = @"---
Name: Andy
---
Name: Brad
...";
var serializer = new Serializer();
var reader = new EventReader(new Parser(new StringReader(yaml)));
reader.Expect<StreamStart>();
var andy = serializer.Deserialize<Person>(reader);
Assert.NotNull(andy);
Assert.AreEqual("Andy", andy.Name);
var brad = serializer.Deserialize<Person>(reader);
Assert.NotNull(brad);
Assert.AreEqual("Brad", brad.Name);
}
[Test]
public void DeserializeManyDocuments()
{
var yaml = @"---
Name: Andy
---
Name: Brad
---
Name: Charles
...";
var serializer = new Serializer();
var reader = new EventReader(new Parser(new StringReader(yaml)));
reader.Allow<StreamStart>();
var people = new List<Person>();
while (!reader.Accept<StreamEnd>())
{
var person = serializer.Deserialize<Person>(reader);
people.Add(person);
}
Assert.AreEqual(3, people.Count);
Assert.AreEqual("Andy", people[0].Name);
Assert.AreEqual("Brad", people[1].Name);
Assert.AreEqual("Charles", people[2].Name);
}
public class Person {
public string Name { get; set; }
}
[Test]
public void DeserializeEmptyDocument()
{
var serializer = new Serializer();
var array = (int[])serializer.Deserialize(new StringReader(""), typeof(int[]));
Assert.Null(array);
}
[Test]
public void SerializeGenericDictionaryShouldNotThrowTargetException()
{
var serializer = new Serializer();
var buffer = new StringWriter();
serializer.Serialize(buffer, new OnlyGenericDictionary
{
{ "hello", "world" },
});
}
private class OnlyGenericDictionary : IDictionary<string, string>
{
private readonly Dictionary<string, string> _dictionary = new Dictionary<string, string>();
#region IDictionary<string,string> Members
public void Add(string key, string value)
{
_dictionary.Add(key, value);
}
public bool ContainsKey(string key)
{
throw new NotImplementedException();
}
public ICollection<string> Keys
{
get { throw new NotImplementedException(); }
}
public bool Remove(string key)
{
throw new NotImplementedException();
}
public bool TryGetValue(string key, out string value)
{
throw new NotImplementedException();
}
public ICollection<string> Values
{
get { throw new NotImplementedException(); }
}
public string this[string key]
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
#endregion
#region ICollection<KeyValuePair<string,string>> Members
public void Add(KeyValuePair<string, string> item)
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
public bool Contains(KeyValuePair<string, string> item)
{
throw new NotImplementedException();
}
public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex)
{
throw new NotImplementedException();
}
public int Count
{
get { throw new NotImplementedException(); }
}
public bool IsReadOnly
{
get { throw new NotImplementedException(); }
}
public bool Remove(KeyValuePair<string, string> item)
{
throw new NotImplementedException();
}
#endregion
#region IEnumerable<KeyValuePair<string,string>> Members
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
return _dictionary.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return _dictionary.GetEnumerator();
}
#endregion
}
[Test]
public void UndefinedForwardReferencesFail()
{
var serializer = new Serializer();
Assert.Throws<AnchorNotFoundException>(() =>
serializer.Deserialize<X>(YamlText(@"
Nothing: *forward
MyString: ForwardReference
"))
);
}
private class X
{
[DefaultValue(false)]
public bool MyFlag { get; set; }
[DefaultValue(null)]
public string Nothing { get; set; }
[DefaultValue(1234)]
public int MyInt { get; set; }
[DefaultValue(6789.1011)]
public double MyDouble { get; set; }
[DefaultValue("Hello world")]
public string MyString { get; set; }
public DateTime MyDate { get; set; }
public TimeSpan MyTimeSpan { get; set; }
public Point MyPoint { get; set; }
[DefaultValue(8)]
public int? MyNullableWithValue { get; set; }
[DefaultValue(null)]
public int? MyNullableWithoutValue { get; set; }
public X()
{
MyInt = 1234;
MyDouble = 6789.1011;
MyString = "Hello world";
MyDate = DateTime.Now;
MyTimeSpan = TimeSpan.FromHours(1);
MyPoint = new Point(100, 200);
MyNullableWithValue = 8;
}
}
}
}
| |
using NUnit.Framework;
using Spart;
namespace SIL.WritingSystems.Tests
{
[TestFixture]
public class SimpleCollationRulesParserTests
{
private const string IcuStart = "&[before 1] [first regular] < ";
static private void VerifyIcuRules(string icuRules)
{
new IcuRulesCollator(icuRules);
}
static private void VerifyParserError(string errorId, string rules, long line, long column)
{
try
{
var parser = new SimpleRulesParser();
parser.ConvertToIcuRules(rules);
}
catch (ParserErrorException e)
{
Assert.AreEqual(errorId, e.ParserError.ErrorId);
Assert.AreEqual(line, e.ParserError.Line);
Assert.AreEqual(column, e.ParserError.Column);
throw;
}
}
static private void VerifyParseIsSyntacticEquivalent(string simplestRule, string syntacticEquivalent)
{
var parser = new SimpleRulesParser();
string expected = parser.ConvertToIcuRules(simplestRule);
string actual = parser.ConvertToIcuRules(syntacticEquivalent);
Assert.AreEqual(expected, actual);
}
static private void VerifyExpectedIcuFromActualSimple(string icuExpected, string shoeboxActual)
{
var parser = new SimpleRulesParser();
string icuRulesActual = parser.ConvertToIcuRules(shoeboxActual);
VerifyIcuRules(icuExpected);
Assert.AreEqual(icuExpected, icuRulesActual);
}
[Test]
public void ConvertToIcuRules_Empty()
{
VerifyExpectedIcuFromActualSimple(string.Empty, string.Empty);
}
[Test]
public void ConvertToIcuRules_Blank()
{
VerifyParseIsSyntacticEquivalent(string.Empty, "\n");
VerifyParseIsSyntacticEquivalent(string.Empty, " ");
VerifyParseIsSyntacticEquivalent(string.Empty, "\n ");
VerifyParseIsSyntacticEquivalent(string.Empty, " \n");
VerifyParseIsSyntacticEquivalent(string.Empty, " \n ");
VerifyParseIsSyntacticEquivalent(string.Empty, "\n\n");
VerifyParseIsSyntacticEquivalent(string.Empty, "\n\n ");
VerifyParseIsSyntacticEquivalent(string.Empty, " \n\n");
VerifyParseIsSyntacticEquivalent(string.Empty, " \n\n ");
VerifyParseIsSyntacticEquivalent(string.Empty, "\n \n");
VerifyParseIsSyntacticEquivalent(string.Empty, " \n \n");
VerifyParseIsSyntacticEquivalent(string.Empty, " \n \n ");
VerifyParseIsSyntacticEquivalent(string.Empty, "\n\n\n");
VerifyParseIsSyntacticEquivalent(string.Empty, "\n \n \n ");
}
[Test]
public void ConvertToIcuRules_Digraph()
{
VerifyExpectedIcuFromActualSimple(IcuStart + "n < ng", "n\nng");
}
[Test]
public void ConvertToIcuRules_SecondarySegments()
{
VerifyExpectedIcuFromActualSimple(IcuStart + "b << B < a << A", "b B\na A");
}
[Test]
public void ConvertToIcuRules_SegmentsWithinParenthesis_ConsideredTertiary()
{
VerifyExpectedIcuFromActualSimple(IcuStart + "b << B < \u0101 << a <<< A", "b B\n\\u0101 (a A)");
VerifyExpectedIcuFromActualSimple(IcuStart + "b << B < \u0101 <<< a << A", "b B\n(\\u0101 a) A");
}
[Test]
public void ConvertToIcuRules_PaddedWithWhiteSpace()
{
VerifyExpectedIcuFromActualSimple(IcuStart + "b <<< B < \u0101 <<< a <<< A", "(b \t B \t ) \n (\t\\u0101 \ta A\t)\t");
}
[Test]
public void ConvertToIcuRules_Parse()
{
VerifyExpectedIcuFromActualSimple(
IcuStart + "a <<< A << \u3022 <<< \u3064 < b << B < c <<< C < e <<< E << e\u3000 <<< E\u3000 < ng << Ng << NG < \u1234\u1234\u1234",
" \n ( a A ) (\\u3022 \\u3064)\n\nb B\n(c C)\n(e E)(e\\u3000 E\\u3000)\n \n ng Ng NG\n\\u1234\\u1234\\u1234");
}
[Test]
public void ConvertToIcuRules_SingleElement()
{
VerifyExpectedIcuFromActualSimple(IcuStart + "a", "a");
}
[Test]
public void ConvertToIcuRules_NoHyphenInRules_HasIgnoreHyphen()
{
//&[last primary ignorable] <<< '-' <<<
VerifyExpectedIcuFromActualSimple(IcuStart + "a", "a");
}
[Test]
public void ConvertToIcuRules_SingleElementWithBlanks()
{
VerifyParseIsSyntacticEquivalent("a", "a ");
VerifyParseIsSyntacticEquivalent("a", " a");
VerifyParseIsSyntacticEquivalent("a", " a ");
VerifyParseIsSyntacticEquivalent("a", "a\n");
VerifyParseIsSyntacticEquivalent("a", "\na");
VerifyParseIsSyntacticEquivalent("a", "\na\n");
VerifyParseIsSyntacticEquivalent("a", "\na ");
VerifyParseIsSyntacticEquivalent("a", "\n a");
VerifyParseIsSyntacticEquivalent("a", "\n a ");
VerifyParseIsSyntacticEquivalent("a", "\n\na");
VerifyParseIsSyntacticEquivalent("a", "\n\na\n");
VerifyParseIsSyntacticEquivalent("a", "a \n");
VerifyParseIsSyntacticEquivalent("a", " a\n");
VerifyParseIsSyntacticEquivalent("a", " a \n");
VerifyParseIsSyntacticEquivalent("a", "a\n\n");
VerifyParseIsSyntacticEquivalent("a", "\na\n");
VerifyParseIsSyntacticEquivalent("a", "\na\n\n");
VerifyParseIsSyntacticEquivalent("a", " a");
VerifyParseIsSyntacticEquivalent("a", " a ");
VerifyParseIsSyntacticEquivalent("a", " a\n");
VerifyParseIsSyntacticEquivalent("a", " \na");
VerifyParseIsSyntacticEquivalent("a", " \na\n");
VerifyParseIsSyntacticEquivalent("a", "a ");
VerifyParseIsSyntacticEquivalent("a", " a ");
VerifyParseIsSyntacticEquivalent("a", "a\n ");
VerifyParseIsSyntacticEquivalent("a", "\na ");
VerifyParseIsSyntacticEquivalent("a", "\na\n ");
VerifyParseIsSyntacticEquivalent("a", " \na \n");
VerifyParseIsSyntacticEquivalent("a", "\n a\n ");
VerifyParseIsSyntacticEquivalent("a", " \n a \n ");
}
[Test]
public void ConvertToIcuRules_SingleUnicodeEscChar()
{
VerifyExpectedIcuFromActualSimple(IcuStart + "a", "\\u0061");
}
[Test]
public void ConvertToIcuRules_SingleUnicodeEscCharWithBlanks()
{
VerifyParseIsSyntacticEquivalent("a", "\\u0061 ");
VerifyParseIsSyntacticEquivalent("a", " \\u0061");
VerifyParseIsSyntacticEquivalent("a", " \\u0061 ");
VerifyParseIsSyntacticEquivalent("a", "\\u0061\n");
VerifyParseIsSyntacticEquivalent("a", "\n\\u0061");
VerifyParseIsSyntacticEquivalent("a", "\n\\u0061\n");
VerifyParseIsSyntacticEquivalent("a", "\n\\u0061 ");
VerifyParseIsSyntacticEquivalent("a", "\n \\u0061");
VerifyParseIsSyntacticEquivalent("a", "\n \\u0061 ");
VerifyParseIsSyntacticEquivalent("a", "\n\n\\u0061");
VerifyParseIsSyntacticEquivalent("a", "\n\n\\u0061\n");
VerifyParseIsSyntacticEquivalent("a", "\\u0061 \n");
VerifyParseIsSyntacticEquivalent("a", " \\u0061\n");
VerifyParseIsSyntacticEquivalent("a", " \\u0061 \n");
VerifyParseIsSyntacticEquivalent("a", "\\u0061\n\n");
VerifyParseIsSyntacticEquivalent("a", "\n\\u0061\n");
VerifyParseIsSyntacticEquivalent("a", "\n\\u0061\n\n");
VerifyParseIsSyntacticEquivalent("a", " \\u0061");
VerifyParseIsSyntacticEquivalent("a", " \\u0061 ");
VerifyParseIsSyntacticEquivalent("a", " \\u0061\n");
VerifyParseIsSyntacticEquivalent("a", " \n\\u0061");
VerifyParseIsSyntacticEquivalent("a", " \n\\u0061\n");
VerifyParseIsSyntacticEquivalent("a", "\\u0061 ");
VerifyParseIsSyntacticEquivalent("a", " \\u0061 ");
VerifyParseIsSyntacticEquivalent("a", "\\u0061\n ");
VerifyParseIsSyntacticEquivalent("a", "\n\\u0061 ");
VerifyParseIsSyntacticEquivalent("a", "\n\\u0061\n ");
}
[Test]
public void ConvertToIcuRules_TwoSingleElements()
{
var parser = new SimpleRulesParser();
string result = parser.ConvertToIcuRules("a A");
Assert.AreEqual(IcuStart + "a << A", result);
}
[Test]
public void ConvertToIcuRules_TwoSingleElementsWithBlanks()
{
VerifyParseIsSyntacticEquivalent("a A", "a A ");
VerifyParseIsSyntacticEquivalent("a A", " a A");
VerifyParseIsSyntacticEquivalent("a A", " a A ");
VerifyParseIsSyntacticEquivalent("a A", "a A");
VerifyParseIsSyntacticEquivalent("a A", " a A ");
VerifyParseIsSyntacticEquivalent("a A", "\na A");
VerifyParseIsSyntacticEquivalent("a A", "\na A ");
VerifyParseIsSyntacticEquivalent("a A", "\n a A");
VerifyParseIsSyntacticEquivalent("a A", "\n a A ");
VerifyParseIsSyntacticEquivalent("a A", "\na A");
VerifyParseIsSyntacticEquivalent("a A", "\n a A ");
VerifyParseIsSyntacticEquivalent("a A", "a A\n");
VerifyParseIsSyntacticEquivalent("a A", "a A \n");
VerifyParseIsSyntacticEquivalent("a A", " a A\n");
VerifyParseIsSyntacticEquivalent("a A", " a A \n");
VerifyParseIsSyntacticEquivalent("a A", "a A\n");
VerifyParseIsSyntacticEquivalent("a A", " a A \n");
VerifyParseIsSyntacticEquivalent("a A", "\na A\n");
VerifyParseIsSyntacticEquivalent("a A", " \na A \n");
VerifyParseIsSyntacticEquivalent("a A", "\n a A\n ");
VerifyParseIsSyntacticEquivalent("a A", " \n a A \n ");
}
[Test]
public void ConvertToIcuRules_TwoSingleElementsInGroup()
{
VerifyExpectedIcuFromActualSimple(IcuStart + "a <<< A", "(a A)");
}
[Test]
public void ConvertToIcuRules_TwoSingleElementsInGroupWithBlanks()
{
VerifyParseIsSyntacticEquivalent("(a A)", " (a A)");
VerifyParseIsSyntacticEquivalent("(a A)", " (a A) ");
VerifyParseIsSyntacticEquivalent("(a A)", "\n(a A)");
VerifyParseIsSyntacticEquivalent("(a A)", "(a A)\n");
VerifyParseIsSyntacticEquivalent("(a A)", "\n(a A)\n");
VerifyParseIsSyntacticEquivalent("(a A)", " \n(a A) \n");
VerifyParseIsSyntacticEquivalent("(a A)", "\n (a A)\n ");
VerifyParseIsSyntacticEquivalent("(a A)", " \n (a A) \n ");
VerifyParseIsSyntacticEquivalent("(a A)", "( a A)");
VerifyParseIsSyntacticEquivalent("(a A)", " ( a A)");
VerifyParseIsSyntacticEquivalent("(a A)", " ( a A) ");
VerifyParseIsSyntacticEquivalent("(a A)", "\n( a A)");
VerifyParseIsSyntacticEquivalent("(a A)", "( a A)\n");
VerifyParseIsSyntacticEquivalent("(a A)", "\n( a A)\n");
VerifyParseIsSyntacticEquivalent("(a A)", " \n( a A) \n");
VerifyParseIsSyntacticEquivalent("(a A)", "\n ( a A)\n ");
VerifyParseIsSyntacticEquivalent("(a A)", " \n ( a A) \n ");
VerifyParseIsSyntacticEquivalent("(a A)", "(a A )");
VerifyParseIsSyntacticEquivalent("(a A)", " (a A )");
VerifyParseIsSyntacticEquivalent("(a A)", " (a A ) ");
VerifyParseIsSyntacticEquivalent("(a A)", "\n(a A )");
VerifyParseIsSyntacticEquivalent("(a A)", "(a A )\n");
VerifyParseIsSyntacticEquivalent("(a A)", "\n(a A )\n");
VerifyParseIsSyntacticEquivalent("(a A)", " \n(a A ) \n");
VerifyParseIsSyntacticEquivalent("(a A)", "\n (a A )\n ");
VerifyParseIsSyntacticEquivalent("(a A)", " \n (a A ) \n ");
VerifyParseIsSyntacticEquivalent("(a A)", "( a A )");
VerifyParseIsSyntacticEquivalent("(a A)", " ( a A )");
VerifyParseIsSyntacticEquivalent("(a A)", " ( a A ) ");
VerifyParseIsSyntacticEquivalent("(a A)", "\n( a A )");
VerifyParseIsSyntacticEquivalent("(a A)", "( a A )\n");
VerifyParseIsSyntacticEquivalent("(a A)", "\n( a A )\n");
VerifyParseIsSyntacticEquivalent("(a A)", " \n( a A ) \n");
VerifyParseIsSyntacticEquivalent("(a A)", "\n ( a A )\n ");
VerifyParseIsSyntacticEquivalent("(a A)", " \n ( a A ) \n ");
}
[Test]
public void ConvertToIcuRules_TwoSingleElementsOnSeparateLines()
{
VerifyExpectedIcuFromActualSimple(IcuStart + "a < A", "a\nA");
}
[Test]
public void ConvertToIcuRules_TwoSingleElementsOnSeparateLinesWithBlanks()
{
VerifyParseIsSyntacticEquivalent("a\nA", " a\nA");
VerifyParseIsSyntacticEquivalent("a\nA", " a\nA ");
VerifyParseIsSyntacticEquivalent("a\nA", "\na\nA");
VerifyParseIsSyntacticEquivalent("a\nA", "a\nA\n");
VerifyParseIsSyntacticEquivalent("a\nA", "\na\nA\n");
VerifyParseIsSyntacticEquivalent("a\nA", " \na\nA \n");
VerifyParseIsSyntacticEquivalent("a\nA", "\n a\nA\n ");
VerifyParseIsSyntacticEquivalent("a\nA", " \n a\nA \n ");
VerifyParseIsSyntacticEquivalent("a\nA", "a \nA");
VerifyParseIsSyntacticEquivalent("a\nA", " a \nA");
VerifyParseIsSyntacticEquivalent("a\nA", " a \nA ");
VerifyParseIsSyntacticEquivalent("a\nA", "\na \nA");
VerifyParseIsSyntacticEquivalent("a\nA", "a \nA\n");
VerifyParseIsSyntacticEquivalent("a\nA", "\na \nA\n");
VerifyParseIsSyntacticEquivalent("a\nA", " \na \nA \n");
VerifyParseIsSyntacticEquivalent("a\nA", "\n a \nA\n ");
VerifyParseIsSyntacticEquivalent("a\nA", " \n a \nA \n ");
VerifyParseIsSyntacticEquivalent("a\nA", "a\n A");
VerifyParseIsSyntacticEquivalent("a\nA", " a\n A");
VerifyParseIsSyntacticEquivalent("a\nA", " a\n A ");
VerifyParseIsSyntacticEquivalent("a\nA", "\na\n A");
VerifyParseIsSyntacticEquivalent("a\nA", "a\n A\n");
VerifyParseIsSyntacticEquivalent("a\nA", "\na\n A\n");
VerifyParseIsSyntacticEquivalent("a\nA", " \na\n A \n");
VerifyParseIsSyntacticEquivalent("a\nA", "\n a\n A\n ");
VerifyParseIsSyntacticEquivalent("a\nA", " \n a\n A \n ");
VerifyParseIsSyntacticEquivalent("a\nA", "a \n A");
VerifyParseIsSyntacticEquivalent("a\nA", " a \n A");
VerifyParseIsSyntacticEquivalent("a\nA", " a \n A ");
VerifyParseIsSyntacticEquivalent("a\nA", "\na \n A");
VerifyParseIsSyntacticEquivalent("a\nA", "a \n A\n");
VerifyParseIsSyntacticEquivalent("a\nA", "\na \n A\n");
VerifyParseIsSyntacticEquivalent("a\nA", " \na \n A \n");
VerifyParseIsSyntacticEquivalent("a\nA", "\n a \n A\n ");
VerifyParseIsSyntacticEquivalent("a\nA", " \n a \n A \n ");
}
[Test]
public void ConvertToIcuRules_ThreeSingleElementsOnSeparateLines()
{
VerifyExpectedIcuFromActualSimple(IcuStart + "c < b < a", "c\nb\na");
}
[Test]
public void ConvertToIcuRules_TwoSingleElementsOnSeparateLinesWithBlankLines()
{
VerifyExpectedIcuFromActualSimple(IcuStart + "a < b", "\n a \n \n b \n");
}
[Test]
public void ConvertToIcuRules_ThreeSingleCharactersOnSameLine()
{
VerifyExpectedIcuFromActualSimple(IcuStart + "a << A << \u0301", "a A \\u0301");
}
[Test]
public void ConvertToIcuRules_ThreeSingleCharactersInParenthesis()
{
VerifyExpectedIcuFromActualSimple(IcuStart + "a <<< A <<< \u0301", "(a A \\u0301)");
}
[Test]
public void ConvertToIcuRules_GroupFollowedBySingleCharacter()
{
VerifyExpectedIcuFromActualSimple(IcuStart + "a <<< A << \u0301", "(a A)\\u0301");
}
[Test]
public void ConvertToIcuRules_GroupFollowedBySingleCharacterWithBlanks()
{
VerifyParseIsSyntacticEquivalent("(a A)\\u0301", "(a A) \\u0301");
VerifyParseIsSyntacticEquivalent("(a A)\\u0301", "(a A )\\u0301");
VerifyParseIsSyntacticEquivalent("(a A)\\u0301", " ( a A ) \\u0301 ");
}
[Test]
public void ConvertToIcuRules_SingleCharacterFollowedByGroup()
{
VerifyExpectedIcuFromActualSimple(IcuStart + "a << A <<< \u0301", "a(A \\u0301)");
}
[Test]
public void ConvertToIcuRules_SingleCharacterFollowedByGroupWithBlanks()
{
VerifyParseIsSyntacticEquivalent("a(A \\u0301)", "a (A \\u0301)");
VerifyParseIsSyntacticEquivalent("a(A \\u0301)", " a (A \\u0301) ");
VerifyParseIsSyntacticEquivalent("a(A \\u0301)", " a ( A \\u0301 ) ");
}
[Test]
public void ConvertToIcuRules_MultipleCharactersFormingCollationElement()
{
VerifyExpectedIcuFromActualSimple(IcuStart + "abcd << ab\u1234cd", "abcd ab\\u1234cd");
}
[Test]
public void ConvertToIcuRules_ParenthesisWithNoData_Throws()
{
Assert.Throws<ParserErrorException>(
// expected 2 or more collation elements in collation group
() => VerifyParserError("scr0003", "()", 1, 2)
);
}
[Test]
public void ConvertToIcuRules_ParenthesisWithBlank_Throws()
{
Assert.Throws<ParserErrorException>(
// expected 2 or more collation elements in collation group
() => VerifyParserError("scr0003", "( )", 1, 3)
);
}
[Test]
public void ConvertToIcuRules_ParenthesisWithSingleItem_Throws()
{
Assert.Throws<ParserErrorException>(
// expected 2 or more collation elements in collation group
() => VerifyParserError("scr0003", "(a)", 1, 3)
);
}
[Test]
public void ConvertToIcuRules_ParenthesisWithSingleDigraph_Throws()
{
Assert.Throws<ParserErrorException>(
// expected 2 or more collation elements in collation group
() => VerifyParserError("scr0003", "(ab)", 1, 4)
);
}
[Test]
public void ConvertToIcuRules_ParenthesisWithSingleUnicodeCharacterReference_Throws()
{
Assert.Throws<ParserErrorException>(
// expected 2 or more collation elements in collation group
() => VerifyParserError("scr0003", "(\\u0061)", 1, 8)
);
}
[Test]
public void ConvertToIcuRules_ParenthesisWithCharacterAndUnicodeCharacterReference_Throws()
{
Assert.Throws<ParserErrorException>(
// expected 2 or more collation elements in collation group
() => VerifyParserError("scr0003", "(b\\u0061)", 1, 9)
);
}
[Test]
public void ConvertToIcuRules_ParenthesisWithDigraphUnicodeCharacterReference_Throws()
{
Assert.Throws<ParserErrorException>(
// expected 2 or more collation elements in collation group
() => VerifyParserError("scr0003", "(\\uA123\\uABCD)", 1, 14)
);
}
[Test]
public void ConvertToIcuRules_ParenthesisWithUnicodeCharacterReferenceAndCharacter_Throws()
{
Assert.Throws<ParserErrorException>(
// expected 2 or more collation elements in collation group
() => VerifyParserError("scr0003", "(\\uA123p)", 1, 9)
);
}
[Test]
public void ConvertToIcuRules_NestedParenthesis_Throws()
{
Assert.Throws<ParserErrorException>(
// expected 2 or more collation elements in collation group
() => VerifyParserError("scr0003", "((a A) b)", 1,2)
);
}
[Test]
public void ConvertToIcuRules_SingleCollatingElementInParenthesis_Throws()
{
Assert.Throws<ParserErrorException>(
// expected 2 or more collation elements in collation group
() => VerifyParserError("scr0003", "b (B)\n(\\u0101) a A", 1, 5)
);
}
[Test]
public void ConvertToIcuRules_OpenParenthesisWithoutCloseOnSameLineOneGroup_Throws()
{
Assert.Throws<ParserErrorException>(
//Expected: group close ')'
() => VerifyParserError("scr0005", "(a A \\u0301\n)", 1, 12)
);
}
[Test]
public void ConvertToIcuRules_OpenParenthesisWithoutCloseOnSameLine_Throws()
{
Assert.Throws<ParserErrorException>(
//Expected: group close ')'
() => VerifyParserError("scr0005", "a(A \\u0301\n)", 1, 11)
);
}
[Test]
public void ConvertToIcuRules_OpenParenthesisWithoutClose_Throws()
{
Assert.Throws<ParserErrorException>(
// expected 2 or more collation elements in collation group
() => VerifyParserError("scr0003", "(", 1, 2)
);
}
[Test]
public void ConvertToIcuRules_OpenParenthesisWithoutCloseWithBlanks_Throws()
{
Assert.Throws<ParserErrorException>(
// expected 2 or more collation elements in collation group
() => VerifyParserError("scr0003", "( \n ", 1, 3)
);
}
[Test]
public void ConvertToIcuRules_UnmatchedCloseParenthesis_Throws()
{
Assert.Throws<ParserErrorException>(
// Invalid Character
() => VerifyParserError("scr0006", ")", 1, 1)
);
}
[Test]
public void ConvertToIcuRules_UnmatchedCloseParenthesisWithBlanks_Throws()
{
Assert.Throws<ParserErrorException>(
// Invalid Character
() => VerifyParserError("scr0006", " ) \n ", 1, 2)
);
}
[Test]
public void ConvertToIcuRules_BackslashWithNoCharacterFollowing_Throws()
{
Assert.Throws<ParserErrorException>(
// Invalid unicode character escape sequence
() => VerifyParserError("scr0001", "\\", 1, 2)
);
}
[Test]
public void ConvertToIcuRules_UnicodeCharacterReferenceWithSpaceAfterBackSlash_Throws()
{
Assert.Throws<ParserErrorException>(
// Invalid unicode character escape sequence
() => VerifyParserError("scr0001", "\\ u0301", 1, 2)
);
}
[Test]
public void ConvertToIcuRules_UnicodeCharacterReferenceWithUpperCaseU_Throws()
{
Assert.Throws<ParserErrorException>(
// Invalid unicode character escape sequence
() => VerifyParserError("scr0001", "\\U1234", 1, 2)
);
}
[Test]
public void ConvertToIcuRules_UnicodeCharacterReferenceWithSpaceAfterU_Throws()
{
Assert.Throws<ParserErrorException>(
// Invalid unicode character escape sequence: missing hexadecimal digit after '\u'
() => VerifyParserError("scr0002", "\\u 0301", 1, 3)
);
}
[Test]
public void ConvertToIcuRules_UnicodeCharacterReferenceWithOnlyOneHexDigit_Throws()
{
Assert.Throws<ParserErrorException>(
// Invalid unicode character escape sequence: missing hexadecimal digit after '\u'
() => VerifyParserError("scr0002", "\\u1", 1,4)
);
}
[Test]
public void ConvertToIcuRules_UnicodeCharacterReferenceWithOnlyTwoHexDigits_Throws()
{
Assert.Throws<ParserErrorException>(
// Invalid unicode character escape sequence: missing hexadecimal digit after '\u'
() => VerifyParserError("scr0002", "\\u12",1,5)
);
}
[Test]
public void ConvertToIcuRules_UnicodeCharacterReferenceWithOnlyThreeHexDigits_Throws()
{
Assert.Throws<ParserErrorException>(
// Invalid unicode character escape sequence: missing hexadecimal digit after '\u'
() => VerifyParserError("scr0002", "\\u123",1,6)
);
}
[Test]
public void ConvertToIcuRules_UnicodeCharacterReferenceWithFiveHexDigits_LastDigitTreatedAsCharacter()
{
VerifyExpectedIcuFromActualSimple(IcuStart + "\u12345", "\\u12345");
}
[Test]
public void ConvertToIcuRules_UnicodeCharacterReference_VerifyUnsigned()
{
VerifyExpectedIcuFromActualSimple(IcuStart + "\uA123", "\\uA123");
}
[Test]
public void ConvertToIcuRules_UnicodeCharacterReference_Surrogates()
{
VerifyExpectedIcuFromActualSimple(IcuStart + "a << \\ud800\\udc00", "a \\ud800\\udc00");
}
[Test]
public void ConvertToIcuRules_SurrogateCharacters()
{
VerifyExpectedIcuFromActualSimple(IcuStart + "a << \ud800\udc00", "a \ud800\udc00");
}
[Test]
public void ConvertToIcuRules_CollationElementUsedTwice_Throws()
{
Assert.Throws<ParserErrorException>(
// duplicate collation element
() => VerifyParserError("scr0100", "a \\u0061", 1, 9)
);
}
[Test]
public void ConvertToIcuRules_AsciiCharacterNotLetterOrDigit_RequiresIcuEscaping()
{
VerifyExpectedIcuFromActualSimple(
IcuStart + "\\\\ << \\< << \\<\\< << \\<\\<\\< << \\= << \\&",
"\\u005c < << <<< = &");
}
[Test]
public void ParseError_CorrectLineAndOffset()
{
Assert.Throws<ParserErrorException>(
() => VerifyParserError("scr0006", "ph\na A)\nb B\nc C",2,4)
);
}
}
}
| |
//
// Copyright 2012-2016, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
# if ! __UNIFIED__
using MonoTouch.UIKit;
using MonoTouch.Foundation;
#else
using UIKit;
using Foundation;
#endif
#if ! AZURE_MOBILE_SERVICES
using Xamarin.Controls;
using Xamarin.Utilities.iOS;
#else
using Xamarin.Controls._MobileServices;
using Xamarin.Utilities._MobileServices.iOS;
#endif
#if ! AZURE_MOBILE_SERVICES
namespace Xamarin.Auth
#else
namespace Xamarin.Auth._MobileServices
#endif
{
internal class FormAuthenticatorController : UITableViewController
{
FormAuthenticator authenticator;
ProgressLabel progress;
CancellationTokenSource cancelSource;
public FormAuthenticatorController(FormAuthenticator authenticator)
: base(UITableViewStyle.Grouped)
{
this.authenticator = authenticator;
Title = authenticator.Title;
TableView.DataSource = new FormDataSource(this);
TableView.Delegate = new FormDelegate(this);
if (authenticator.AllowCancel)
{
NavigationItem.LeftBarButtonItem = new UIBarButtonItem
(
UIBarButtonSystemItem.Cancel,
delegate
{
StopProgress();
authenticator.OnCancelled();
}
);
}
}
void HandleSubmit()
{
if (progress == null)
{
progress = new ProgressLabel
(
NSBundle.MainBundle.LocalizedString
(
"Verifying",
"Verifying status message when adding accounts"
)
);
NavigationItem.TitleView = progress;
progress.StartAnimating();
}
cancelSource = new CancellationTokenSource();
authenticator.SignInAsync(cancelSource.Token).ContinueWith(task =>
{
StopProgress();
if (task.IsFaulted)
{
if (!authenticator.ShowErrors)
return;
this.ShowError("Error Signing In", task.Exception);
}
else
{
authenticator.OnSucceeded(task.Result);
}
}, TaskScheduler.FromCurrentSynchronizationContext());
return;
}
void StopProgress()
{
if (progress != null)
{
progress.StopAnimating();
NavigationItem.TitleView = null;
progress = null;
}
return;
}
#region
///-------------------------------------------------------------------------------------------------
/// Pull Request - manually added/fixed
/// Added IsAuthenticated check #88
/// https://github.com/xamarin/Xamarin.Auth/pull/88
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
if (authenticator.AllowCancel && authenticator.IsAuthenticated())
{
authenticator.OnCancelled();
}
return;
}
///-------------------------------------------------------------------------------------------------
#endregion
class FormDelegate : UITableViewDelegate
{
FormAuthenticatorController controller;
public FormDelegate(FormAuthenticatorController controller)
{
this.controller = controller;
}
public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
tableView.ResignFirstResponder();
if (indexPath.Section == 1)
{
tableView.DeselectRow(indexPath, true);
((FormDataSource)tableView.DataSource).ResignFirstResponder();
controller.HandleSubmit();
}
else if (indexPath.Section == 2)
{
tableView.DeselectRow(indexPath, true);
UIApplication.SharedApplication.OpenUrl(
new NSUrl(controller.authenticator.CreateAccountLink.AbsoluteUri));
}
}
}
class FieldCell : UITableViewCell
{
public static readonly UIFont LabelFont = UIFont.BoldSystemFontOfSize(16);
public static readonly UIFont FieldFont = UIFont.SystemFontOfSize(16);
static readonly UIColor FieldColor = UIColor.FromRGB(56, 84, 135);
public UITextField TextField { get; private set; }
#if !__UNIFIED__
public FieldCell (FormAuthenticatorField field, float fieldXPosition, Action handleReturn)
#else
public FieldCell(FormAuthenticatorField field, nfloat fieldXPosition, Action handleReturn)
#endif
: base(UITableViewCellStyle.Default, "Field")
{
SelectionStyle = UITableViewCellSelectionStyle.None;
TextLabel.Text = field.Title;
var hang = 3;
var h = FieldFont.PointSize + hang;
var cellSize = Frame.Size;
#if !__UNIFIED__
TextField = new UITextField
(
new RectangleF
(
fieldXPosition, (cellSize.Height - h)/2,
cellSize.Width - fieldXPosition - 12, h)
)
#else
TextField = new UITextField
(
new CoreGraphics.CGRect
(
fieldXPosition, (cellSize.Height - h) / 2,
cellSize.Width - fieldXPosition - 12, h
)
)
#endif
{
Font = FieldFont,
Placeholder = field.Placeholder,
Text = field.Value,
TextColor = FieldColor,
AutoresizingMask = UIViewAutoresizing.FlexibleWidth,
SecureTextEntry = (field.FieldType == FormAuthenticatorFieldType.Password),
KeyboardType = (field.FieldType == FormAuthenticatorFieldType.Email) ?
UIKeyboardType.EmailAddress :
UIKeyboardType.Default,
AutocorrectionType = (field.FieldType == FormAuthenticatorFieldType.PlainText) ?
UITextAutocorrectionType.Yes :
UITextAutocorrectionType.No,
AutocapitalizationType = UITextAutocapitalizationType.None,
ShouldReturn = delegate
{
handleReturn();
return false;
},
};
TextField.EditingDidEnd += delegate
{
field.Value = TextField.Text;
};
ContentView.AddSubview(TextField);
}
}
class FormDataSource : UITableViewDataSource
{
FormAuthenticatorController controller;
public FormDataSource(FormAuthenticatorController controller)
{
this.controller = controller;
}
#if !__UNIFIED__
public override int NumberOfSections (UITableView tableView)
#else
public override nint NumberOfSections(UITableView tableView)
#endif
{
return 2 + (controller.authenticator.CreateAccountLink != null ? 1 : 0);
}
#if !__UNIFIED__
public override int RowsInSection (UITableView tableView, int section)
#else
public override nint RowsInSection(UITableView tableView, nint section)
#endif
{
if (section == 0)
{
return controller.authenticator.Fields.Count;
}
else
{
return 1;
}
}
FieldCell[] fieldCells = null;
public void SelectNext()
{
for (var i = 0; i < controller.authenticator.Fields.Count; i++)
{
if (fieldCells[i].TextField.IsFirstResponder)
{
if (i + 1 < fieldCells.Length)
{
fieldCells[i + 1].TextField.BecomeFirstResponder();
return;
}
else
{
fieldCells[i].TextField.ResignFirstResponder();
controller.HandleSubmit();
return;
}
}
}
}
public void ResignFirstResponder()
{
foreach (var cell in fieldCells)
{
cell.TextField.ResignFirstResponder();
}
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
if (indexPath.Section == 0)
{
if (fieldCells == null)
{
var fieldXPosition = controller
.authenticator
.Fields
#if !__UNIFIED__
.Select (f => tableView.StringSize (f.Title, FieldCell.LabelFont).Width)
#else
.Select(f => UIKit.UIStringDrawing.StringSize(f.Title, FieldCell.LabelFont).Width)
#endif
.Max();
fieldXPosition += 36;
fieldCells = controller
.authenticator
.Fields
#if !__UNIFIED__
.Select (f => new FieldCell (f, fieldXPosition, SelectNext))
#else
.Select(f => new FieldCell(f, fieldXPosition, SelectNext))
#endif
.ToArray();
}
return fieldCells[indexPath.Row];
}
else if (indexPath.Section == 1)
{
var cell = tableView.DequeueReusableCell("SignIn");
if (cell == null)
{
cell = new UITableViewCell(UITableViewCellStyle.Default, "SignIn");
cell.TextLabel.TextAlignment = UITextAlignment.Center;
}
cell.TextLabel.Text = NSBundle.MainBundle.LocalizedString("Sign In", "Sign In button title");
return cell;
}
else
{
var cell = tableView.DequeueReusableCell("CreateAccount");
if (cell == null)
{
cell = new UITableViewCell(UITableViewCellStyle.Default, "CreateAccount");
cell.TextLabel.TextAlignment = UITextAlignment.Center;
}
cell.TextLabel.Text = NSBundle.MainBundle.LocalizedString("Create Account", "Create Account button title");
return cell;
}
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace applicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// SecurityRulesOperations operations.
/// </summary>
public partial interface ISecurityRulesOperations
{
/// <summary>
/// Deletes the specified network security rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the specified network security rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </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<SecurityRule>> GetWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a security rule in the specified network
/// security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create or update network security rule
/// 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<SecurityRule>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all security rules in a network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </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<SecurityRule>>> ListWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified network security rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a security rule in the specified network
/// security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='securityRuleName'>
/// The name of the security rule.
/// </param>
/// <param name='securityRuleParameters'>
/// Parameters supplied to the create or update network security rule
/// 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<SecurityRule>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string securityRuleName, SecurityRule securityRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all security rules in a network security group.
/// </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<SecurityRule>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using ProBuilder2.Common;
namespace ProBuilder2.EditorCommon
{
/**
* INSTRUCTIONS
*
* - Only modify properties in the USER SETTINGS region.
* - All content is loaded from external files (pc_AboutEntry_YourProduct. Use the templates!
*/
/**
* Used to pop up the window on import.
*/
[InitializeOnLoad]
static class pb_AboutWindowSetup
{
static pb_AboutWindowSetup()
{
EditorApplication.delayCall += () => { pb_AboutWindow.Init(false); };
}
}
/**
* Changelog.txt file should follow this format:
*
* | # Product Name 2.1.0
* |
* | ## Features
* |
* | - All kinds of awesome stuff
* | - New flux capacitor design achieves time travel at lower velocities.
* | - Dark matter reactor recalibrated.
* |
* | ## Bug Fixes
* |
* | - No longer explodes when spacebar is pressed.
* | - Fix rolling issue in rickmeter.
* |
* | # Changes
* |
* | - Changed Blue to Red.
* | - Enter key now causes explosions.
*
* This path is relative to the PRODUCT_ROOT path.
*
* Note that your changelog may contain multiple entries. Only the top-most
* entry will be displayed.
*/
public class pb_AboutWindow : EditorWindow
{
// Modify these constants to customize about screen.
const string PACKAGE_NAME = "ProBuilder";
private static string aboutRoot = "Assets/ProCore/" + PACKAGE_NAME + "/About";
// Path to the root folder
internal static string AboutRoot
{
get
{
if( Directory.Exists(aboutRoot) )
{
return aboutRoot;
}
else
{
aboutRoot = pb_FileUtil.FindFolder("ProBuilder/About");
if(aboutRoot.EndsWith("/"))
aboutRoot = aboutRoot.Remove(aboutRoot.LastIndexOf("/"), 1);
return aboutRoot;
}
}
}
GUIContent gc_Learn = new GUIContent("Learn ProBuilder", "Documentation");
GUIContent gc_Forum = new GUIContent("Support Forum", "ProCore Support Forum");
GUIContent gc_Contact = new GUIContent("Contact Us", "Send us an email!");
GUIContent gc_Banner = new GUIContent("", "ProBuilder Quick-Start Video Tutorials");
private const string VIDEO_URL = @"http://bit.ly/pbstarter";
private const string LEARN_URL = @"http://procore3d.com/docs/probuilder";
private const string SUPPORT_URL = @"http://www.procore3d.com/forum/";
private const string CONTACT_EMAIL = @"http://www.procore3d.com/about/";
private const float BANNER_WIDTH = 480f;
private const float BANNER_HEIGHT = 270f;
internal const string FONT_REGULAR = "Asap-Regular.otf";
internal const string FONT_MEDIUM = "Asap-Medium.otf";
// Use less contast-y white and black font colors for better readabililty
public static readonly Color font_white = HexToColor(0xCECECE);
public static readonly Color font_black = HexToColor(0x545454);
public static readonly Color font_blue_normal = HexToColor(0x00AAEF);
public static readonly Color font_blue_hover = HexToColor(0x008BEF);
private string productName = pb_Constant.PRODUCT_NAME;
private pb_AboutEntry about = null;
private string changelogRichText = "";
internal static GUIStyle bannerStyle,
header1Style,
versionInfoStyle,
linkStyle,
separatorStyle,
changelogStyle,
changelogTextStyle;
Vector2 scroll = Vector2.zero;
/**
* Return true if Init took place, false if not.
*/
public static bool Init (bool fromMenu)
{
pb_AboutEntry about;
if(!pb_VersionUtil.GetAboutEntry(out about))
{
Debug.LogWarning("Couldn't find pb_AboutEntry_ProBuilder.txt");
return false;
}
if(fromMenu || pb_Preferences_Internal.GetString(about.identifier) != about.version)
{
pb_AboutWindow win;
win = (pb_AboutWindow)EditorWindow.GetWindow(typeof(pb_AboutWindow), true, about.name, true);
win.ShowUtility();
win.SetAbout(about);
pb_Preferences_Internal.SetString(about.identifier, about.version, pb_PreferenceLocation.Global);
return true;
}
else
{
return false;
}
}
private static Color HexToColor(uint x)
{
return new Color( ((x >> 16) & 0xFF) / 255f,
((x >> 8) & 0xFF) / 255f,
(x & 0xFF) / 255f,
1f);
}
public static void InitGuiStyles()
{
bannerStyle = new GUIStyle()
{
// RectOffset(left, right, top, bottom)
margin = new RectOffset(12, 12, 12, 12),
normal = new GUIStyleState() {
background = LoadAssetAtPath<Texture2D>(string.Format("{0}/Images/Banner_Normal.png", AboutRoot))
},
hover = new GUIStyleState() {
background = LoadAssetAtPath<Texture2D>(string.Format("{0}/Images/Banner_Hover.png", AboutRoot))
},
};
header1Style = new GUIStyle()
{
margin = new RectOffset(10, 10, 10, 10),
alignment = TextAnchor.MiddleCenter,
fontSize = 24,
// fontStyle = FontStyle.Bold,
font = LoadAssetAtPath<Font>(string.Format("{0}/Font/{1}", AboutRoot, FONT_MEDIUM)),
normal = new GUIStyleState() { textColor = EditorGUIUtility.isProSkin ? font_white : font_black }
};
versionInfoStyle = new GUIStyle()
{
margin = new RectOffset(10, 10, 10, 10),
fontSize = 14,
font = LoadAssetAtPath<Font>(string.Format("{0}/Font/{1}", AboutRoot, FONT_REGULAR)),
normal = new GUIStyleState() { textColor = EditorGUIUtility.isProSkin ? font_white : font_black }
};
linkStyle = new GUIStyle()
{
margin = new RectOffset(10, 10, 10, 10),
alignment = TextAnchor.MiddleCenter,
fontSize = 16,
font = LoadAssetAtPath<Font>(string.Format("{0}/Font/{1}", AboutRoot, FONT_REGULAR)),
normal = new GUIStyleState() {
textColor = font_blue_normal,
background = LoadAssetAtPath<Texture2D>(
string.Format("{0}/Images/ScrollBackground_{1}.png",
AboutRoot,
EditorGUIUtility.isProSkin ? "Pro" : "Light"))
},
hover = new GUIStyleState() {
textColor = font_blue_hover,
background = LoadAssetAtPath<Texture2D>(
string.Format("{0}/Images/ScrollBackground_{1}.png",
AboutRoot,
EditorGUIUtility.isProSkin ? "Pro" : "Light"))
}
};
separatorStyle = new GUIStyle()
{
margin = new RectOffset(10, 10, 10, 10),
alignment = TextAnchor.MiddleCenter,
fontSize = 16,
font = LoadAssetAtPath<Font>(string.Format("{0}/Font/{1}", AboutRoot, FONT_REGULAR)),
normal = new GUIStyleState() { textColor = EditorGUIUtility.isProSkin ? font_white : font_black }
};
changelogStyle = new GUIStyle()
{
margin = new RectOffset(10, 10, 10, 10),
font = LoadAssetAtPath<Font>(string.Format("{0}/Font/{1}", AboutRoot, FONT_REGULAR)),
richText = true,
normal = new GUIStyleState() { background = LoadAssetAtPath<Texture2D>(
string.Format("{0}/Images/ScrollBackground_{1}.png",
AboutRoot,
EditorGUIUtility.isProSkin ? "Pro" : "Light"))
}
};
changelogTextStyle = new GUIStyle()
{
margin = new RectOffset(10, 10, 10, 10),
font = LoadAssetAtPath<Font>(string.Format("{0}/Font/{1}", AboutRoot, FONT_REGULAR)),
fontSize = 14,
normal = new GUIStyleState() { textColor = EditorGUIUtility.isProSkin ? font_white : font_black },
richText = true,
wordWrap = true
};
}
public void OnEnable()
{
InitGuiStyles();
Texture2D banner = bannerStyle.normal.background;
if(banner == null)
{
Debug.LogWarning("Could not load About window resources");
this.Close();
}
else
{
bannerStyle.fixedWidth = BANNER_WIDTH; // banner.width;
bannerStyle.fixedHeight = BANNER_HEIGHT; // banner.height;
this.wantsMouseMove = true;
this.minSize = new Vector2(BANNER_WIDTH + 24, BANNER_HEIGHT * 2.5f);
this.maxSize = new Vector2(BANNER_WIDTH + 24, BANNER_HEIGHT * 2.5f);
if(!productName.Contains("Basic"))
productName = "ProBuilder Advanced";
}
}
void SetAbout(pb_AboutEntry about)
{
this.about = about;
if(!File.Exists(about.changelogPath))
about.changelogPath = pb_FileUtil.FindFile("ProBuilder/About/changelog.txt");
if(File.Exists(about.changelogPath))
{
string raw = File.ReadAllText(about.changelogPath);
if(!string.IsNullOrEmpty(raw))
{
pb_VersionInfo vi;
pb_VersionUtil.FormatChangelog(raw, out vi, out changelogRichText);
}
}
}
internal static T LoadAssetAtPath<T>(string InPath) where T : UnityEngine.Object
{
return (T) AssetDatabase.LoadAssetAtPath(InPath, typeof(T));
}
void OnGUI()
{
Vector2 mousePosition = Event.current.mousePosition;
if( GUILayout.Button(gc_Banner, bannerStyle) )
Application.OpenURL(VIDEO_URL);
if(GUILayoutUtility.GetLastRect().Contains(mousePosition))
Repaint();
GUILayout.BeginVertical(changelogStyle);
GUILayout.Label(productName, header1Style);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if(GUILayout.Button(gc_Learn, linkStyle))
Application.OpenURL(LEARN_URL);
GUILayout.Label("|", separatorStyle);
if(GUILayout.Button(gc_Forum, linkStyle))
Application.OpenURL(SUPPORT_URL);
GUILayout.Label("|", separatorStyle);
if(GUILayout.Button(gc_Contact, linkStyle))
Application.OpenURL(CONTACT_EMAIL);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
if(GUILayoutUtility.GetLastRect().Contains(mousePosition))
Repaint();
GUILayout.EndVertical();
// always bold the first line (cause it's the version info stuff)
scroll = EditorGUILayout.BeginScrollView(scroll, changelogStyle);
GUILayout.Label(string.Format("Version: {0}", about.version), versionInfoStyle);
GUILayout.Label("\n" + changelogRichText, changelogTextStyle);
EditorGUILayout.EndScrollView();
}
/**
* Draw a horizontal line across the screen and update the guilayout.
*/
void HorizontalLine()
{
Rect r = GUILayoutUtility.GetLastRect();
Color og = GUI.backgroundColor;
GUI.backgroundColor = Color.black;
GUI.Box(new Rect(0f, r.y + r.height + 2, Screen.width, 2f), "");
GUI.backgroundColor = og;
GUILayout.Space(6);
}
}
}
| |
using System;
using System.Globalization;
using Orleans.Core;
using Orleans.Core.Abstractions.Internal;
namespace Orleans.Runtime
{
[Serializable]
internal class GrainId : UniqueIdentifier, IEquatable<GrainId>, IGrainIdentity
{
private static readonly object lockable = new object();
private const int INTERN_CACHE_INITIAL_SIZE = InternerConstants.SIZE_LARGE;
private static readonly TimeSpan internCacheCleanupInterval = InternerConstants.DefaultCacheCleanupFreq;
private static Interner<UniqueKey, GrainId> grainIdInternCache;
public UniqueKey.Category Category => Key.IdCategory;
public bool IsSystemTarget => Key.IsSystemTargetKey;
public bool IsGrain => Category == UniqueKey.Category.Grain || Category == UniqueKey.Category.KeyExtGrain;
public bool IsClient => Category == UniqueKey.Category.Client || Category == UniqueKey.Category.GeoClient;
internal GrainId(UniqueKey key)
: base(key)
{
}
public static GrainId NewId()
{
return FindOrCreateGrainId(UniqueKey.NewKey(Guid.NewGuid(), UniqueKey.Category.Grain));
}
public static GrainId NewClientId(string clusterId = null)
{
return NewClientId(Guid.NewGuid(), clusterId);
}
internal static GrainId NewClientId(Guid id, string clusterId = null)
{
return FindOrCreateGrainId(UniqueKey.NewKey(id,
clusterId == null ? UniqueKey.Category.Client : UniqueKey.Category.GeoClient, 0, clusterId));
}
internal static GrainId GetGrainId(UniqueKey key)
{
return FindOrCreateGrainId(key);
}
internal static GrainId GetSystemGrainId(Guid guid)
{
return FindOrCreateGrainId(UniqueKey.NewKey(guid, UniqueKey.Category.SystemGrain));
}
// For testing only.
internal static GrainId GetGrainIdForTesting(Guid guid)
{
return FindOrCreateGrainId(UniqueKey.NewKey(guid, UniqueKey.Category.None));
}
internal static GrainId NewSystemTargetGrainIdByTypeCode(int typeData)
{
return FindOrCreateGrainId(UniqueKey.NewSystemTargetKey(Guid.NewGuid(), typeData));
}
internal static GrainId GetSystemTargetGrainId(short systemGrainId)
{
return FindOrCreateGrainId(UniqueKey.NewSystemTargetKey(systemGrainId));
}
internal static GrainId GetGrainId(long typeCode, long primaryKey, string keyExt=null)
{
return FindOrCreateGrainId(UniqueKey.NewKey(primaryKey,
keyExt == null ? UniqueKey.Category.Grain : UniqueKey.Category.KeyExtGrain,
typeCode, keyExt));
}
internal static GrainId GetGrainId(long typeCode, Guid primaryKey, string keyExt=null)
{
return FindOrCreateGrainId(UniqueKey.NewKey(primaryKey,
keyExt == null ? UniqueKey.Category.Grain : UniqueKey.Category.KeyExtGrain,
typeCode, keyExt));
}
internal static GrainId GetGrainId(long typeCode, string primaryKey)
{
return FindOrCreateGrainId(UniqueKey.NewKey(0L,
UniqueKey.Category.KeyExtGrain,
typeCode, primaryKey));
}
internal static GrainId GetGrainServiceGrainId(short id, int typeData)
{
return FindOrCreateGrainId(UniqueKey.NewGrainServiceKey(id, typeData));
}
public Guid PrimaryKey
{
get { return GetPrimaryKey(); }
}
public long PrimaryKeyLong
{
get { return GetPrimaryKeyLong(); }
}
public string PrimaryKeyString
{
get { return GetPrimaryKeyString(); }
}
public string IdentityString
{
get { return ToDetailedString(); }
}
public bool IsLongKey
{
get { return Key.IsLongKey; }
}
public long GetPrimaryKeyLong(out string keyExt)
{
return Key.PrimaryKeyToLong(out keyExt);
}
internal long GetPrimaryKeyLong()
{
return Key.PrimaryKeyToLong();
}
public Guid GetPrimaryKey(out string keyExt)
{
return Key.PrimaryKeyToGuid(out keyExt);
}
internal Guid GetPrimaryKey()
{
return Key.PrimaryKeyToGuid();
}
internal string GetPrimaryKeyString()
{
string key;
var tmp = GetPrimaryKey(out key);
return key;
}
public int TypeCode => Key.BaseTypeCode;
private static GrainId FindOrCreateGrainId(UniqueKey key)
{
// Note: This is done here to avoid a wierd cyclic dependency / static initialization ordering problem involving the GrainId, Constants & Interner classes
if (grainIdInternCache != null) return grainIdInternCache.FindOrCreate(key, k => new GrainId(k));
lock (lockable)
{
if (grainIdInternCache == null)
{
grainIdInternCache = new Interner<UniqueKey, GrainId>(INTERN_CACHE_INITIAL_SIZE, internCacheCleanupInterval);
}
}
return grainIdInternCache.FindOrCreate(key, k => new GrainId(k));
}
#region IEquatable<GrainId> Members
public bool Equals(GrainId other)
{
return other != null && Key.Equals(other.Key);
}
#endregion
public override bool Equals(UniqueIdentifier obj)
{
var o = obj as GrainId;
return o != null && Key.Equals(o.Key);
}
public override bool Equals(object obj)
{
var o = obj as GrainId;
return o != null && Key.Equals(o.Key);
}
// Keep compiler happy -- it does not like classes to have Equals(...) without GetHashCode() methods
public override int GetHashCode()
{
return Key.GetHashCode();
}
/// <summary>
/// Get a uniformly distributed hash code value for this grain, based on Jenkins Hash function.
/// NOTE: Hash code value may be positive or NEGATIVE.
/// </summary>
/// <returns>Hash code for this GrainId</returns>
public uint GetUniformHashCode()
{
return Key.GetUniformHashCode();
}
public override string ToString()
{
return ToStringImpl(false);
}
// same as ToString, just full primary key and type code
internal string ToDetailedString()
{
return ToStringImpl(true);
}
// same as ToString, just full primary key and type code
private string ToStringImpl(bool detailed)
{
// TODO Get name of system/target grain + name of the grain type
var keyString = Key.ToString();
// this should grab the least-significant half of n1, suffixing it with the key extension.
string idString = keyString;
if (!detailed)
{
if (keyString.Length >= 48)
idString = keyString.Substring(24, 8) + keyString.Substring(48);
else
idString = keyString.Substring(24, 8);
}
string fullString = null;
switch (Category)
{
case UniqueKey.Category.Grain:
case UniqueKey.Category.KeyExtGrain:
var typeString = TypeCode.ToString("X");
if (!detailed) typeString = typeString.Substring(Math.Max(0, typeString.Length - 8));
fullString = $"*grn/{typeString}/{idString}";
break;
case UniqueKey.Category.Client:
fullString = $"*cli/{idString}";
break;
case UniqueKey.Category.GeoClient:
fullString = $"*gcl/{Key.KeyExt}/{idString}";
break;
case UniqueKey.Category.SystemGrain:
fullString = $"*sgn/{Key.PrimaryKeyToGuid()}/{idString}";
break;
case UniqueKey.Category.SystemTarget:
fullString = $"*stg/{Key.N1}/{idString}";
break;
default:
fullString = "???/" + idString;
break;
}
return detailed ? String.Format("{0}-0x{1, 8:X8}", fullString, GetUniformHashCode()) : fullString;
}
internal string ToFullString()
{
string kx;
string pks =
Key.IsLongKey ?
GetPrimaryKeyLong(out kx).ToString(CultureInfo.InvariantCulture) :
GetPrimaryKey(out kx).ToString();
string pksHex =
Key.IsLongKey ?
GetPrimaryKeyLong(out kx).ToString("X") :
GetPrimaryKey(out kx).ToString("X");
return
String.Format(
"[GrainId: {0}, IdCategory: {1}, BaseTypeCode: {2} (x{3}), PrimaryKey: {4} (x{5}), UniformHashCode: {6} (0x{7, 8:X8}){8}]",
ToDetailedString(), // 0
Category, // 1
TypeCode, // 2
TypeCode.ToString("X"), // 3
pks, // 4
pksHex, // 5
GetUniformHashCode(), // 6
GetUniformHashCode(), // 7
Key.HasKeyExt ? String.Format(", KeyExtension: {0}", kx) : ""); // 8
}
internal string ToStringWithHashCode()
{
return String.Format("{0}-0x{1, 8:X8}", this.ToString(), this.GetUniformHashCode());
}
/// <summary>
/// Return this GrainId in a standard string form, suitable for later use with the <c>FromParsableString</c> method.
/// </summary>
/// <returns>GrainId in a standard string format.</returns>
internal string ToParsableString()
{
// NOTE: This function must be the "inverse" of FromParsableString, and data must round-trip reliably.
return Key.ToHexString();
}
/// <summary>
/// Create a new GrainId object by parsing string in a standard form returned from <c>ToParsableString</c> method.
/// </summary>
/// <param name="grainId">String containing the GrainId info to be parsed.</param>
/// <returns>New GrainId object created from the input data.</returns>
internal static GrainId FromParsableString(string grainId)
{
// NOTE: This function must be the "inverse" of ToParsableString, and data must round-trip reliably.
var key = UniqueKey.Parse(grainId);
return FindOrCreateGrainId(key);
}
}
}
| |
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 FunMatchGame.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;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
namespace Equality {
internal static class EqualsInternals {
internal delegate Boolean StructEquals<T>(ref T x, ref T y) where T : struct;
internal delegate Boolean StructEqualsObject<T>(ref T x, Object y) where T : struct;
internal delegate Boolean ClassEquals<in T>(T x, T y) where T : class;
internal delegate Boolean ClassEqualsObject<in T>(T x, Object y) where T : class;
internal static class StaticStructCache<T> where T : struct {
public static readonly StructEquals<T> Func = GetStructEqualsFunc<T>();
}
internal static class StaticClassCache<T> where T : class {
public static readonly ClassEquals<T> Func = GetClassEqualsFunc<T>(typeof(T));
}
internal static ClassEquals<Object> GetDynamicClassEquals(Type type) => DynamicCache.GetOrAdd(type, GetClassEqualsFunc<Object>);
private static StructEquals<T> GetStructEqualsFunc<T>() where T : struct => Common.GenerateIL<StructEquals<T>>(GenerateIL<T>, typeof(T));
private static ClassEquals<T> GetClassEqualsFunc<T>(Type type) where T : class => Common.GenerateIL<ClassEquals<T>>(GenerateIL<T>, type);
private static readonly ConcurrentDictionary<Type, ClassEquals<Object>> DynamicCache = new ConcurrentDictionary<Type, ClassEquals<Object>>();
private static Boolean EnumerableEquals<T>(IEnumerable<T> first, IEnumerable<T> second) {
try {
var dictionary = first as IDictionary;
if (dictionary != null)
return DictionaryComparer.Equals(dictionary, (IDictionary) second);
var list = first as IList<T>;
if (list != null)
return ArrayEquals(list, (IList<T>) second);
if (first is IStructuralEquatable)
return StructuralComparisons.StructuralEqualityComparer.Equals(first, second);
return first.SequenceEqual(second);
}
catch (InvalidOperationException) { // Catch any collection changes while enumerating
return false;
}
}
private static Boolean ArrayEquals<T>(IList<T> first, IList<T> second) {
if (first.Count != second.Count)
return false;
var comparer = EqualityComparer<T>.Default;
for (var i = 0; i < first.Count; i++)
if (!comparer.Equals(first[i], second[i]))
return false;
return true;
}
private static void GenerateIL<T>(Type type, ILGenerator ilGenerator) {
Action<ILGenerator> loadFirstInstance = i => i.Emit(OpCodes.Ldarg_0);
if (typeof(T) != type) {
var instanceLocal = ilGenerator.DeclareLocal(type);
loadFirstInstance = i => i.Emit(OpCodes.Ldloc, instanceLocal);
ilGenerator.Emit(OpCodes.Ldarg_0);
ilGenerator.Emit(OpCodes.Castclass, type);
ilGenerator.Emit(OpCodes.Stloc, instanceLocal);
}
Action<ILGenerator> loadSecondInstance = i => i.Emit(OpCodes.Ldarg_1);
if (typeof(T) != type) {
var instanceLocal = ilGenerator.DeclareLocal(type);
loadSecondInstance = i => i.Emit(OpCodes.Ldloc, instanceLocal);
ilGenerator.Emit(OpCodes.Ldarg_1);
ilGenerator.Emit(OpCodes.Castclass, type);
ilGenerator.Emit(OpCodes.Stloc, instanceLocal);
}
var firstMemberLocalMap = new ConcurrentDictionary<Type, LocalBuilder>();
var secondMemberLocalMap = new ConcurrentDictionary<Type, LocalBuilder>();
var fields = Common.GetFields(type);
foreach (var field in fields) {
var nextField = ilGenerator.DefineLabel();
EmitMemberEqualityComparison(ilGenerator, firstMemberLocalMap, secondMemberLocalMap, loadFirstInstance, loadSecondInstance, field, field.FieldType, nextField);
ilGenerator.MarkLabel(nextField);
}
var properties = Common.GetProperties(type);
foreach (var property in properties) {
var nextProperty = ilGenerator.DefineLabel();
EmitMemberEqualityComparison(ilGenerator, firstMemberLocalMap, secondMemberLocalMap, loadFirstInstance, loadSecondInstance, property, property.PropertyType, nextProperty);
ilGenerator.MarkLabel(nextProperty);
}
ilGenerator.Emit(OpCodes.Ldc_I4_1);
ilGenerator.Emit(OpCodes.Ret);
}
private static void EmitMemberEqualityComparison(ILGenerator ilGenerator,
ConcurrentDictionary<Type, LocalBuilder> firstMemberLocalMap,
ConcurrentDictionary<Type, LocalBuilder> secondMemberLocalMap,
Action<ILGenerator> loadFirstInstance,
Action<ILGenerator> loadSecondInstance,
MemberInfo memberInfo,
Type memberType,
Label nextMember) {
Action<ILGenerator> emitLoadFirstMember;
Action<ILGenerator> emitLoadSecondMember;
if (memberInfo is FieldInfo)
emitLoadFirstMember = emitLoadSecondMember = ilg => ilg.Emit(OpCodes.Ldfld, (FieldInfo) memberInfo);
else if (memberInfo is PropertyInfo)
emitLoadFirstMember = emitLoadSecondMember = ilg => ilg.Emit(OpCodes.Call, ((PropertyInfo) memberInfo).GetGetMethod(nonPublic: true));
else
throw new ArgumentOutOfRangeException(nameof(memberInfo), "Must be FieldInfo or PropertyInfo");
Action<ILGenerator> emitComparison = delegate { };
if (memberType.IsPrimitive || memberType.IsEnum)
emitComparison = ilg => ilg.Emit(OpCodes.Beq, nextMember);
else {
MethodInfo opEquality;
Type t;
if (typeof(IEquatable<>).MakeGenericType(memberType).IsAssignableFrom(memberType)) {
if (memberType.IsValueType) {
emitLoadFirstMember = GetEmitLoadMembersForValueType(firstMemberLocalMap, memberInfo, memberType, emitLoadFirstMember);
}
else {
emitComparison = GetEmitLoadAndCompareForReferenceType(firstMemberLocalMap, secondMemberLocalMap, memberType, nextMember, ref emitLoadFirstMember, ref emitLoadSecondMember);
}
if (memberInfo.ShouldRecurse(memberType)) {
if (memberType.IsValueType) {
emitLoadSecondMember = GetEmitLoadMembersForValueType(secondMemberLocalMap, memberInfo, memberType, emitLoadSecondMember);
emitComparison = emitComparison.CombineDelegates(ilg => ilg.Emit(OpCodes.Call, Struct.EqualsMethodInfo.MakeGenericMethod(memberType)));
}
else
emitComparison = emitComparison.CombineDelegates(ilg => ilg.Emit(OpCodes.Call, Class.EqualsMethodInfo.MakeGenericMethod(memberType)));
}
else
emitComparison = emitComparison.CombineDelegates(ilg => ilg.Emit(OpCodes.Call, memberType.GetMethod(nameof(Equals), new[] { memberType })));
}
else if ((opEquality = memberType.GetMethod("op_Equality", new[] { memberType, memberType })) != null) {
emitComparison = ilg => ilg.Emit(OpCodes.Call, opEquality);
}
else {
if (memberType.IsValueType) {
emitLoadFirstMember = GetEmitLoadMembersForValueType(firstMemberLocalMap, memberInfo, memberType, emitLoadFirstMember);
loadSecondInstance = loadSecondInstance.CombineDelegates(ilg => ilg.Emit(OpCodes.Box, memberType));
}
else {
emitComparison = GetEmitLoadAndCompareForReferenceType(firstMemberLocalMap, secondMemberLocalMap, memberType, nextMember, ref emitLoadFirstMember, ref emitLoadSecondMember);
}
if (memberInfo.ShouldGetStructural(memberType, out t))
emitComparison = emitComparison.CombineDelegates(ilg => ilg.Emit(OpCodes.Call, typeof(EqualsInternals).GetMethod(nameof(EnumerableEquals), BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(t)));
else if (memberInfo.ShouldRecurse(memberType)) {
if (memberType.IsValueType) {
emitLoadSecondMember = GetEmitLoadMembersForValueType(secondMemberLocalMap, memberInfo, memberType, emitLoadSecondMember);
emitComparison = emitComparison.CombineDelegates(ilg => ilg.Emit(OpCodes.Call, Struct.EqualsMethodInfo.MakeGenericMethod(memberType)));
}
else
emitComparison = emitComparison.CombineDelegates(ilg => ilg.Emit(OpCodes.Call, Class.EqualsMethodInfo.MakeGenericMethod(memberType)));
}
else
emitComparison = emitComparison.CombineDelegates(ilg => ilg.Emit(OpCodes.Callvirt, memberType.GetMethod(nameof(Equals), new[] {typeof(Object)})));
}
emitComparison = emitComparison.CombineDelegates(ilg => ilg.Emit(OpCodes.Brtrue, nextMember));
}
loadFirstInstance(ilGenerator);
emitLoadFirstMember(ilGenerator);
loadSecondInstance(ilGenerator);
emitLoadSecondMember(ilGenerator);
emitComparison(ilGenerator);
ilGenerator.Emit(OpCodes.Ldc_I4_0);
ilGenerator.Emit(OpCodes.Ret);
}
private static Action<ILGenerator> GetEmitLoadAndCompareForReferenceType(ConcurrentDictionary<Type, LocalBuilder> firstMemberLocalMap,
ConcurrentDictionary<Type, LocalBuilder> secondMemberLocalMap,
Type memberType,
Label nextMember,
ref Action<ILGenerator> emitLoadFirstMember,
ref Action<ILGenerator> emitLoadSecondMember) {
LocalBuilder firstLocal = null;
emitLoadFirstMember = emitLoadFirstMember.CombineDelegates(ilg => {
firstLocal = firstMemberLocalMap.GetOrAdd(memberType, ilg.DeclareLocal);
ilg.Emit(OpCodes.Stloc, firstLocal);
});
LocalBuilder secondLocal = null;
emitLoadSecondMember = emitLoadSecondMember.CombineDelegates(ilg => {
secondLocal = secondMemberLocalMap.GetOrAdd(memberType, ilg.DeclareLocal);
ilg.Emit(OpCodes.Stloc, secondLocal);
});
return ilg => {
var nonNullMemberCompare = ilg.DefineLabel();
ilg.Emit(OpCodes.Ldloc, firstLocal);
ilg.Emit(OpCodes.Brtrue, nonNullMemberCompare);
ilg.Emit(OpCodes.Ldloc, secondLocal);
ilg.Emit(OpCodes.Brfalse, nextMember);
ilg.Emit(OpCodes.Ldc_I4_0);
ilg.Emit(OpCodes.Ret);
ilg.MarkLabel(nonNullMemberCompare);
ilg.Emit(OpCodes.Ldloc, firstLocal);
ilg.Emit(OpCodes.Ldloc, secondLocal);
};
}
private static Action<ILGenerator> GetEmitLoadMembersForValueType(ConcurrentDictionary<Type, LocalBuilder> localMap, MemberInfo memberInfo, Type memberType, Action<ILGenerator> emitLoadFirstMember) {
if (memberInfo is FieldInfo)
return ilg => ilg.Emit(OpCodes.Ldflda, (FieldInfo) memberInfo);
if (memberInfo is PropertyInfo) {
return emitLoadFirstMember.CombineDelegates(ilg => {
var local = localMap.GetOrAdd(memberType, ilg.DeclareLocal);
ilg.Emit(OpCodes.Stloc, local);
ilg.Emit(OpCodes.Ldloca, local);
});
}
throw new ArgumentOutOfRangeException(nameof(memberInfo), "Must be FieldInfo or PropertyInfo");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////////////////////////////////////////////////////////////////////////////
//
//
//
// Purpose: This class represents the software preferences of a particular
// culture or community. It includes information such as the
// language, writing system, and a calendar used by the culture
// as well as methods for common operations such as printing
// dates and sorting strings.
//
//
//
// !!!! NOTE WHEN CHANGING THIS CLASS !!!!
//
// If adding or removing members to this class, please update CultureInfoBaseObject
// in ndp/clr/src/vm/object.h. Note, the "actual" layout of the class may be
// different than the order in which members are declared. For instance, all
// reference types will come first in the class before value types (like ints, bools, etc)
// regardless of the order in which they are declared. The best way to see the
// actual order of the class is to do a !dumpobj on an instance of the managed
// object inside of the debugger.
//
////////////////////////////////////////////////////////////////////////////
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Threading;
#if ENABLE_WINRT
using Internal.Runtime.Augments;
#endif
namespace System.Globalization
{
public partial class CultureInfo : IFormatProvider, ICloneable
{
//--------------------------------------------------------------------//
// Internal Information //
//--------------------------------------------------------------------//
//--------------------------------------------------------------------//
// Data members to be serialized:
//--------------------------------------------------------------------//
// We use an RFC4646 type string to construct CultureInfo.
// This string is stored in _name and is authoritative.
// We use the _cultureData to get the data for our object
private bool _isReadOnly;
private CompareInfo _compareInfo;
private TextInfo _textInfo;
internal NumberFormatInfo numInfo;
internal DateTimeFormatInfo dateTimeInfo;
private Calendar _calendar;
//
// The CultureData instance that we are going to read data from.
// For supported culture, this will be the CultureData instance that read data from mscorlib assembly.
// For customized culture, this will be the CultureData instance that read data from user customized culture binary file.
//
internal CultureData _cultureData;
internal bool _isInherited;
private CultureInfo _consoleFallbackCulture;
// Names are confusing. Here are 3 names we have:
//
// new CultureInfo() _name _nonSortName _sortName
// en-US en-US en-US en-US
// de-de_phoneb de-DE_phoneb de-DE de-DE_phoneb
// fj-fj (custom) fj-FJ fj-FJ en-US (if specified sort is en-US)
// en en
//
// Note that in Silverlight we ask the OS for the text and sort behavior, so the
// textinfo and compareinfo names are the same as the name
// Note that the name used to be serialized for Everett; it is now serialized
// because alternate sorts can have alternate names.
// This has a de-DE, de-DE_phoneb or fj-FJ style name
internal string _name;
// This will hold the non sorting name to be returned from CultureInfo.Name property.
// This has a de-DE style name even for de-DE_phoneb type cultures
private string _nonSortName;
// This will hold the sorting name to be returned from CultureInfo.SortName property.
// This might be completely unrelated to the culture name if a custom culture. Ie en-US for fj-FJ.
// Otherwise its the sort name, ie: de-DE or de-DE_phoneb
private string _sortName;
//--------------------------------------------------------------------//
//
// Static data members
//
//--------------------------------------------------------------------//
private static volatile CultureInfo s_userDefaultCulture;
private static volatile CultureInfo s_userDefaultUICulture;
// WARNING: We allow diagnostic tools to directly inspect these three members (s_InvariantCultureInfo, s_DefaultThreadCurrentUICulture and s_DefaultThreadCurrentCulture)
// See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details.
// Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools.
// Get in touch with the diagnostics team if you have questions.
//The Invariant culture;
private static readonly CultureInfo s_InvariantCultureInfo = new CultureInfo(CultureData.Invariant, isReadOnly: true);
//These are defaults that we use if a thread has not opted into having an explicit culture
private static volatile CultureInfo s_DefaultThreadCurrentUICulture;
private static volatile CultureInfo s_DefaultThreadCurrentCulture;
[ThreadStatic]
private static CultureInfo s_currentThreadCulture;
[ThreadStatic]
private static CultureInfo s_currentThreadUICulture;
private static readonly Lock s_lock = new Lock();
private static volatile LowLevelDictionary<string, CultureInfo> s_NameCachedCultures;
private static volatile LowLevelDictionary<int, CultureInfo> s_LcidCachedCultures;
//The parent culture.
private CultureInfo _parent;
// LOCALE constants of interest to us internally and privately for LCID functions
// (ie: avoid using these and use names if possible)
internal const int LOCALE_NEUTRAL = 0x0000;
private const int LOCALE_USER_DEFAULT = 0x0400;
private const int LOCALE_SYSTEM_DEFAULT = 0x0800;
internal const int LOCALE_CUSTOM_UNSPECIFIED = 0x1000;
internal const int LOCALE_CUSTOM_DEFAULT = 0x0c00;
internal const int LOCALE_INVARIANT = 0x007F;
private static CultureInfo InitializeUserDefaultCulture()
{
Interlocked.CompareExchange(ref s_userDefaultCulture, GetUserDefaultCulture(), null);
return s_userDefaultCulture;
}
private static CultureInfo InitializeUserDefaultUICulture()
{
Interlocked.CompareExchange(ref s_userDefaultUICulture, GetUserDefaultUICulture(), null);
return s_userDefaultUICulture;
}
////////////////////////////////////////////////////////////////////////
//
// CultureInfo Constructors
//
////////////////////////////////////////////////////////////////////////
public CultureInfo(String name)
: this(name, true)
{
}
public CultureInfo(String name, bool useUserOverride)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name),
SR.ArgumentNull_String);
}
// Get our data providing record
_cultureData = CultureData.GetCultureData(name, useUserOverride);
if (_cultureData == null)
throw new CultureNotFoundException(
nameof(name), name, SR.Argument_CultureNotSupported);
_name = _cultureData.CultureName;
_isInherited = !this.EETypePtr.FastEquals(EETypePtr.EETypePtrOf<CultureInfo>());
}
private CultureInfo(CultureData cultureData, bool isReadOnly = false)
{
Debug.Assert(cultureData != null);
_cultureData = cultureData;
_name = cultureData.CultureName;
_isInherited = false;
_isReadOnly = isReadOnly;
}
private static CultureInfo CreateCultureInfoNoThrow(string name, bool useUserOverride)
{
Debug.Assert(name != null);
CultureData cultureData = CultureData.GetCultureData(name, useUserOverride);
if (cultureData == null)
{
return null;
}
return new CultureInfo(cultureData);
}
public CultureInfo(int culture) : this(culture, true)
{
}
public CultureInfo(int culture, bool useUserOverride)
{
// We don't check for other invalid LCIDS here...
if (culture < 0)
{
throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum);
}
switch (culture)
{
case LOCALE_CUSTOM_DEFAULT:
case LOCALE_SYSTEM_DEFAULT:
case LOCALE_NEUTRAL:
case LOCALE_USER_DEFAULT:
case LOCALE_CUSTOM_UNSPECIFIED:
// Can't support unknown custom cultures and we do not support neutral or
// non-custom user locales.
throw new CultureNotFoundException(nameof(culture), culture, SR.Argument_CultureNotSupported);
default:
// Now see if this LCID is supported in the system default CultureData table.
_cultureData = CultureData.GetCultureData(culture, useUserOverride);
break;
}
_isInherited = (this.GetType() != typeof(System.Globalization.CultureInfo));
_name = _cultureData.CultureName;
}
// Constructor called by SQL Server's special munged culture - creates a culture with
// a TextInfo and CompareInfo that come from a supplied alternate source. This object
// is ALWAYS read-only.
// Note that we really cannot use an LCID version of this override as the cached
// name we create for it has to include both names, and the logic for this is in
// the GetCultureInfo override *only*.
internal CultureInfo(String cultureName, String textAndCompareCultureName)
{
if (cultureName == null)
{
throw new ArgumentNullException(nameof(cultureName), SR.ArgumentNull_String);
}
_cultureData = CultureData.GetCultureData(cultureName, false);
if (_cultureData == null)
throw new CultureNotFoundException(nameof(cultureName), cultureName, SR.Argument_CultureNotSupported);
_name = _cultureData.CultureName;
CultureInfo altCulture = GetCultureInfo(textAndCompareCultureName);
_compareInfo = altCulture.CompareInfo;
_textInfo = altCulture.TextInfo;
}
// We do this to try to return the system UI language and the default user languages
// This method will fallback if this fails (like Invariant)
//
// TODO: It would appear that this is only ever called with userOveride = true
// and this method only has one caller. Can we fold it into the caller?
private static CultureInfo GetCultureByName(String name, bool userOverride)
{
CultureInfo ci = null;
// Try to get our culture
try
{
ci = userOverride ? new CultureInfo(name) : CultureInfo.GetCultureInfo(name);
}
catch (ArgumentException)
{
}
if (ci == null)
{
ci = InvariantCulture;
}
return ci;
}
//
// Return a specific culture. A tad irrelevent now since we always return valid data
// for neutral locales.
//
// Note that there's interesting behavior that tries to find a smaller name, ala RFC4647,
// if we can't find a bigger name. That doesn't help with things like "zh" though, so
// the approach is of questionable value
//
public static CultureInfo CreateSpecificCulture(String name)
{
CultureInfo culture;
try
{
culture = new CultureInfo(name);
}
catch (ArgumentException)
{
// When CultureInfo throws this exception, it may be because someone passed the form
// like "az-az" because it came out of an http accept lang. We should try a little
// parsing to perhaps fall back to "az" here and use *it* to create the neutral.
int idx;
culture = null;
for (idx = 0; idx < name.Length; idx++)
{
if ('-' == name[idx])
{
try
{
culture = new CultureInfo(name.Substring(0, idx));
break;
}
catch (ArgumentException)
{
// throw the original exception so the name in the string will be right
throw;
}
}
}
if (culture == null)
{
// nothing to save here; throw the original exception
throw;
}
}
// In the most common case, they've given us a specific culture, so we'll just return that.
if (!(culture.IsNeutralCulture))
{
return culture;
}
return (new CultureInfo(culture._cultureData.SSPECIFICCULTURE));
}
internal static bool VerifyCultureName(String cultureName, bool throwException)
{
// This function is used by ResourceManager.GetResourceFileName().
// ResourceManager searches for resource using CultureInfo.Name,
// so we should check against CultureInfo.Name.
for (int i = 0; i < cultureName.Length; i++)
{
char c = cultureName[i];
// TODO: Names can only be RFC4646 names (ie: a-zA-Z0-9) while this allows any unicode letter/digit
if (Char.IsLetterOrDigit(c) || c == '-' || c == '_')
{
continue;
}
if (throwException)
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidResourceCultureName, cultureName));
}
return false;
}
return true;
}
internal static bool VerifyCultureName(CultureInfo culture, bool throwException)
{
//If we have an instance of one of our CultureInfos, the user can't have changed the
//name and we know that all names are valid in files.
if (!culture._isInherited)
{
return true;
}
return VerifyCultureName(culture.Name, throwException);
}
////////////////////////////////////////////////////////////////////////
//
// CurrentCulture
//
// This instance provides methods based on the current user settings.
// These settings are volatile and may change over the lifetime of the
// thread.
//
////////////////////////////////////////////////////////////////////////
//
// We use the following order to return CurrentCulture and CurrentUICulture
// o Use WinRT to return the current user profile language
// o use current thread culture if the user already set one using CurrentCulture/CurrentUICulture
// o use thread culture if the user already set one using DefaultThreadCurrentCulture
// or DefaultThreadCurrentUICulture
// o Use NLS default user culture
// o Use NLS default system culture
// o Use Invariant culture
//
public static CultureInfo CurrentCulture
{
get
{
CultureInfo ci = GetUserDefaultCultureCacheOverride();
if (ci != null)
{
return ci;
}
if (s_currentThreadCulture != null)
{
return s_currentThreadCulture;
}
ci = s_DefaultThreadCurrentCulture;
if (ci != null)
{
return ci;
}
return s_userDefaultCulture ?? InitializeUserDefaultCulture();
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
#if ENABLE_WINRT
WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks;
if (callbacks != null && callbacks.IsAppxModel())
{
callbacks.SetGlobalDefaultCulture(value);
return;
}
#endif
s_currentThreadCulture = value;
}
}
public static CultureInfo CurrentUICulture
{
get
{
CultureInfo ci = GetUserDefaultCultureCacheOverride();
if (ci != null)
{
return ci;
}
if (s_currentThreadUICulture != null)
{
return s_currentThreadUICulture;
}
ci = s_DefaultThreadCurrentUICulture;
if (ci != null)
{
return ci;
}
return s_userDefaultUICulture ?? InitializeUserDefaultUICulture();
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
CultureInfo.VerifyCultureName(value, true);
#if ENABLE_WINRT
WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks;
if (callbacks != null && callbacks.IsAppxModel())
{
callbacks.SetGlobalDefaultCulture(value);
return;
}
#endif
s_currentThreadUICulture = value;
}
}
internal static void ResetThreadCulture()
{
s_currentThreadCulture = null;
s_currentThreadUICulture = null;
}
internal static CultureInfo UserDefaultUICulture => s_userDefaultUICulture ?? InitializeUserDefaultUICulture();
public static CultureInfo InstalledUICulture => s_userDefaultCulture ?? InitializeUserDefaultCulture();
public static CultureInfo DefaultThreadCurrentCulture
{
get { return s_DefaultThreadCurrentCulture; }
set
{
// If you add pre-conditions to this method, check to see if you also need to
// add them to Thread.CurrentCulture.set.
s_DefaultThreadCurrentCulture = value;
}
}
public static CultureInfo DefaultThreadCurrentUICulture
{
get { return s_DefaultThreadCurrentUICulture; }
set
{
//If they're trying to use a Culture with a name that we can't use in resource lookup,
//don't even let them set it on the thread.
// If you add more pre-conditions to this method, check to see if you also need to
// add them to Thread.CurrentUICulture.set.
if (value != null)
{
CultureInfo.VerifyCultureName(value, true);
}
s_DefaultThreadCurrentUICulture = value;
}
}
////////////////////////////////////////////////////////////////////////
//
// InvariantCulture
//
// This instance provides methods, for example for casing and sorting,
// that are independent of the system and current user settings. It
// should be used only by processes such as some system services that
// require such invariant results (eg. file systems). In general,
// the results are not linguistically correct and do not match any
// culture info.
//
////////////////////////////////////////////////////////////////////////
public static CultureInfo InvariantCulture
{
get
{
Debug.Assert(s_InvariantCultureInfo != null);
return (s_InvariantCultureInfo);
}
}
////////////////////////////////////////////////////////////////////////
//
// Parent
//
// Return the parent CultureInfo for the current instance.
//
////////////////////////////////////////////////////////////////////////
public virtual CultureInfo Parent
{
get
{
if (null == _parent)
{
CultureInfo culture = null;
string parentName = _cultureData.SPARENT;
if (String.IsNullOrEmpty(parentName))
{
culture = InvariantCulture;
}
else
{
culture = CreateCultureInfoNoThrow(parentName, _cultureData.UseUserOverride);
if (culture == null)
{
// For whatever reason our IPARENT or SPARENT wasn't correct, so use invariant
// We can't allow ourselves to fail. In case of custom cultures the parent of the
// current custom culture isn't installed.
culture = InvariantCulture;
}
}
Interlocked.CompareExchange<CultureInfo>(ref _parent, culture, null);
}
return _parent;
}
}
public virtual int LCID
{
get
{
return _cultureData.ILANGUAGE;
}
}
public virtual int KeyboardLayoutId
{
get
{
return _cultureData.IINPUTLANGUAGEHANDLE;
}
}
public static CultureInfo[] GetCultures(CultureTypes types)
{
// internally we treat UserCustomCultures as Supplementals but v2
// treats as Supplementals and Replacements
if ((types & CultureTypes.UserCustomCulture) == CultureTypes.UserCustomCulture)
{
types |= CultureTypes.ReplacementCultures;
}
return (CultureData.GetCultures(types));
}
////////////////////////////////////////////////////////////////////////
//
// Name
//
// Returns the full name of the CultureInfo. The name is in format like
// "en-US" This version does NOT include sort information in the name.
//
////////////////////////////////////////////////////////////////////////
public virtual String Name
{
get
{
// We return non sorting name here.
if (_nonSortName == null)
{
_nonSortName = _cultureData.SNAME;
if (_nonSortName == null)
{
_nonSortName = String.Empty;
}
}
return _nonSortName;
}
}
// This one has the sort information (ie: de-DE_phoneb)
internal String SortName
{
get
{
if (_sortName == null)
{
_sortName = _cultureData.SCOMPAREINFO;
}
return _sortName;
}
}
public string IetfLanguageTag
{
get
{
// special case the compatibility cultures
switch (this.Name)
{
case "zh-CHT":
return "zh-Hant";
case "zh-CHS":
return "zh-Hans";
default:
return this.Name;
}
}
}
////////////////////////////////////////////////////////////////////////
//
// DisplayName
//
// Returns the full name of the CultureInfo in the localized language.
// For example, if the localized language of the runtime is Spanish and the CultureInfo is
// US English, "Ingles (Estados Unidos)" will be returned.
//
////////////////////////////////////////////////////////////////////////
public virtual String DisplayName
{
get
{
Debug.Assert(_name != null, "[CultureInfo.DisplayName] Always expect _name to be set");
return _cultureData.SLOCALIZEDDISPLAYNAME;
}
}
////////////////////////////////////////////////////////////////////////
//
// GetNativeName
//
// Returns the full name of the CultureInfo in the native language.
// For example, if the CultureInfo is US English, "English
// (United States)" will be returned.
//
////////////////////////////////////////////////////////////////////////
public virtual String NativeName
{
get
{
return _cultureData.SNATIVEDISPLAYNAME;
}
}
////////////////////////////////////////////////////////////////////////
//
// GetEnglishName
//
// Returns the full name of the CultureInfo in English.
// For example, if the CultureInfo is US English, "English
// (United States)" will be returned.
//
////////////////////////////////////////////////////////////////////////
public virtual String EnglishName
{
get
{
return _cultureData.SENGDISPLAYNAME;
}
}
// ie: en
public virtual String TwoLetterISOLanguageName
{
get
{
return _cultureData.SISO639LANGNAME;
}
}
// ie: eng
public virtual String ThreeLetterISOLanguageName
{
get
{
return _cultureData.SISO639LANGNAME2;
}
}
////////////////////////////////////////////////////////////////////////
//
// ThreeLetterWindowsLanguageName
//
// Returns the 3 letter windows language name for the current instance. eg: "ENU"
// The ISO names are much preferred
//
////////////////////////////////////////////////////////////////////////
public virtual String ThreeLetterWindowsLanguageName
{
get
{
return _cultureData.SABBREVLANGNAME;
}
}
////////////////////////////////////////////////////////////////////////
//
// CompareInfo Read-Only Property
//
// Gets the CompareInfo for this culture.
//
////////////////////////////////////////////////////////////////////////
public virtual CompareInfo CompareInfo
{
get
{
if (_compareInfo == null)
{
// Since CompareInfo's don't have any overrideable properties, get the CompareInfo from
// the Non-Overridden CultureInfo so that we only create one CompareInfo per culture
CompareInfo temp = UseUserOverride
? GetCultureInfo(_name).CompareInfo
: new CompareInfo(this);
if (OkayToCacheClassWithCompatibilityBehavior)
{
_compareInfo = temp;
}
else
{
return temp;
}
}
return (_compareInfo);
}
}
private static bool OkayToCacheClassWithCompatibilityBehavior
{
get
{
return true;
}
}
////////////////////////////////////////////////////////////////////////
//
// TextInfo
//
// Gets the TextInfo for this culture.
//
////////////////////////////////////////////////////////////////////////
public virtual TextInfo TextInfo
{
get
{
if (_textInfo == null)
{
// Make a new textInfo
TextInfo tempTextInfo = new TextInfo(_cultureData);
tempTextInfo.SetReadOnlyState(_isReadOnly);
if (OkayToCacheClassWithCompatibilityBehavior)
{
_textInfo = tempTextInfo;
}
else
{
return tempTextInfo;
}
}
return (_textInfo);
}
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same CultureInfo as the current instance.
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object value)
{
if (Object.ReferenceEquals(this, value))
return true;
CultureInfo that = value as CultureInfo;
if (that != null)
{
// using CompareInfo to verify the data passed through the constructor
// CultureInfo(String cultureName, String textAndCompareCultureName)
return (this.Name.Equals(that.Name) && this.CompareInfo.Equals(that.CompareInfo));
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// CultureInfo. The hash code is guaranteed to be the same for CultureInfo A
// and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (this.Name.GetHashCode() + this.CompareInfo.GetHashCode());
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns the name of the CultureInfo,
// eg. "de-DE_phoneb", "en-US", or "fj-FJ".
//
////////////////////////////////////////////////////////////////////////
public override String ToString()
{
return _name;
}
public virtual Object GetFormat(Type formatType)
{
if (formatType == typeof(NumberFormatInfo))
return (NumberFormat);
if (formatType == typeof(DateTimeFormatInfo))
return (DateTimeFormat);
return (null);
}
public virtual bool IsNeutralCulture
{
get
{
return _cultureData.IsNeutralCulture;
}
}
public CultureTypes CultureTypes
{
get
{
CultureTypes types = 0;
if (_cultureData.IsNeutralCulture)
types |= CultureTypes.NeutralCultures;
else
types |= CultureTypes.SpecificCultures;
types |= _cultureData.IsWin32Installed ? CultureTypes.InstalledWin32Cultures : 0;
// Disable warning 618: System.Globalization.CultureTypes.FrameworkCultures' is obsolete
#pragma warning disable 618
types |= _cultureData.IsFramework ? CultureTypes.FrameworkCultures : 0;
#pragma warning restore 618
types |= _cultureData.IsSupplementalCustomCulture ? CultureTypes.UserCustomCulture : 0;
types |= _cultureData.IsReplacementCulture ? CultureTypes.ReplacementCultures | CultureTypes.UserCustomCulture : 0;
return types;
}
}
public virtual NumberFormatInfo NumberFormat
{
get
{
if (numInfo == null)
{
NumberFormatInfo temp = new NumberFormatInfo(_cultureData);
temp.isReadOnly = _isReadOnly;
Interlocked.CompareExchange(ref numInfo, temp, null);
}
return (numInfo);
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value), SR.ArgumentNull_Obj);
}
VerifyWritable();
numInfo = value;
}
}
////////////////////////////////////////////////////////////////////////
//
// GetDateTimeFormatInfo
//
// Create a DateTimeFormatInfo, and fill in the properties according to
// the CultureID.
//
////////////////////////////////////////////////////////////////////////
public virtual DateTimeFormatInfo DateTimeFormat
{
get
{
if (dateTimeInfo == null)
{
// Change the calendar of DTFI to the specified calendar of this CultureInfo.
DateTimeFormatInfo temp = new DateTimeFormatInfo(_cultureData, this.Calendar);
temp._isReadOnly = _isReadOnly;
Interlocked.CompareExchange(ref dateTimeInfo, temp, null);
}
return (dateTimeInfo);
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value), SR.ArgumentNull_Obj);
}
VerifyWritable();
dateTimeInfo = value;
}
}
public void ClearCachedData()
{
// reset the default culture values
s_userDefaultCulture = GetUserDefaultCulture();
s_userDefaultUICulture = GetUserDefaultUICulture();
RegionInfo.s_currentRegionInfo = null;
#pragma warning disable 0618 // disable the obsolete warning
TimeZone.ResetTimeZone();
#pragma warning restore 0618
TimeZoneInfo.ClearCachedData();
s_LcidCachedCultures = null;
s_NameCachedCultures = null;
CultureData.ClearCachedData();
}
/*=================================GetCalendarInstance==========================
**Action: Map a Win32 CALID to an instance of supported calendar.
**Returns: An instance of calendar.
**Arguments: calType The Win32 CALID
**Exceptions:
** Shouldn't throw exception since the calType value is from our data table or from Win32 registry.
** If we are in trouble (like getting a weird value from Win32 registry), just return the GregorianCalendar.
============================================================================*/
internal static Calendar GetCalendarInstance(CalendarId calType)
{
if (calType == CalendarId.GREGORIAN)
{
return (new GregorianCalendar());
}
return GetCalendarInstanceRare(calType);
}
//This function exists as a shortcut to prevent us from loading all of the non-gregorian
//calendars unless they're required.
internal static Calendar GetCalendarInstanceRare(CalendarId calType)
{
Debug.Assert(calType != CalendarId.GREGORIAN, "calType!=CalendarId.GREGORIAN");
switch (calType)
{
case CalendarId.GREGORIAN_US: // Gregorian (U.S.) calendar
case CalendarId.GREGORIAN_ME_FRENCH: // Gregorian Middle East French calendar
case CalendarId.GREGORIAN_ARABIC: // Gregorian Arabic calendar
case CalendarId.GREGORIAN_XLIT_ENGLISH: // Gregorian Transliterated English calendar
case CalendarId.GREGORIAN_XLIT_FRENCH: // Gregorian Transliterated French calendar
return (new GregorianCalendar((GregorianCalendarTypes)calType));
case CalendarId.TAIWAN: // Taiwan Era calendar
return (new TaiwanCalendar());
case CalendarId.JAPAN: // Japanese Emperor Era calendar
return (new JapaneseCalendar());
case CalendarId.KOREA: // Korean Tangun Era calendar
return (new KoreanCalendar());
case CalendarId.THAI: // Thai calendar
return (new ThaiBuddhistCalendar());
case CalendarId.HIJRI: // Hijri (Arabic Lunar) calendar
return (new HijriCalendar());
case CalendarId.HEBREW: // Hebrew (Lunar) calendar
return (new HebrewCalendar());
case CalendarId.UMALQURA:
return (new UmAlQuraCalendar());
case CalendarId.PERSIAN:
return (new PersianCalendar());
}
return (new GregorianCalendar());
}
/*=================================Calendar==========================
**Action: Return/set the default calendar used by this culture.
** This value can be overridden by regional option if this is a current culture.
**Returns:
**Arguments:
**Exceptions:
** ArgumentNull_Obj if the set value is null.
============================================================================*/
public virtual Calendar Calendar
{
get
{
if (_calendar == null)
{
Debug.Assert(_cultureData.CalendarIds.Length > 0, "_cultureData.CalendarIds.Length > 0");
// Get the default calendar for this culture. Note that the value can be
// from registry if this is a user default culture.
Calendar newObj = _cultureData.DefaultCalendar;
System.Threading.Interlocked.MemoryBarrier();
newObj.SetReadOnlyState(_isReadOnly);
_calendar = newObj;
}
return (_calendar);
}
}
/*=================================OptionCalendars==========================
**Action: Return an array of the optional calendar for this culture.
**Returns: an array of Calendar.
**Arguments:
**Exceptions:
============================================================================*/
public virtual Calendar[] OptionalCalendars
{
get
{
//
// This property always returns a new copy of the calendar array.
//
CalendarId[] calID = _cultureData.CalendarIds;
Calendar[] cals = new Calendar[calID.Length];
for (int i = 0; i < cals.Length; i++)
{
cals[i] = GetCalendarInstance(calID[i]);
}
return (cals);
}
}
public bool UseUserOverride
{
get
{
return _cultureData.UseUserOverride;
}
}
public CultureInfo GetConsoleFallbackUICulture()
{
CultureInfo temp = _consoleFallbackCulture;
if (temp == null)
{
temp = CreateSpecificCulture(_cultureData.SCONSOLEFALLBACKNAME);
temp._isReadOnly = true;
_consoleFallbackCulture = temp;
}
return (temp);
}
public virtual Object Clone()
{
CultureInfo ci = (CultureInfo)MemberwiseClone();
ci._isReadOnly = false;
//If this is exactly our type, we can make certain optimizations so that we don't allocate NumberFormatInfo or DTFI unless
//they've already been allocated. If this is a derived type, we'll take a more generic codepath.
if (!_isInherited)
{
if (this.dateTimeInfo != null)
{
ci.dateTimeInfo = (DateTimeFormatInfo)this.dateTimeInfo.Clone();
}
if (this.numInfo != null)
{
ci.numInfo = (NumberFormatInfo)this.numInfo.Clone();
}
}
else
{
ci.DateTimeFormat = (DateTimeFormatInfo)this.DateTimeFormat.Clone();
ci.NumberFormat = (NumberFormatInfo)this.NumberFormat.Clone();
}
if (_textInfo != null)
{
ci._textInfo = (TextInfo)_textInfo.Clone();
}
if (_calendar != null)
{
ci._calendar = (Calendar)_calendar.Clone();
}
return (ci);
}
public static CultureInfo ReadOnly(CultureInfo ci)
{
if (ci == null)
{
throw new ArgumentNullException(nameof(ci));
}
if (ci.IsReadOnly)
{
return (ci);
}
CultureInfo newInfo = (CultureInfo)(ci.MemberwiseClone());
if (!ci.IsNeutralCulture)
{
//If this is exactly our type, we can make certain optimizations so that we don't allocate NumberFormatInfo or DTFI unless
//they've already been allocated. If this is a derived type, we'll take a more generic codepath.
if (!ci._isInherited)
{
if (ci.dateTimeInfo != null)
{
newInfo.dateTimeInfo = DateTimeFormatInfo.ReadOnly(ci.dateTimeInfo);
}
if (ci.numInfo != null)
{
newInfo.numInfo = NumberFormatInfo.ReadOnly(ci.numInfo);
}
}
else
{
newInfo.DateTimeFormat = DateTimeFormatInfo.ReadOnly(ci.DateTimeFormat);
newInfo.NumberFormat = NumberFormatInfo.ReadOnly(ci.NumberFormat);
}
}
if (ci._textInfo != null)
{
newInfo._textInfo = TextInfo.ReadOnly(ci._textInfo);
}
if (ci._calendar != null)
{
newInfo._calendar = Calendar.ReadOnly(ci._calendar);
}
// Don't set the read-only flag too early.
// We should set the read-only flag here. Otherwise, info.DateTimeFormat will not be able to set.
newInfo._isReadOnly = true;
return (newInfo);
}
public bool IsReadOnly
{
get
{
return (_isReadOnly);
}
}
private void VerifyWritable()
{
if (_isReadOnly)
{
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
}
// For resource lookup, we consider a culture the invariant culture by name equality.
// We perform this check frequently during resource lookup, so adding a property for
// improved readability.
internal bool HasInvariantCultureName
{
get { return Name == CultureInfo.InvariantCulture.Name; }
}
// Helper function both both overloads of GetCachedReadOnlyCulture. If lcid is 0, we use the name.
// If lcid is -1, use the altName and create one of those special SQL cultures.
internal static CultureInfo GetCultureInfoHelper(int lcid, string name, string altName)
{
// retval is our return value.
CultureInfo retval;
// Temporary hashtable for the names.
LowLevelDictionary<string, CultureInfo> tempNameHT = s_NameCachedCultures;
if (name != null)
{
name = CultureData.AnsiToLower(name);
}
if (altName != null)
{
altName = CultureData.AnsiToLower(altName);
}
// We expect the same result for both hashtables, but will test individually for added safety.
if (tempNameHT == null)
{
tempNameHT = new LowLevelDictionary<string, CultureInfo>();
}
else
{
// If we are called by name, check if the object exists in the hashtable. If so, return it.
if (lcid == -1 || lcid == 0)
{
bool ret;
using (LockHolder.Hold(s_lock))
{
ret = tempNameHT.TryGetValue(lcid == 0 ? name : name + '\xfffd' + altName, out retval);
}
if (ret && retval != null)
{
return retval;
}
}
}
// Next, the Lcid table.
LowLevelDictionary<int, CultureInfo> tempLcidHT = s_LcidCachedCultures;
if (tempLcidHT == null)
{
// Case insensitive is not an issue here, save the constructor call.
tempLcidHT = new LowLevelDictionary<int, CultureInfo>();
}
else
{
// If we were called by Lcid, check if the object exists in the table. If so, return it.
if (lcid > 0)
{
bool ret;
using (LockHolder.Hold(s_lock))
{
ret = tempLcidHT.TryGetValue(lcid, out retval);
}
if (ret && retval != null)
{
return retval;
}
}
}
// We now have two temporary hashtables and the desired object was not found.
// We'll construct it. We catch any exceptions from the constructor call and return null.
try
{
switch (lcid)
{
case -1:
// call the private constructor
retval = new CultureInfo(name, altName);
break;
case 0:
retval = new CultureInfo(name, false);
break;
default:
retval = new CultureInfo(lcid, false);
break;
}
}
catch (ArgumentException)
{
return null;
}
// Set it to read-only
retval._isReadOnly = true;
if (lcid == -1)
{
using (LockHolder.Hold(s_lock))
{
// This new culture will be added only to the name hash table.
tempNameHT[name + '\xfffd' + altName] = retval;
}
// when lcid == -1 then TextInfo object is already get created and we need to set it as read only.
retval.TextInfo.SetReadOnlyState(true);
}
else if (lcid == 0)
{
// Remember our name (as constructed). Do NOT use alternate sort name versions because
// we have internal state representing the sort. (So someone would get the wrong cached version)
string newName = CultureData.AnsiToLower(retval._name);
// We add this new culture info object to both tables.
using (LockHolder.Hold(s_lock))
{
tempNameHT[newName] = retval;
}
}
else
{
using (LockHolder.Hold(s_lock))
{
tempLcidHT[lcid] = retval;
}
}
// Copy the two hashtables to the corresponding member variables. This will potentially overwrite
// new tables simultaneously created by a new thread, but maximizes thread safety.
if (-1 != lcid)
{
// Only when we modify the lcid hash table, is there a need to overwrite.
s_LcidCachedCultures = tempLcidHT;
}
s_NameCachedCultures = tempNameHT;
// Finally, return our new CultureInfo object.
return retval;
}
// Gets a cached copy of the specified culture from an internal hashtable (or creates it
// if not found). (LCID version)... use named version
public static CultureInfo GetCultureInfo(int culture)
{
// Must check for -1 now since the helper function uses the value to signal
// the altCulture code path for SQL Server.
// Also check for zero as this would fail trying to add as a key to the hash.
if (culture <= 0)
{
throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum);
}
CultureInfo retval = GetCultureInfoHelper(culture, null, null);
if (null == retval)
{
throw new CultureNotFoundException(nameof(culture), culture, SR.Argument_CultureNotSupported);
}
return retval;
}
// Gets a cached copy of the specified culture from an internal hashtable (or creates it
// if not found). (Named version)
public static CultureInfo GetCultureInfo(string name)
{
// Make sure we have a valid, non-zero length string as name
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
CultureInfo retval = GetCultureInfoHelper(0, name, null);
if (retval == null)
{
throw new CultureNotFoundException(
nameof(name), name, SR.Argument_CultureNotSupported);
}
return retval;
}
// Gets a cached copy of the specified culture from an internal hashtable (or creates it
// if not found).
public static CultureInfo GetCultureInfo(string name, string altName)
{
// Make sure we have a valid, non-zero length string as name
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (altName == null)
{
throw new ArgumentNullException(nameof(altName));
}
CultureInfo retval = GetCultureInfoHelper(-1, name, altName);
if (retval == null)
{
throw new CultureNotFoundException("name or altName",
SR.Format(SR.Argument_OneOfCulturesNotSupported, name, altName));
}
return retval;
}
// This function is deprecated, we don't like it
public static CultureInfo GetCultureInfoByIetfLanguageTag(string name)
{
// Disallow old zh-CHT/zh-CHS names
if (name == "zh-CHT" || name == "zh-CHS")
{
throw new CultureNotFoundException(nameof(name), SR.Format(SR.Argument_CultureIetfNotSupported, name));
}
CultureInfo ci = GetCultureInfo(name);
// Disallow alt sorts and es-es_TS
if (ci.LCID > 0xffff || ci.LCID == 0x040a)
{
throw new CultureNotFoundException(nameof(name), SR.Format(SR.Argument_CultureIetfNotSupported, name));
}
return ci;
}
}
}
| |
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 WebApiUniqueConstraintHandling.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;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.Tracing;
// We wish to test both Microsoft.Diagnostics.Tracing (Nuget)
// and System.Diagnostics.Tracing (Framewwork), we use this Ifdef make each kind
namespace SdtEventSources
{
public class UnsealedEventSource : EventSource
{
[Event(1, Level = EventLevel.Informational)]
public void WriteInteger(int n)
{
WriteEvent(1, n);
}
}
public sealed class EventWithReturnEventSource : EventSource
{
[Event(1, Level = EventLevel.Informational)]
public int WriteInteger(int n)
{
WriteEvent(1, n);
return n;
}
}
public sealed class NegativeEventIdEventSource : EventSource
{
[Event(-10, Level = EventLevel.Informational)]
public void WriteInteger(int n)
{
WriteEvent(-10, n);
}
}
// this behaves differently in 4.5 vs. 4.5.1 so just skip it for those scenarios
public sealed class OutOfRangeKwdEventSource : EventSource
{
[Event(1, Keywords = Keywords.Kwd1, Level = EventLevel.Informational)]
public void WriteInteger(int n)
{
WriteEvent(1, n);
}
#region Keywords / Tasks /Opcodes / Channels
public static class Keywords
{
public const EventKeywords Kwd1 = (EventKeywords)0x0000100000000000UL;
}
#endregion
}
public sealed class ReservedOpcodeEventSource : EventSource
{
[Event(1, Opcode = Opcodes.Op1, Level = EventLevel.Informational)]
public void WriteInteger(int n)
{
WriteEvent(1, n);
}
#region Keywords / Tasks /Opcodes / Channels
public static class Opcodes
{
public const EventOpcode Op1 = (EventOpcode)3; // values <= 10 are reserved
}
#endregion
}
public sealed class EnumKindMismatchEventSource : EventSource
{
[Event(1, Keywords = Opcodes.Op1, Level = EventLevel.Informational)]
public void WriteInteger(int n)
{
WriteEvent(1, n);
}
#region Keywords / Tasks /Opcodes / Channels
public static class Opcodes
{
public const EventKeywords Op1 = (EventKeywords)0x1;
}
#endregion
}
public sealed class MismatchIdEventSource : EventSource
{
[Event(10, Level = EventLevel.Informational)]
public void WriteInteger(int n)
{
WriteEvent(1, n);
}
}
public sealed class EventIdReusedEventSource : EventSource
{
[Event(1, Level = EventLevel.Informational)]
public void WriteInteger1(int n)
{
WriteEvent(1, n);
}
[Event(1, Level = EventLevel.Informational)]
public void WriteInteger2(int n)
{
WriteEvent(1, n);
}
}
public sealed class EventNameReusedEventSource : EventSource
{
[Event(1, Level = EventLevel.Informational)]
public void WriteInteger(int n)
{
WriteEvent(1, n);
}
[Event(2, Level = EventLevel.Informational)]
public void WriteInteger(uint n)
{
WriteEvent(2, n);
}
}
public sealed class TaskOpcodePairReusedEventSource : EventSource
{
[Event(1, Task = Tasks.MyTask, Opcode = Opcodes.Op1)]
public void WriteInteger1(int n)
{
WriteEvent(1, n);
}
[Event(2, Task = Tasks.MyTask, Opcode = Opcodes.Op1)]
public void WriteInteger2(int n)
{
WriteEvent(2, n);
}
#region Keywords / Tasks /Opcodes / Channels
public static class Tasks
{
public const EventTask MyTask = (EventTask)1;
}
public static class Opcodes
{
public const EventOpcode Op1 = (EventOpcode)15;
}
#endregion
}
public sealed class EventWithOpcodeNoTaskEventSource : EventSource
{
[Event(1, Opcode = EventOpcode.Send)]
public void WriteInteger(int n)
{
WriteEvent(1, n);
}
}
public sealed class EventWithInvalidMessageEventSource : EventSource
{
[Event(1, Message = "Message = {0,12:G}")]
public void WriteString(string msg)
{ WriteEvent(1, msg); }
}
#if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
public sealed class TooManyChannelsEventSource : EventSource
{
[Event(1, Channel = Channels.Analytic, Level = EventLevel.Informational)]
public void WriteInteger(int n)
{
WriteEvent(1, n);
}
#region Keywords / Tasks /Opcodes / Channels
/// <summary>
/// The Channels definition for the ETW manifest
/// </summary>
public static class Channels
{
[Channel(Enabled = true, ChannelType = ChannelType.Admin)]
public const EventChannel Admin = (EventChannel)16;
[Channel(Enabled = true, ChannelType = ChannelType.Operational)]
public const EventChannel Operational = (EventChannel)17;
[Channel(Enabled = false, ChannelType = ChannelType.Analytic)]
public const EventChannel Analytic = (EventChannel)18;
[Channel(Enabled = false, ChannelType = ChannelType.Debug)]
public const EventChannel Debug = (EventChannel)19;
[Channel(Enabled = true, ChannelType = ChannelType.Admin)]
public const EventChannel Admin2 = (EventChannel)20;
[Channel(Enabled = true, ChannelType = ChannelType.Operational)]
public const EventChannel Operational2 = (EventChannel)21;
[Channel(Enabled = false, ChannelType = ChannelType.Analytic)]
public const EventChannel Analytic2 = (EventChannel)22;
[Channel(Enabled = false, ChannelType = ChannelType.Debug)]
public const EventChannel Debug2 = (EventChannel)23;
[Channel(Enabled = false, ChannelType = ChannelType.Debug)]
public const EventChannel BrokeCamelsBack = (EventChannel)24;
}
#endregion
}
#endif
public sealed class EventWithAdminChannelNoMessageEventSource : EventSource
{
[Event(1, Channel = EventChannel.Admin, Level = EventLevel.Informational)]
public void WriteInteger(int n)
{
WriteEvent(1, n);
}
#region Keywords / Tasks /Opcodes / Channels
#if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
/// <summary>
/// The Channels definition for the ETW manifest
/// </summary>
public static class Channels
{
[Channel(Enabled = true, ChannelType = ChannelType.Admin)]
public const EventChannel Admin = (EventChannel)16;
}
#endif
#endregion
}
public abstract class AbstractWithKwdTaskOpcodeEventSource : EventSource
{
#region Keywords / Tasks /Opcodes / Channels
public static class Keywords
{
public const EventKeywords Kwd1 = (EventKeywords)1;
}
public static class Tasks
{
public const EventTask Task1 = (EventTask)1;
}
public static class Opcodes
{
public const EventOpcode Op1 = (EventOpcode)15;
}
#endregion
}
public abstract class AbstractWithEventsEventSource : EventSource
{
[Event(1)]
public void WriteInteger(int n)
{ WriteEvent(1, n); }
}
public interface ILogging
{
void Error(int errorCode, string msg);
}
public sealed class ImplementsInterfaceEventSource : EventSource, ILogging
{
public static MyLoggingEventSource Log = new MyLoggingEventSource();
[Event(1)]
void ILogging.Error(int errorCode, string msg)
{ WriteEvent(1, errorCode, msg); }
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Text;
using System;
using System.Globalization;
using System.Diagnostics.Contracts;
namespace System.Text
{
// A Decoder is used to decode a sequence of blocks of bytes into a
// sequence of blocks of characters. Following instantiation of a decoder,
// sequential blocks of bytes are converted into blocks of characters through
// calls to the GetChars method. The decoder maintains state between the
// conversions, allowing it to correctly decode byte sequences that span
// adjacent blocks.
//
// Instances of specific implementations of the Decoder abstract base
// class are typically obtained through calls to the GetDecoder method
// of Encoding objects.
//
internal class DecoderNLS : Decoder
{
// Remember our encoding
protected EncodingNLS m_encoding;
protected bool m_mustFlush;
internal bool m_throwOnOverflow;
internal int m_bytesUsed;
internal DecoderFallback m_fallback;
internal DecoderFallbackBuffer m_fallbackBuffer;
internal DecoderNLS(EncodingNLS encoding)
{
m_encoding = encoding;
m_fallback = m_encoding.DecoderFallback;
Reset();
}
// This is used by our child deserializers
internal DecoderNLS()
{
m_encoding = null;
Reset();
}
internal new DecoderFallback Fallback
{
get { return m_fallback; }
}
internal bool InternalHasFallbackBuffer
{
get
{
return m_fallbackBuffer != null;
}
}
public new DecoderFallbackBuffer FallbackBuffer
{
get
{
if (m_fallbackBuffer == null)
{
if (m_fallback != null)
m_fallbackBuffer = m_fallback.CreateFallbackBuffer();
else
m_fallbackBuffer = DecoderFallback.ReplacementFallback.CreateFallbackBuffer();
}
return m_fallbackBuffer;
}
}
public override void Reset()
{
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
public override unsafe int GetCharCount(byte[] bytes, int index, int count)
{
return GetCharCount(bytes, index, count, false);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes", SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
// Avoid null fixed problem
if (bytes.Length == 0)
bytes = new byte[1];
// Just call pointer version
fixed (byte* pBytes = bytes)
return GetCharCount(pBytes + index, count, flush);
}
[System.Security.SecurityCritical] // auto-generated
public unsafe int GetCharCount(byte* bytes, int count, bool flush)
{
// Validate parameters
if (bytes == null)
throw new ArgumentNullException("bytes", SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Remember the flush
m_mustFlush = flush;
m_throwOnOverflow = true;
// By default just call the encoding version, no flush by default
return m_encoding.GetCharCount(bytes, count, this);
}
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, bool flush)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer);
if (charIndex < 0 || charIndex > chars.Length)
throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
// Avoid empty input fixed problem
if (bytes.Length == 0)
bytes = new byte[1];
int charCount = chars.Length - charIndex;
if (chars.Length == 0)
chars = new char[1];
// Just call pointer version
fixed (byte* pBytes = bytes)
fixed (char* pChars = chars)
// Remember that charCount is # to decode, not size of array
return GetChars(pBytes + byteIndex, byteCount,
pChars + charIndex, charCount, flush);
}
[System.Security.SecurityCritical] // auto-generated
public unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, bool flush)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount < 0 ? "byteCount" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Remember our flush
m_mustFlush = flush;
m_throwOnOverflow = true;
// By default just call the encoding's version
return m_encoding.GetChars(bytes, byteCount, chars, charCount, this);
}
// This method is used when the output buffer might not be big enough.
// Just call the pointer version. (This gets chars)
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
{
// Validate parameters
if (bytes == null || chars == null)
throw new ArgumentNullException((bytes == null ? "bytes" : "chars"), SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
// Avoid empty input problem
if (bytes.Length == 0)
bytes = new byte[1];
if (chars.Length == 0)
chars = new char[1];
// Just call the pointer version (public overrides can't do this)
fixed (byte* pBytes = bytes)
{
fixed (char* pChars = chars)
{
Convert(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush,
out bytesUsed, out charsUsed, out completed);
}
}
}
// This is the version that used pointers. We call the base encoding worker function
// after setting our appropriate internal variables. This is getting chars
[System.Security.SecurityCritical] // auto-generated
public unsafe void Convert(byte* bytes, int byteCount,
char* chars, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
{
// Validate input parameters
if (chars == null || bytes == null)
throw new ArgumentNullException(chars == null ? "chars" : "bytes", SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount < 0 ? "byteCount" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// We don't want to throw
m_mustFlush = flush;
m_throwOnOverflow = false;
m_bytesUsed = 0;
// Do conversion
charsUsed = m_encoding.GetChars(bytes, byteCount, chars, charCount, this);
bytesUsed = m_bytesUsed;
// It's completed if they've used what they wanted AND if they didn't want flush or if we are flushed
completed = (bytesUsed == byteCount) && (!flush || !HasState) &&
(m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0);
// Our data thingies are now full, we can return
}
public bool MustFlush
{
get
{
return m_mustFlush;
}
}
// Anything left in our decoder?
internal virtual bool HasState
{
get
{
return false;
}
}
// Allow encoding to clear our must flush instead of throwing (in ThrowCharsOverflow)
internal void ClearMustFlush()
{
m_mustFlush = false;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: booking/rpc/reservation_cancellation_svc.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Booking.RPC {
/// <summary>Holder for reflection information generated from booking/rpc/reservation_cancellation_svc.proto</summary>
public static partial class ReservationCancellationSvcReflection {
#region Descriptor
/// <summary>File descriptor for booking/rpc/reservation_cancellation_svc.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ReservationCancellationSvcReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ci5ib29raW5nL3JwYy9yZXNlcnZhdGlvbl9jYW5jZWxsYXRpb25fc3ZjLnBy",
"b3RvEhdob2xtcy50eXBlcy5ib29raW5nLnJwYxorYm9va2luZy9jYW5jZWxs",
"YXRpb25fcGVuYWx0eV9lc3RpbWF0ZS5wcm90bxojYm9va2luZy9jYW5jZWxs",
"YXRpb25fcmVzcG9uc2UucHJvdG8aLmJvb2tpbmcvaW5kaWNhdG9ycy9yZXNl",
"cnZhdGlvbl9pbmRpY2F0b3IucHJvdG8aMGJvb2tpbmcvcmVzZXJ2YXRpb25z",
"L2NhbmNlbGxlZF9yZXNlcnZhdGlvbi5wcm90bxoiYm9va2luZy9jYW5jZWxs",
"YXRpb25fcmVxdWVzdC5wcm90bxowcHJpbWl0aXZlL3BiX2luY2x1c2l2ZV9j",
"YWxlbmRhcl9kYXRlX3JhbmdlLnByb3RvGi5ib29raW5nL3Jlc2VydmF0aW9u",
"cy9yZXNlcnZhdGlvbl9zdW1tYXJ5LnByb3RvInAKM1Jlc2VydmF0aW9uQ2Fu",
"Y2VsbGF0aW9uU3ZjQ2FuY2VsUmVzZXJ2YXRpb25SZXNwb25zZRI5CgZyZXN1",
"bHQYASABKA4yKS5ob2xtcy50eXBlcy5ib29raW5nLkNhbmNlbGxhdGlvblJl",
"c3BvbnNlIqoBCjlSZXNlcnZhdGlvbkNhbmNlbGxhdGlvblN2Y0dldENhbmNl",
"bGxlZFJlc2VydmF0aW9uUmVzcG9uc2USIAoYcmVzZXJ2YXRpb25faXNfY2Fu",
"Y2VsbGVkGAEgASgIEksKC3Jlc2VydmF0aW9uGAIgASgLMjYuaG9sbXMudHlw",
"ZXMuYm9va2luZy5yZXNlcnZhdGlvbnMuQ2FuY2VsbGVkUmVzZXJ2YXRpb24i",
"iwEKPVJlc2VydmF0aW9uQ2FuY2VsbGF0aW9uU3ZjU2VhcmNoQ2FuY2VsbGVk",
"UmVzZXJ2YXRpb25zUmVzcG9uc2USSgoMcmVzZXJ2YXRpb25zGAEgAygLMjQu",
"aG9sbXMudHlwZXMuYm9va2luZy5yZXNlcnZhdGlvbnMuUmVzZXJ2YXRpb25T",
"dW1tYXJ5MoUFChpSZXNlcnZhdGlvbkNhbmNlbGxhdGlvblN2YxKFAQobRXN0",
"aW1hdGVDYW5jZWxsYXRpb25QZW5hbHR5EjQuaG9sbXMudHlwZXMuYm9va2lu",
"Zy5pbmRpY2F0b3JzLlJlc2VydmF0aW9uSW5kaWNhdG9yGjAuaG9sbXMudHlw",
"ZXMuYm9va2luZy5DYW5jZWxsYXRpb25QZW5hbHR5RXN0aW1hdGUSiwEKEUNh",
"bmNlbFJlc2VydmF0aW9uEiguaG9sbXMudHlwZXMuYm9va2luZy5DYW5jZWxs",
"YXRpb25SZXF1ZXN0GkwuaG9sbXMudHlwZXMuYm9va2luZy5ycGMuUmVzZXJ2",
"YXRpb25DYW5jZWxsYXRpb25TdmNDYW5jZWxSZXNlcnZhdGlvblJlc3BvbnNl",
"EqMBChdHZXRDYW5jZWxsZWRSZXNlcnZhdGlvbhI0LmhvbG1zLnR5cGVzLmJv",
"b2tpbmcuaW5kaWNhdG9ycy5SZXNlcnZhdGlvbkluZGljYXRvchpSLmhvbG1z",
"LnR5cGVzLmJvb2tpbmcucnBjLlJlc2VydmF0aW9uQ2FuY2VsbGF0aW9uU3Zj",
"R2V0Q2FuY2VsbGVkUmVzZXJ2YXRpb25SZXNwb25zZRKqAQobU2VhcmNoQ2Fu",
"Y2VsbGVkUmVzZXJ2YXRpb25zEjMuaG9sbXMudHlwZXMucHJpbWl0aXZlLlBi",
"SW5jbHVzaXZlQ2FsZW5kYXJEYXRlUmFuZ2UaVi5ob2xtcy50eXBlcy5ib29r",
"aW5nLnJwYy5SZXNlcnZhdGlvbkNhbmNlbGxhdGlvblN2Y1NlYXJjaENhbmNl",
"bGxlZFJlc2VydmF0aW9uc1Jlc3BvbnNlQidaC2Jvb2tpbmcvcnBjqgIXSE9M",
"TVMuVHlwZXMuQm9va2luZy5SUENiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.CancellationPenaltyEstimateReflection.Descriptor, global::HOLMS.Types.Booking.CancellationResponseReflection.Descriptor, global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.Reservations.CancelledReservationReflection.Descriptor, global::HOLMS.Types.Booking.CancellationRequestReflection.Descriptor, global::HOLMS.Types.Primitive.PbInclusiveCalendarDateRangeReflection.Descriptor, global::HOLMS.Types.Booking.Reservations.ReservationSummaryReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.ReservationCancellationSvcCancelReservationResponse), global::HOLMS.Types.Booking.RPC.ReservationCancellationSvcCancelReservationResponse.Parser, new[]{ "Result" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.ReservationCancellationSvcGetCancelledReservationResponse), global::HOLMS.Types.Booking.RPC.ReservationCancellationSvcGetCancelledReservationResponse.Parser, new[]{ "ReservationIsCancelled", "Reservation" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.RPC.ReservationCancellationSvcSearchCancelledReservationsResponse), global::HOLMS.Types.Booking.RPC.ReservationCancellationSvcSearchCancelledReservationsResponse.Parser, new[]{ "Reservations" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class ReservationCancellationSvcCancelReservationResponse : pb::IMessage<ReservationCancellationSvcCancelReservationResponse> {
private static readonly pb::MessageParser<ReservationCancellationSvcCancelReservationResponse> _parser = new pb::MessageParser<ReservationCancellationSvcCancelReservationResponse>(() => new ReservationCancellationSvcCancelReservationResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ReservationCancellationSvcCancelReservationResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.RPC.ReservationCancellationSvcReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationCancellationSvcCancelReservationResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationCancellationSvcCancelReservationResponse(ReservationCancellationSvcCancelReservationResponse other) : this() {
result_ = other.result_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationCancellationSvcCancelReservationResponse Clone() {
return new ReservationCancellationSvcCancelReservationResponse(this);
}
/// <summary>Field number for the "result" field.</summary>
public const int ResultFieldNumber = 1;
private global::HOLMS.Types.Booking.CancellationResponse result_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.CancellationResponse Result {
get { return result_; }
set {
result_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ReservationCancellationSvcCancelReservationResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ReservationCancellationSvcCancelReservationResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Result != other.Result) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Result != 0) hash ^= Result.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 (Result != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) Result);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Result != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ReservationCancellationSvcCancelReservationResponse other) {
if (other == null) {
return;
}
if (other.Result != 0) {
Result = other.Result;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
result_ = (global::HOLMS.Types.Booking.CancellationResponse) input.ReadEnum();
break;
}
}
}
}
}
public sealed partial class ReservationCancellationSvcGetCancelledReservationResponse : pb::IMessage<ReservationCancellationSvcGetCancelledReservationResponse> {
private static readonly pb::MessageParser<ReservationCancellationSvcGetCancelledReservationResponse> _parser = new pb::MessageParser<ReservationCancellationSvcGetCancelledReservationResponse>(() => new ReservationCancellationSvcGetCancelledReservationResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ReservationCancellationSvcGetCancelledReservationResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.RPC.ReservationCancellationSvcReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationCancellationSvcGetCancelledReservationResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationCancellationSvcGetCancelledReservationResponse(ReservationCancellationSvcGetCancelledReservationResponse other) : this() {
reservationIsCancelled_ = other.reservationIsCancelled_;
Reservation = other.reservation_ != null ? other.Reservation.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationCancellationSvcGetCancelledReservationResponse Clone() {
return new ReservationCancellationSvcGetCancelledReservationResponse(this);
}
/// <summary>Field number for the "reservation_is_cancelled" field.</summary>
public const int ReservationIsCancelledFieldNumber = 1;
private bool reservationIsCancelled_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool ReservationIsCancelled {
get { return reservationIsCancelled_; }
set {
reservationIsCancelled_ = value;
}
}
/// <summary>Field number for the "reservation" field.</summary>
public const int ReservationFieldNumber = 2;
private global::HOLMS.Types.Booking.Reservations.CancelledReservation reservation_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Reservations.CancelledReservation Reservation {
get { return reservation_; }
set {
reservation_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ReservationCancellationSvcGetCancelledReservationResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ReservationCancellationSvcGetCancelledReservationResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ReservationIsCancelled != other.ReservationIsCancelled) return false;
if (!object.Equals(Reservation, other.Reservation)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ReservationIsCancelled != false) hash ^= ReservationIsCancelled.GetHashCode();
if (reservation_ != null) hash ^= Reservation.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 (ReservationIsCancelled != false) {
output.WriteRawTag(8);
output.WriteBool(ReservationIsCancelled);
}
if (reservation_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Reservation);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ReservationIsCancelled != false) {
size += 1 + 1;
}
if (reservation_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Reservation);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ReservationCancellationSvcGetCancelledReservationResponse other) {
if (other == null) {
return;
}
if (other.ReservationIsCancelled != false) {
ReservationIsCancelled = other.ReservationIsCancelled;
}
if (other.reservation_ != null) {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Reservations.CancelledReservation();
}
Reservation.MergeFrom(other.Reservation);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
ReservationIsCancelled = input.ReadBool();
break;
}
case 18: {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Reservations.CancelledReservation();
}
input.ReadMessage(reservation_);
break;
}
}
}
}
}
public sealed partial class ReservationCancellationSvcSearchCancelledReservationsResponse : pb::IMessage<ReservationCancellationSvcSearchCancelledReservationsResponse> {
private static readonly pb::MessageParser<ReservationCancellationSvcSearchCancelledReservationsResponse> _parser = new pb::MessageParser<ReservationCancellationSvcSearchCancelledReservationsResponse>(() => new ReservationCancellationSvcSearchCancelledReservationsResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ReservationCancellationSvcSearchCancelledReservationsResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.RPC.ReservationCancellationSvcReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationCancellationSvcSearchCancelledReservationsResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationCancellationSvcSearchCancelledReservationsResponse(ReservationCancellationSvcSearchCancelledReservationsResponse other) : this() {
reservations_ = other.reservations_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationCancellationSvcSearchCancelledReservationsResponse Clone() {
return new ReservationCancellationSvcSearchCancelledReservationsResponse(this);
}
/// <summary>Field number for the "reservations" field.</summary>
public const int ReservationsFieldNumber = 1;
private static readonly pb::FieldCodec<global::HOLMS.Types.Booking.Reservations.ReservationSummary> _repeated_reservations_codec
= pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Booking.Reservations.ReservationSummary.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Booking.Reservations.ReservationSummary> reservations_ = new pbc::RepeatedField<global::HOLMS.Types.Booking.Reservations.ReservationSummary>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Booking.Reservations.ReservationSummary> Reservations {
get { return reservations_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ReservationCancellationSvcSearchCancelledReservationsResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ReservationCancellationSvcSearchCancelledReservationsResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!reservations_.Equals(other.reservations_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= reservations_.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) {
reservations_.WriteTo(output, _repeated_reservations_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += reservations_.CalculateSize(_repeated_reservations_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ReservationCancellationSvcSearchCancelledReservationsResponse other) {
if (other == null) {
return;
}
reservations_.Add(other.reservations_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
reservations_.AddEntriesFrom(input, _repeated_reservations_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
/*
* BinaryFormatter.cs - Implementation of the
* "System.Runtime.Serialization.BinaryFormatter" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Runtime.Serialization.Formatters.Binary
{
#if CONFIG_SERIALIZATION
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
public sealed class BinaryFormatter : IRemotingFormatter, IFormatter
{
// Internal state.
private SerializationBinder binder;
private StreamingContext context;
private ISurrogateSelector surrogateSelector;
private FormatterAssemblyStyle assemblyFormat;
private FormatterTypeStyle typeFormat;
private TypeFilterLevel filterLevel;
internal FormatterConverter converter;
// Constructor.
public BinaryFormatter()
{
this.context = new StreamingContext(StreamingContextStates.All);
this.assemblyFormat = FormatterAssemblyStyle.Full;
this.typeFormat = FormatterTypeStyle.TypesAlways;
this.filterLevel = TypeFilterLevel.Full;
this.converter = new FormatterConverter();
}
public BinaryFormatter(ISurrogateSelector selector,
StreamingContext context)
{
this.surrogateSelector = selector;
this.context = context;
this.assemblyFormat = FormatterAssemblyStyle.Full;
this.typeFormat = FormatterTypeStyle.TypesAlways;
this.filterLevel = TypeFilterLevel.Full;
this.converter = new FormatterConverter();
}
// Deserialize an object from a stream.
[TODO]
public Object Deserialize(Stream serializationStream,
HeaderHandler handler)
{
// Validate the parameters.
if(serializationStream == null)
{
throw new ArgumentNullException("serializationStream");
}
// Wrap the stream in a binary reader.
using(BinaryReader reader =
new BinaryReader(serializationStream))
{
DeserializationContext context = new DeserializationContext(this, reader);
return BinaryValueReader.Deserialize(context);
}
}
// Write a serialization header to a stream.
private static void WriteHeader(BinaryWriter writer, bool headersPresent)
{
writer.Write((byte)(BinaryElementType.Header));
writer.Write(1); // Main object.
writer.Write((headersPresent ? 2 : -1)); // Header object.
writer.Write(1); // Major version.
writer.Write(0); // Minor version
}
// Write a serialization footer to a stream.
private static void WriteFooter(BinaryWriter writer)
{
writer.Write((byte)(BinaryElementType.End));
}
// Write an object to a stream.
internal void WriteObject
(BinaryValueWriter.BinaryValueContext context, Object value)
{
// Handle the null case first.
if(value == null)
{
context.writer.Write((byte)(BinaryElementType.NullValue));
return;
}
// Get the type of the object and see if we've
// processed the type before.
Type type = value.GetType();
long typeID = context.gen.GetIDForType(type);
// Allocate an object identifier.
bool firstTime;
long objectID = context.gen.GetId(value, out firstTime);
if(typeID == -1)
{
context.gen.RegisterType(type, objectID);
}
// Get a value writer for the type.
BinaryValueWriter writer;
writer = BinaryValueWriter.GetWriter(context, type);
// Write the object header.
writer.WriteObjectHeader
(context, value, type, objectID, typeID);
// Write the object internals.
writer.WriteObject(context, value, type);
}
// Serialize an object to a stream.
[TODO]
public void Serialize(Stream serializationStream,
Object graph, Header[] headers)
{
// Validate the parameters.
if(graph == null)
{
throw new ArgumentNullException("graph");
}
if(serializationStream == null)
{
throw new ArgumentNullException("serializationStream");
}
// Wrap the stream in a binary writer.
using(BinaryWriter writer =
new BinaryWriter(serializationStream))
{
// Create a binary value writing context.
BinaryValueWriter.BinaryValueContext context =
new BinaryValueWriter.BinaryValueContext(this, writer);
// Allocate object ID's 1 and 2 to the top-most
// object graph and the header block, respectively.
bool firstTime;
context.gen.GetId(graph, out firstTime);
if(headers != null)
{
context.gen.GetId(headers, out firstTime);
}
// Write the header information.
WriteHeader(writer, (headers != null));
// Write the main object for the message.
if(graph is IMethodCallMessage)
{
// TODO
}
else if(graph is IMethodReturnMessage)
{
// TODO
}
else
{
if(headers != null)
{
context.queue.Enqueue(headers);
}
context.queue.Enqueue(graph);
}
// Process outstanding queued objects.
context.ProcessQueue();
// Write the footer information.
WriteFooter(writer);
}
}
// Implement the IFormatter interface.
public SerializationBinder Binder
{
get
{
return binder;
}
set
{
binder = value;
}
}
public StreamingContext Context
{
get
{
return context;
}
set
{
context = value;
}
}
public ISurrogateSelector SurrogateSelector
{
get
{
return surrogateSelector;
}
set
{
surrogateSelector = value;
}
}
public Object Deserialize(Stream serializationStream)
{
return Deserialize(serializationStream, null);
}
public void Serialize(Stream serializationStream, Object graph)
{
Serialize(serializationStream, graph, null);
}
// Formatter properties.
public FormatterAssemblyStyle AssemblyFormat
{
get
{
return assemblyFormat;
}
set
{
assemblyFormat = value;
}
}
public FormatterTypeStyle TypeFormat
{
get
{
return typeFormat;
}
set
{
typeFormat = value;
}
}
[ComVisible(false)]
public TypeFilterLevel FilterLevel
{
get
{
return filterLevel;
}
set
{
filterLevel = value;
}
}
// Deserialize the response to a method call.
[TODO]
public Object DeserializeMethodResponse
(Stream serializationStream, HeaderHandler handler,
IMethodCallMessage methodCallMessage)
{
// TODO
return null;
}
// Unsafe version of "Deserialize".
[ComVisible(false)]
public Object UnsafeDeserialize(Stream serializationStream,
HeaderHandler handler)
{
// We always do things safely.
return Deserialize(serializationStream, handler);
}
// Unsafe version of "DeserializeMethodResponse".
[ComVisible(false)]
public Object UnsafeDeserializeMethodResponse
(Stream serializationStream, HeaderHandler handler,
IMethodCallMessage methodCallMessage)
{
return DeserializeMethodResponse
(serializationStream, handler, methodCallMessage);
}
}; // class BinaryFormatter
#endif // CONFIG_SERIALIZATION
}; // namespace System.Runtime.Serialization.Formatters.Binary
| |
// 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.Globalization {
using System.Security.Permissions;
using System.Runtime.Serialization;
using System.Text;
using System;
using System.Diagnostics.Contracts;
//
// Property Default Description
// PositiveSign '+' Character used to indicate positive values.
// NegativeSign '-' Character used to indicate negative values.
// NumberDecimalSeparator '.' The character used as the decimal separator.
// NumberGroupSeparator ',' The character used to separate groups of
// digits to the left of the decimal point.
// NumberDecimalDigits 2 The default number of decimal places.
// NumberGroupSizes 3 The number of digits in each group to the
// left of the decimal point.
// NaNSymbol "NaN" The string used to represent NaN values.
// PositiveInfinitySymbol"Infinity" The string used to represent positive
// infinities.
// NegativeInfinitySymbol"-Infinity" The string used to represent negative
// infinities.
//
//
//
// Property Default Description
// CurrencyDecimalSeparator '.' The character used as the decimal
// separator.
// CurrencyGroupSeparator ',' The character used to separate groups
// of digits to the left of the decimal
// point.
// CurrencyDecimalDigits 2 The default number of decimal places.
// CurrencyGroupSizes 3 The number of digits in each group to
// the left of the decimal point.
// CurrencyPositivePattern 0 The format of positive values.
// CurrencyNegativePattern 0 The format of negative values.
// CurrencySymbol "$" String used as local monetary symbol.
//
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class NumberFormatInfo : ICloneable, IFormatProvider
{
// invariantInfo is constant irrespective of your current culture.
private static volatile NumberFormatInfo invariantInfo;
// READTHIS READTHIS READTHIS
// This class has an exact mapping onto a native structure defined in COMNumber.cpp
// DO NOT UPDATE THIS WITHOUT UPDATING THAT STRUCTURE. IF YOU ADD BOOL, ADD THEM AT THE END.
// ALSO MAKE SURE TO UPDATE mscorlib.h in the VM directory to check field offsets.
// READTHIS READTHIS READTHIS
internal int[] numberGroupSizes = new int[] {3};
internal int[] currencyGroupSizes = new int[] {3};
internal int[] percentGroupSizes = new int[] {3};
internal String positiveSign = "+";
internal String negativeSign = "-";
internal String numberDecimalSeparator = ".";
internal String numberGroupSeparator = ",";
internal String currencyGroupSeparator = ",";
internal String currencyDecimalSeparator = ".";
internal String currencySymbol = "\x00a4"; // U+00a4 is the symbol for International Monetary Fund.
// The alternative currency symbol used in Win9x ANSI codepage, that can not roundtrip between ANSI and Unicode.
// Currently, only ja-JP and ko-KR has non-null values (which is U+005c, backslash)
// NOTE: The only legal values for this string are null and "\x005c"
internal String ansiCurrencySymbol = null;
internal String nanSymbol = "NaN";
internal String positiveInfinitySymbol = "Infinity";
internal String negativeInfinitySymbol = "-Infinity";
internal String percentDecimalSeparator = ".";
internal String percentGroupSeparator = ",";
internal String percentSymbol = "%";
internal String perMilleSymbol = "\u2030";
[OptionalField(VersionAdded = 2)]
internal String[] nativeDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
// an index which points to a record in Culture Data Table.
// We shouldn't be persisting dataItem (since its useless & we weren't using it),
// but since COMNumber.cpp uses it and since serialization isn't implimented, its stuck for now.
[OptionalField(VersionAdded = 1)]
internal int m_dataItem = 0; // NEVER USED, DO NOT USE THIS! (Serialized in Everett)
internal int numberDecimalDigits = 2;
internal int currencyDecimalDigits = 2;
internal int currencyPositivePattern = 0;
internal int currencyNegativePattern = 0;
internal int numberNegativePattern = 1;
internal int percentPositivePattern = 0;
internal int percentNegativePattern = 0;
internal int percentDecimalDigits = 2;
#if !FEATURE_CORECLR
[OptionalField(VersionAdded = 2)]
internal int digitSubstitution = 1; // DigitShapes.None
#endif // !FEATURE_CORECLR
internal bool isReadOnly=false;
// We shouldn't be persisting m_useUserOverride (since its useless & we weren't using it),
// but since COMNumber.cpp uses it and since serialization isn't implimented, its stuck for now.
[OptionalField(VersionAdded = 1)]
internal bool m_useUserOverride=false; // NEVER USED, DO NOT USE THIS! (Serialized in Everett)
// Is this NumberFormatInfo for invariant culture?
[OptionalField(VersionAdded = 2)]
internal bool m_isInvariant=false;
public NumberFormatInfo() : this(null) {
}
#region Serialization
#if !FEATURE_CORECLR
// Check if NumberFormatInfo was not set up ambiguously for parsing as number and currency
// eg. if the NumberDecimalSeparator and the NumberGroupSeparator were the same. This check
// is solely for backwards compatibility / version tolerant serialization
[OptionalField(VersionAdded = 1)]
internal bool validForParseAsNumber = true; // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey/Everett)
[OptionalField(VersionAdded = 1)]
internal bool validForParseAsCurrency = true; // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey/Everett)
#endif // !FEATURE_CORECLR
[OnSerializing]
private void OnSerializing(StreamingContext ctx)
{
#if !FEATURE_CORECLR
// Update these legacy flags, so that 1.1/2.0 versions of the framework
// can still throw while parsing; even when using a de-serialized
// NumberFormatInfo from a 4.0+ version of the framework
if (numberDecimalSeparator != numberGroupSeparator) {
validForParseAsNumber = true;
} else {
validForParseAsNumber = false;
}
if ((numberDecimalSeparator != numberGroupSeparator) &&
(numberDecimalSeparator != currencyGroupSeparator) &&
(currencyDecimalSeparator != numberGroupSeparator) &&
(currencyDecimalSeparator != currencyGroupSeparator)) {
validForParseAsCurrency = true;
} else {
validForParseAsCurrency = false;
}
#endif // !FEATURE_CORECLR
}
[OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
}
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
}
#endregion Serialization
static private void VerifyDecimalSeparator(String decSep, String propertyName) {
if (decSep==null) {
throw new ArgumentNullException(propertyName,
Environment.GetResourceString("ArgumentNull_String"));
}
if (decSep.Length==0) {
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyDecString"));
}
Contract.EndContractBlock();
}
static private void VerifyGroupSeparator(String groupSep, String propertyName) {
if (groupSep==null) {
throw new ArgumentNullException(propertyName,
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
}
static private void VerifyNativeDigits(String [] nativeDig, String propertyName) {
if (nativeDig==null) {
throw new ArgumentNullException(propertyName,
Environment.GetResourceString("ArgumentNull_Array"));
}
if (nativeDig.Length != 10)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNativeDigitCount"), propertyName);
}
Contract.EndContractBlock();
for(int i = 0; i < nativeDig.Length; i++)
{
if (nativeDig[i] == null)
{
throw new ArgumentNullException(propertyName,
Environment.GetResourceString("ArgumentNull_ArrayValue"));
}
if (nativeDig[i].Length != 1) {
if(nativeDig[i].Length != 2) {
// Not 1 or 2 UTF-16 code points
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNativeDigitValue"), propertyName);
} else if(!char.IsSurrogatePair(nativeDig[i][0], nativeDig[i][1])) {
// 2 UTF-6 code points, but not a surrogate pair
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNativeDigitValue"), propertyName);
}
}
if (CharUnicodeInfo.GetDecimalDigitValue(nativeDig[i], 0) != i &&
CharUnicodeInfo.GetUnicodeCategory(nativeDig[i], 0) != UnicodeCategory.PrivateUse) {
// Not the appropriate digit according to the Unicode data properties
// (Digit 0 must be a 0, etc.).
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNativeDigitValue"), propertyName);
}
}
}
#if !FEATURE_CORECLR
static private void VerifyDigitSubstitution(DigitShapes digitSub, String propertyName) {
switch(digitSub)
{
case DigitShapes.Context:
case DigitShapes.None:
case DigitShapes.NativeNational:
// Success.
break;
default:
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDigitSubstitution"), propertyName);
}
}
#endif // !FEATURE_CORECLR
// We aren't persisting dataItem any more (since its useless & we weren't using it),
// Ditto with m_useUserOverride. Don't use them, we use a local copy of everything.
[System.Security.SecuritySafeCritical] // auto-generated
internal NumberFormatInfo(CultureData cultureData)
{
if (cultureData != null)
{
// We directly use fields here since these data is coming from data table or Win32, so we
// don't need to verify their values (except for invalid parsing situations).
cultureData.GetNFIValues(this);
if (cultureData.IsInvariantCulture)
{
// For invariant culture
this.m_isInvariant = true;
}
}
}
[Pure]
private void VerifyWritable() {
if (isReadOnly) {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
}
Contract.EndContractBlock();
}
// Returns a default NumberFormatInfo that will be universally
// supported and constant irrespective of the current culture.
// Used by FromString methods.
//
public static NumberFormatInfo InvariantInfo {
get {
if (invariantInfo == null) {
// Lazy create the invariant info. This cannot be done in a .cctor because exceptions can
// be thrown out of a .cctor stack that will need this.
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.m_isInvariant = true;
invariantInfo = ReadOnly(nfi);
}
return invariantInfo;
}
}
public static NumberFormatInfo GetInstance(IFormatProvider formatProvider) {
// Fast case for a regular CultureInfo
NumberFormatInfo info;
CultureInfo cultureProvider = formatProvider as CultureInfo;
if (cultureProvider != null && !cultureProvider.m_isInherited) {
info = cultureProvider.numInfo;
if (info != null) {
return info;
}
else {
return cultureProvider.NumberFormat;
}
}
// Fast case for an NFI;
info = formatProvider as NumberFormatInfo;
if (info != null) {
return info;
}
if (formatProvider != null) {
info = formatProvider.GetFormat(typeof(NumberFormatInfo)) as NumberFormatInfo;
if (info != null) {
return info;
}
}
return CurrentInfo;
}
public Object Clone() {
NumberFormatInfo n = (NumberFormatInfo)MemberwiseClone();
n.isReadOnly = false;
return n;
}
public int CurrencyDecimalDigits {
get { return currencyDecimalDigits; }
set {
if (value < 0 || value > 99) {
throw new ArgumentOutOfRangeException(
"CurrencyDecimalDigits",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
0,
99));
}
Contract.EndContractBlock();
VerifyWritable();
currencyDecimalDigits = value;
}
}
public String CurrencyDecimalSeparator {
get { return currencyDecimalSeparator; }
set {
VerifyWritable();
VerifyDecimalSeparator(value, "CurrencyDecimalSeparator");
currencyDecimalSeparator = value;
}
}
public bool IsReadOnly {
get {
return isReadOnly;
}
}
//
// Check the values of the groupSize array.
//
// Every element in the groupSize array should be between 1 and 9
// excpet the last element could be zero.
//
static internal void CheckGroupSize(String propName, int[] groupSize)
{
for (int i = 0; i < groupSize.Length; i++)
{
if (groupSize[i] < 1)
{
if (i == groupSize.Length - 1 && groupSize[i] == 0)
return;
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGroupSize"), propName);
}
else if (groupSize[i] > 9)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGroupSize"), propName);
}
}
}
public int[] CurrencyGroupSizes {
get {
return ((int[])currencyGroupSizes.Clone());
}
set {
if (value == null) {
throw new ArgumentNullException("CurrencyGroupSizes",
Environment.GetResourceString("ArgumentNull_Obj"));
}
Contract.EndContractBlock();
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
CheckGroupSize("CurrencyGroupSizes", inputSizes);
currencyGroupSizes = inputSizes;
}
}
public int[] NumberGroupSizes {
get {
return ((int[])numberGroupSizes.Clone());
}
set {
if (value == null) {
throw new ArgumentNullException("NumberGroupSizes",
Environment.GetResourceString("ArgumentNull_Obj"));
}
Contract.EndContractBlock();
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
CheckGroupSize("NumberGroupSizes", inputSizes);
numberGroupSizes = inputSizes;
}
}
public int[] PercentGroupSizes {
get {
return ((int[])percentGroupSizes.Clone());
}
set {
if (value == null) {
throw new ArgumentNullException("PercentGroupSizes",
Environment.GetResourceString("ArgumentNull_Obj"));
}
Contract.EndContractBlock();
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
CheckGroupSize("PercentGroupSizes", inputSizes);
percentGroupSizes = inputSizes;
}
}
public String CurrencyGroupSeparator {
get { return currencyGroupSeparator; }
set {
VerifyWritable();
VerifyGroupSeparator(value, "CurrencyGroupSeparator");
currencyGroupSeparator = value;
}
}
public String CurrencySymbol {
get { return currencySymbol; }
set {
if (value == null) {
throw new ArgumentNullException("CurrencySymbol",
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
VerifyWritable();
currencySymbol = value;
}
}
// Returns the current culture's NumberFormatInfo. Used by Parse methods.
//
public static NumberFormatInfo CurrentInfo {
get {
System.Globalization.CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentCulture;
if (!culture.m_isInherited) {
NumberFormatInfo info = culture.numInfo;
if (info != null) {
return info;
}
}
return ((NumberFormatInfo)culture.GetFormat(typeof(NumberFormatInfo)));
}
}
public String NaNSymbol {
get {
return nanSymbol;
}
set {
if (value == null) {
throw new ArgumentNullException("NaNSymbol",
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
VerifyWritable();
nanSymbol = value;
}
}
public int CurrencyNegativePattern {
get { return currencyNegativePattern; }
set {
if (value < 0 || value > 15) {
throw new ArgumentOutOfRangeException(
"CurrencyNegativePattern",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
0,
15));
}
Contract.EndContractBlock();
VerifyWritable();
currencyNegativePattern = value;
}
}
public int NumberNegativePattern {
get { return numberNegativePattern; }
set {
//
// NOTENOTE: the range of value should correspond to negNumberFormats[] in vm\COMNumber.cpp.
//
if (value < 0 || value > 4) {
throw new ArgumentOutOfRangeException(
"NumberNegativePattern",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
0,
4));
}
Contract.EndContractBlock();
VerifyWritable();
numberNegativePattern = value;
}
}
public int PercentPositivePattern {
get { return percentPositivePattern; }
set {
//
// NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp.
//
if (value < 0 || value > 3) {
throw new ArgumentOutOfRangeException(
"PercentPositivePattern",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
0,
3));
}
Contract.EndContractBlock();
VerifyWritable();
percentPositivePattern = value;
}
}
public int PercentNegativePattern {
get { return percentNegativePattern; }
set {
//
// NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp.
//
if (value < 0 || value > 11) {
throw new ArgumentOutOfRangeException(
"PercentNegativePattern",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
0,
11));
}
Contract.EndContractBlock();
VerifyWritable();
percentNegativePattern = value;
}
}
public String NegativeInfinitySymbol {
get {
return negativeInfinitySymbol;
}
set {
if (value == null) {
throw new ArgumentNullException("NegativeInfinitySymbol",
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
VerifyWritable();
negativeInfinitySymbol = value;
}
}
public String NegativeSign {
get { return negativeSign; }
set {
if (value == null) {
throw new ArgumentNullException("NegativeSign",
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
VerifyWritable();
negativeSign = value;
}
}
public int NumberDecimalDigits {
get { return numberDecimalDigits; }
set {
if (value < 0 || value > 99) {
throw new ArgumentOutOfRangeException(
"NumberDecimalDigits",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
0,
99));
}
Contract.EndContractBlock();
VerifyWritable();
numberDecimalDigits = value;
}
}
public String NumberDecimalSeparator {
get { return numberDecimalSeparator; }
set {
VerifyWritable();
VerifyDecimalSeparator(value, "NumberDecimalSeparator");
numberDecimalSeparator = value;
}
}
public String NumberGroupSeparator {
get { return numberGroupSeparator; }
set {
VerifyWritable();
VerifyGroupSeparator(value, "NumberGroupSeparator");
numberGroupSeparator = value;
}
}
public int CurrencyPositivePattern {
get { return currencyPositivePattern; }
set {
if (value < 0 || value > 3) {
throw new ArgumentOutOfRangeException(
"CurrencyPositivePattern",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
0,
3));
}
Contract.EndContractBlock();
VerifyWritable();
currencyPositivePattern = value;
}
}
public String PositiveInfinitySymbol {
get {
return positiveInfinitySymbol;
}
set {
if (value == null) {
throw new ArgumentNullException("PositiveInfinitySymbol",
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
VerifyWritable();
positiveInfinitySymbol = value;
}
}
public String PositiveSign {
get { return positiveSign; }
set {
if (value == null) {
throw new ArgumentNullException("PositiveSign",
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
VerifyWritable();
positiveSign = value;
}
}
public int PercentDecimalDigits {
get { return percentDecimalDigits; }
set {
if (value < 0 || value > 99) {
throw new ArgumentOutOfRangeException(
"PercentDecimalDigits",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
0,
99));
}
Contract.EndContractBlock();
VerifyWritable();
percentDecimalDigits = value;
}
}
public String PercentDecimalSeparator {
get { return percentDecimalSeparator; }
set {
VerifyWritable();
VerifyDecimalSeparator(value, "PercentDecimalSeparator");
percentDecimalSeparator = value;
}
}
public String PercentGroupSeparator {
get { return percentGroupSeparator; }
set {
VerifyWritable();
VerifyGroupSeparator(value, "PercentGroupSeparator");
percentGroupSeparator = value;
}
}
public String PercentSymbol {
get {
return percentSymbol;
}
set {
if (value == null) {
throw new ArgumentNullException("PercentSymbol",
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
VerifyWritable();
percentSymbol = value;
}
}
public String PerMilleSymbol {
get { return perMilleSymbol; }
set {
if (value == null) {
throw new ArgumentNullException("PerMilleSymbol",
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
VerifyWritable();
perMilleSymbol = value;
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public String[] NativeDigits
{
get { return (String[])nativeDigits.Clone(); }
set
{
VerifyWritable();
VerifyNativeDigits(value, "NativeDigits");
nativeDigits = value;
}
}
#if !FEATURE_CORECLR
[System.Runtime.InteropServices.ComVisible(false)]
public DigitShapes DigitSubstitution
{
get { return (DigitShapes)digitSubstitution; }
set
{
VerifyWritable();
VerifyDigitSubstitution(value, "DigitSubstitution");
digitSubstitution = (int)value;
}
}
#endif // !FEATURE_CORECLR
public Object GetFormat(Type formatType) {
return formatType == typeof(NumberFormatInfo)? this: null;
}
public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi) {
if (nfi == null) {
throw new ArgumentNullException("nfi");
}
Contract.EndContractBlock();
if (nfi.IsReadOnly) {
return (nfi);
}
NumberFormatInfo info = (NumberFormatInfo)(nfi.MemberwiseClone());
info.isReadOnly = true;
return info;
}
// private const NumberStyles InvalidNumberStyles = unchecked((NumberStyles) 0xFFFFFC00);
private const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite
| NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign
| NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint
| NumberStyles.AllowThousands | NumberStyles.AllowExponent
| NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier);
internal static void ValidateParseStyleInteger(NumberStyles style) {
// Check for undefined flags
if ((style & InvalidNumberStyles) != 0) {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNumberStyles"), "style");
}
Contract.EndContractBlock();
if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number
if ((style & ~NumberStyles.HexNumber) != 0) {
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidHexStyle"));
}
}
}
internal static void ValidateParseStyleFloatingPoint(NumberStyles style) {
// Check for undefined flags
if ((style & InvalidNumberStyles) != 0) {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNumberStyles"), "style");
}
Contract.EndContractBlock();
if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number
throw new ArgumentException(Environment.GetResourceString("Arg_HexStyleNotSupported"));
}
}
} // NumberFormatInfo
}
| |
using Prism.Windows.Interfaces;
using System;
using System.Collections.Generic;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace Prism.Windows.Mvvm
{
/// <summary>
/// Abstracts the Windows.UI.Xaml.Controls.Frame object for use by apps that derive from the PrismApplication class.
/// </summary>
public class FrameFacadeAdapter : IFrameFacade
{
private readonly Frame _frame;
private readonly List<EventHandler<MvvmNavigatedEventArgs>> _navigatedEventHandlers = new List<EventHandler<MvvmNavigatedEventArgs>>();
private readonly List<EventHandler> _navigatingEventHandlers = new List<EventHandler>();
/// <summary>
/// Initializes a new instance of the <see cref="FrameFacadeAdapter"/> class.
/// </summary>
/// <param name="frame">The Frame that will be wrapped.</param>
public FrameFacadeAdapter(Frame frame)
{
_frame = frame;
}
/// <summary>
/// Gets or sets the content of a ContentControl.
/// </summary>
///
/// <returns>
/// An object that contains the control's content. The default is null.
/// </returns>
public object Content
{
get { return _frame.Content; }
set { _frame.Content = value; }
}
/// <summary>
/// Navigates to the most recent item in back navigation history, if a Frame manages its own navigation history.
/// </summary>
public void GoBack()
{
_frame.GoBack();
}
/// <returns>
/// The string-form serialized navigation history. See Remarks.
/// </returns>
public string GetNavigationState()
{
var navigationState = _frame.GetNavigationState();
return navigationState;
}
/// <summary>
/// Reads and restores the navigation history of a Frame from a provided serialization string.
/// </summary>
/// <param name="navigationState">The serialization string that supplies the restore point for navigation history.</param>
public void SetNavigationState(string navigationState)
{
_frame.SetNavigationState(navigationState);
}
/// <summary>
/// Navigates to a page of the requested type.
/// </summary>
/// <param name="sourcePageType">The type of the page that will be navigated to.</param>
/// <param name="parameter">The page's navigation parameter.</param>
///
/// <returns>True if navigation was successful; false otherwise.</returns>
public bool Navigate(Type sourcePageType, object parameter)
{
try
{
return _frame.Navigate(sourcePageType, parameter);
}
catch
{
return false;
}
}
/// <summary>
/// Gets the number of entries in the navigation back stack.
/// </summary>
///
/// <returns>
/// The number of entries in the navigation back stack.
/// </returns>
public int BackStackDepth
{
get { return _frame.BackStackDepth; }
}
/// <summary>
/// Gets a value that indicates whether there is at least one entry in back navigation history.
/// </summary>
///
/// <returns>
/// True if there is at least one entry in back navigation history; false if there are no entries in back navigation history or the Frame does not own its own navigation history.
/// </returns>
public bool CanGoBack
{
get { return _frame.CanGoBack; }
}
/// <summary>
/// Occurs when the content that is being navigated to has been found and is available from the Content property, although it may not have completed loading.
/// </summary>
public event EventHandler<MvvmNavigatedEventArgs> Navigated
{
add
{
if (_navigatedEventHandlers.Contains(value)) return;
_navigatedEventHandlers.Add(value);
if (_navigatedEventHandlers.Count == 1)
{
_frame.Navigated += FacadeNavigatedEventHandler;
}
}
remove
{
if (!_navigatedEventHandlers.Contains(value)) return;
_navigatedEventHandlers.Remove(value);
if (_navigatedEventHandlers.Count == 0)
{
_frame.Navigated -= FacadeNavigatedEventHandler;
}
}
}
/// <summary>
/// Occurs when a new navigation is requested.
/// </summary>
public event EventHandler Navigating
{
add
{
if (_navigatingEventHandlers.Contains(value)) return;
_navigatingEventHandlers.Add(value);
if (_navigatingEventHandlers.Count == 1)
{
_frame.Navigating += FacadeNavigatingCancelEventHandler;
}
}
remove
{
if (!_navigatingEventHandlers.Contains(value)) return;
_navigatingEventHandlers.Remove(value);
if (_navigatingEventHandlers.Count == 0)
{
_frame.Navigating -= FacadeNavigatingCancelEventHandler;
}
}
}
/// <summary>
/// Returns the current effective value of a dependency property from a DependencyObject.
/// </summary>
///
/// <returns>
/// Returns the current effective value.
/// </returns>
/// <param name="dependencyProperty">The DependencyProperty identifier of the property for which to retrieve the value.</param>
public object GetValue(DependencyProperty dependencyProperty)
{
return _frame.GetValue(dependencyProperty);
}
/// <summary>
/// Sets the local value of a dependency property on a DependencyObject.
/// </summary>
/// <param name="dependencyProperty">The identifier of the dependency property to set.</param><param name="value">The new local value.</param>
public void SetValue(DependencyProperty dependencyProperty, object value)
{
_frame.SetValue(dependencyProperty, value);
}
/// <summary>
/// Clears the local value of a dependency property.
/// </summary>
/// <param name="dependencyProperty">The DependencyProperty identifier of the property for which to clear the value.</param>
public void ClearValue(DependencyProperty dependencyProperty)
{
_frame.ClearValue(dependencyProperty);
}
private void FacadeNavigatedEventHandler(object sender, NavigationEventArgs e)
{
foreach (var handler in _navigatedEventHandlers)
{
var eventArgs = new MvvmNavigatedEventArgs()
{
NavigationMode = e.NavigationMode,
Parameter = e.Parameter
};
handler(this, eventArgs);
}
}
private void FacadeNavigatingCancelEventHandler(object sender, NavigatingCancelEventArgs e)
{
foreach (var handler in _navigatingEventHandlers)
{
handler(this, new EventArgs());
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="AspProxy.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.Metadata.Edm
{
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Security;
internal class AspProxy
{
private const string BUILD_MANAGER_TYPE_NAME = @"System.Web.Compilation.BuildManager";
private Assembly _webAssembly;
private bool _triedLoadingWebAssembly = false;
/// <summary>
/// Determine whether we are inside an ASP.NET application.
/// </summary>
/// <param name="webAssembly">The System.Web assembly</param>
/// <returns>true if we are running inside an ASP.NET application</returns>
internal bool IsAspNetEnvironment()
{
if (!TryInitializeWebAssembly())
{
return false;
}
try
{
string result = PrivateMapWebPath(EdmConstants.WebHomeSymbol);
return result != null;
}
catch (SecurityException)
{
// When running under partial trust but not running as an ASP.NET site the System.Web assembly
// may not be not treated as conditionally APTCA and hence throws a security exception. However,
// since this happens when not running as an ASP.NET site we can just return false because we're
// not in an ASP.NET environment.
return false;
}
catch (Exception e)
{
if (EntityUtil.IsCatchableExceptionType(e))
{
return false;
}
throw;
}
}
private bool TryInitializeWebAssembly()
{
// We cannot introduce a hard dependency on the System.Web assembly, so we load
// it via reflection.
//
if (_webAssembly != null)
{
return true;
}
else if (_triedLoadingWebAssembly)
{
return false;
}
Debug.Assert(_triedLoadingWebAssembly == false);
Debug.Assert(_webAssembly == null);
_triedLoadingWebAssembly = true;
try
{
_webAssembly = Assembly.Load(AssemblyRef.SystemWeb);
return _webAssembly != null;
}
catch (Exception e)
{
if (!EntityUtil.IsCatchableExceptionType(e))
{
throw; // StackOverflow, OutOfMemory, ...
}
// It is possible that we are operating in an environment where
// System.Web is simply not available (for instance, inside SQL
// Server). Instead of throwing or rethrowing, we simply fail
// gracefully
}
return false;
}
void InitializeWebAssembly()
{
if (!TryInitializeWebAssembly())
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext);
}
}
/// <summary>
/// This method accepts a string parameter that represents a path in a Web (specifically,
/// an ASP.NET) application -- one that starts with a '~' -- and resolves it to a
/// canonical file path.
/// </summary>
/// <remarks>
/// The implementation assumes that you cannot have file names that begin with the '~'
/// character. (This is a pretty reasonable assumption.) Additionally, the method does not
/// test for the existence of a directory or file resource after resolving the path.
///
internal string MapWebPath(string path)
{
Debug.Assert(path != null, "path == null");
path = PrivateMapWebPath(path);
if (path == null)
{
string errMsg = Strings.InvalidUseOfWebPath(EdmConstants.WebHomeSymbol);
throw EntityUtil.InvalidOperation(errMsg);
}
return path;
}
private string PrivateMapWebPath(string path)
{
Debug.Assert(!string.IsNullOrEmpty(path));
Debug.Assert(path.StartsWith(EdmConstants.WebHomeSymbol, StringComparison.Ordinal));
InitializeWebAssembly();
// Each managed application domain contains a static instance of the HostingEnvironment class, which
// provides access to application-management functions and application services. We'll try to invoke
// the static method MapPath() on that object.
//
try
{
Type hostingEnvType = _webAssembly.GetType("System.Web.Hosting.HostingEnvironment", true);
MethodInfo miMapPath = hostingEnvType.GetMethod("MapPath");
Debug.Assert(miMapPath != null, "Unpexpected missing member in type System.Web.Hosting.HostingEnvironment");
// Note:
// 1. If path is null, then the MapPath() method returns the full physical path to the directory
// containing the current application.
// 2. Any attempt to navigate out of the application directory (using "../..") will generate
// a (wrapped) System.Web.HttpException under ASP.NET (which we catch and re-throw).
//
return (string)miMapPath.Invoke(null, new object[] { path });
}
catch (TargetException e)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext, e);
}
catch (ArgumentException e)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext, e);
}
catch (TargetInvocationException e)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext, e);
}
catch (TargetParameterCountException e)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext, e);
}
catch (MethodAccessException e)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext, e);
}
catch (MemberAccessException e)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext, e);
}
catch (TypeLoadException e)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext, e);
}
}
internal bool HasBuildManagerType()
{
Type buildManager;
return TryGetBuildManagerType(out buildManager);
}
private bool TryGetBuildManagerType(out Type buildManager)
{
InitializeWebAssembly();
buildManager = _webAssembly.GetType(BUILD_MANAGER_TYPE_NAME, false);
return buildManager != null;
}
internal IEnumerable<Assembly> GetBuildManagerReferencedAssemblies()
{
// We are interested in invoking the following method on the class
// System.Web.Compilation.BuildManager, which is available only in Orcas:
//
// public static ICollection GetReferencedAssemblies();
//
Type buildManager;
if (!TryGetBuildManagerType(out buildManager))
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToFindReflectedType(BUILD_MANAGER_TYPE_NAME, AssemblyRef.SystemWeb));
}
MethodInfo getRefAssembliesMethod = buildManager.GetMethod(
@"GetReferencedAssemblies",
BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public
);
if (getRefAssembliesMethod == null)
{
// eat this problem
return new List<Assembly>();
}
ICollection referencedAssemblies = null;
try
{
referencedAssemblies = (ICollection)getRefAssembliesMethod.Invoke(null, null);
if (referencedAssemblies == null)
{
return new List<Assembly>();
}
return referencedAssemblies.Cast<Assembly>();
}
catch (TargetException e)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext, e);
}
catch (TargetInvocationException e)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext, e);
}
catch (MethodAccessException e)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext, e);
}
}
}
}
| |
using System.ServiceModel;
namespace OpenRiaServices.DomainServices.Tools.TextTemplate
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using OpenRiaServices;
using OpenRiaServices.DomainServices;
using OpenRiaServices.DomainServices.Hosting;
using OpenRiaServices.DomainServices.Server;
using OpenRiaServices.DomainServices.Tools.SharedTypes;
/// <summary>
/// Proxy generator for DomainServices.
/// </summary>
public abstract partial class DomainContextGenerator
{
private const string QuerySuffix = "Query";
internal const string DefaultActionSchema = "http://tempuri.org/{0}/{1}";
internal const string DefaultReplyActionSchema = "http://tempuri.org/{0}/{1}Response";
internal const string DefaultFaultActionSchema = "http://tempuri.org/{0}/{1}{2}";
internal string DomainContextTypeName { get; set; }
internal string ContractInterfaceName { get; set; }
internal AttributeCollection Attributes { get; set; }
private List<Type> _entitySets;
private List<DomainOperationEntry> _queryMethods;
private List<DomainOperationEntry> _domainOperations;
/// <summary>
/// Gets the DomainServiceDescription for the DomainService to be generated.
/// </summary>
protected DomainServiceDescription DomainServiceDescription { get; private set; }
/// <summary>
/// Gets the ClientCodeGenerator object.
/// </summary>
protected ClientCodeGenerator ClientCodeGenerator { get; private set; }
/// <summary>
/// Geterates the DomainContext class.
/// </summary>
/// <param name="domainServiceDescription">DomainServcieDescription for the domain service for which the proxy is to be generated.</param>
/// <param name="clientCodeGenerator">ClientCodeGenerator object for this instance.</param>
/// <returns>The generated DomainContext class code.</returns>
public string Generate(DomainServiceDescription domainServiceDescription, ClientCodeGenerator clientCodeGenerator)
{
this.DomainServiceDescription = domainServiceDescription;
this.ClientCodeGenerator = clientCodeGenerator;
return this.GenerateDomainContextClass();
}
/// <summary>
/// Generates the DomainContext code in a specific language.
/// </summary>
/// <returns>The generated code.</returns>
protected abstract string GenerateDomainContextClass();
internal virtual void Initialize()
{
string domainServiceName = this.DomainServiceDescription.DomainServiceType.Name;
this.ContractInterfaceName = "I" + domainServiceName + "Contract";
this.Attributes = this.DomainServiceDescription.Attributes;
this.InitDomainContextData();
}
internal IEnumerable<DomainOperationEntry> QueryMethods
{
get
{
if (this._queryMethods == null)
{
this._queryMethods = new List<DomainOperationEntry>();
}
return this._queryMethods;
}
}
internal IEnumerable<DomainOperationEntry> DomainOperations
{
get
{
if (this._domainOperations == null)
{
this._domainOperations = new List<DomainOperationEntry>();
}
return this._domainOperations;
}
}
internal IEnumerable<Type> EntitySets
{
get
{
if (this._entitySets == null)
{
this._entitySets = new List<Type>();
}
return this._entitySets;
}
}
private void InitDomainContextData()
{
HashSet<Type> visitedEntityTypes = new HashSet<Type>();
this._queryMethods = new List<DomainOperationEntry>();
this._domainOperations = new List<DomainOperationEntry>();
this._entitySets = new List<Type>();
foreach (DomainOperationEntry domainOperationEntry in this.DomainServiceDescription.DomainOperationEntries.Where(p => p.Operation == DomainOperation.Query).OrderBy(m => m.Name))
{
if (!this.CanGenerateDomainOperationEntry(domainOperationEntry))
{
continue;
}
this._queryMethods.Add(domainOperationEntry);
Type entityType = TypeUtility.GetElementType(domainOperationEntry.ReturnType);
if (!visitedEntityTypes.Contains(entityType))
{
visitedEntityTypes.Add(entityType);
bool isComposedType = this.DomainServiceDescription
.GetParentAssociations(entityType).Any(p => p.ComponentType != entityType);
Type rootEntityType = this.DomainServiceDescription.GetRootEntityType(entityType);
if (!isComposedType && rootEntityType == entityType)
{
this._entitySets.Add(entityType);
}
}
}
foreach (Type entityType in this.DomainServiceDescription.EntityTypes.OrderBy(e => e.Name))
{
foreach (DomainOperationEntry entry in this.DomainServiceDescription.GetCustomMethods(entityType))
{
if (this.CanGenerateDomainOperationEntry(entry))
{
this._domainOperations.Add(entry);
}
}
}
}
internal static string GetDomainContextTypeName(DomainServiceDescription domainServiceDescription)
{
string domainContextTypeName = domainServiceDescription.DomainServiceType.Name;
if (domainContextTypeName.EndsWith("Service", StringComparison.Ordinal))
{
domainContextTypeName = domainContextTypeName.Substring(0, domainContextTypeName.Length - 7 /* "Service".Length */) + "Context";
}
return domainContextTypeName;
}
internal bool GetRequiresSecureEndpoint()
{
EnableClientAccessAttribute enableClientAccessAttribute = this.Attributes.OfType<EnableClientAccessAttribute>().Single();
return enableClientAccessAttribute.RequiresSecureEndpoint;
}
internal bool RegisterEnumTypeIfNecessary(Type type, DomainOperationEntry domainOperationEntry)
{
Type enumType = TypeUtility.GetNonNullableType(type);
if (enumType.IsEnum)
{
string errorMessage = null;
if (!this.ClientCodeGenerator.CanExposeEnumType(enumType, out errorMessage))
{
this.ClientCodeGenerator.CodeGenerationHost.LogError(string.Format(CultureInfo.CurrentCulture,
Resource.ClientCodeGen_Domain_Op_Enum_Error,
domainOperationEntry.Name,
this.DomainContextTypeName,
enumType.FullName,
errorMessage));
return false;
}
else
{
// Register use of this enum type, which could cause deferred generation
this.ClientCodeGenerator.AddEnumTypeToGenerate(enumType);
}
}
return true;
}
internal List<Attribute> GetContractServiceKnownTypes(DomainOperationEntry operation, HashSet<Type> registeredTypes)
{
List<Attribute> knownTypeAttributes = new List<Attribute>();
foreach (DomainOperationParameter parameter in operation.Parameters)
{
Type t = CodeGenUtilities.TranslateType(parameter.ParameterType);
// All Nullable<T> types are unwrapped to the underlying non-nullable, because
// that is they type we need to represent, not typeof(Nullable<T>)
t = TypeUtility.GetNonNullableType(t);
if (TypeUtility.IsPredefinedListType(t) || TypeUtility.IsComplexTypeCollection(t))
{
Type elementType = TypeUtility.GetElementType(t);
if (elementType != null)
{
t = elementType.MakeArrayType();
}
}
// Check if the type is a simple type or already registered
if (registeredTypes.Contains(t) || !this.TypeRequiresRegistration(t))
{
continue;
}
// Record the type to prevent redundant [ServiceKnownType]'s.
// This loop executes within a larger loop over multiple
// DomainOperationEntries that may have already processed it.
registeredTypes.Add(t);
// If we determine we need to generate this enum type on the client,
// then we need to register that intent and conjure a virtual type
// here in our list of registered types to account for the fact it
// could get a different root namespace on the client.
if (t.IsEnum && this.ClientCodeGenerator.NeedToGenerateEnumType(t))
{
// Request deferred generation of the enum
this.ClientCodeGenerator.AddEnumTypeToGenerate(t);
// Compose a virtual type that will reflect the correct namespace
// on the client when the [ServiceKnownType] is created.
t = new VirtualType(t.Name, CodeGenUtilities.TranslateNamespace(t), t.Assembly, t.BaseType);
}
knownTypeAttributes.Add(new ServiceKnownTypeAttribute(t));
}
return knownTypeAttributes;
}
private bool TypeRequiresRegistration(Type type)
{
if (type.IsPrimitive || type == typeof(string))
{
return false;
}
if (this.DomainServiceDescription.EntityTypes.Contains(type))
{
return false;
}
return true;
}
internal static bool OperationHasSideEffects(DomainOperationEntry operation)
{
if (operation.Operation == DomainOperation.Query)
{
return ((QueryAttribute)operation.OperationAttribute).HasSideEffects;
}
else if (operation.Operation == DomainOperation.Invoke)
{
return ((InvokeAttribute)operation.OperationAttribute).HasSideEffects;
}
return false;
}
internal bool CanGenerateDomainOperationEntry(DomainOperationEntry domainOperationEntry)
{
string methodName = (domainOperationEntry.Operation == DomainOperation.Query) ? domainOperationEntry.Name : domainOperationEntry.Name + QuerySuffix;
// Check each parameter type to see if is enum
DomainOperationParameter[] paramInfos = domainOperationEntry.Parameters.ToArray();
for (int i = 0; i < paramInfos.Length; i++)
{
DomainOperationParameter paramInfo = paramInfos[i];
// If this is an enum type, we need to ensure it is either shared or
// can be generated. Failure logs an error. The test for legality also causes
// the enum to be generated if required.
Type enumType = TypeUtility.GetNonNullableType(paramInfo.ParameterType);
if (enumType.IsEnum)
{
string errorMessage = null;
if (!this.ClientCodeGenerator.CanExposeEnumType(enumType, out errorMessage))
{
this.ClientCodeGenerator.CodeGenerationHost.LogError(string.Format(CultureInfo.CurrentCulture,
Resource.ClientCodeGen_Domain_Op_Enum_Error,
domainOperationEntry.Name,
this.DomainContextTypeName,
enumType.FullName,
errorMessage));
return false;
}
else
{
// Register use of this enum type, which could cause deferred generation
this.ClientCodeGenerator.AddEnumTypeToGenerate(enumType);
}
}
}
return true;
}
}
}
| |
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 Northwind{
/// <summary>
/// Strongly-typed collection for the OrderDetailsExtended class.
/// </summary>
[Serializable]
public partial class OrderDetailsExtendedCollection : ReadOnlyList<OrderDetailsExtended, OrderDetailsExtendedCollection>
{
public OrderDetailsExtendedCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the Order Details Extended view.
/// </summary>
[Serializable]
public partial class OrderDetailsExtended : ReadOnlyRecord<OrderDetailsExtended>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
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("Order Details Extended", TableType.View, DataService.GetInstance("Northwind"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarOrderID = new TableSchema.TableColumn(schema);
colvarOrderID.ColumnName = "OrderID";
colvarOrderID.DataType = DbType.Int32;
colvarOrderID.MaxLength = 0;
colvarOrderID.AutoIncrement = false;
colvarOrderID.IsNullable = false;
colvarOrderID.IsPrimaryKey = false;
colvarOrderID.IsForeignKey = false;
colvarOrderID.IsReadOnly = false;
schema.Columns.Add(colvarOrderID);
TableSchema.TableColumn colvarProductID = new TableSchema.TableColumn(schema);
colvarProductID.ColumnName = "ProductID";
colvarProductID.DataType = DbType.Int32;
colvarProductID.MaxLength = 0;
colvarProductID.AutoIncrement = false;
colvarProductID.IsNullable = false;
colvarProductID.IsPrimaryKey = false;
colvarProductID.IsForeignKey = false;
colvarProductID.IsReadOnly = false;
schema.Columns.Add(colvarProductID);
TableSchema.TableColumn colvarProductName = new TableSchema.TableColumn(schema);
colvarProductName.ColumnName = "ProductName";
colvarProductName.DataType = DbType.String;
colvarProductName.MaxLength = 40;
colvarProductName.AutoIncrement = false;
colvarProductName.IsNullable = false;
colvarProductName.IsPrimaryKey = false;
colvarProductName.IsForeignKey = false;
colvarProductName.IsReadOnly = false;
schema.Columns.Add(colvarProductName);
TableSchema.TableColumn colvarUnitPrice = new TableSchema.TableColumn(schema);
colvarUnitPrice.ColumnName = "UnitPrice";
colvarUnitPrice.DataType = DbType.Currency;
colvarUnitPrice.MaxLength = 0;
colvarUnitPrice.AutoIncrement = false;
colvarUnitPrice.IsNullable = false;
colvarUnitPrice.IsPrimaryKey = false;
colvarUnitPrice.IsForeignKey = false;
colvarUnitPrice.IsReadOnly = false;
schema.Columns.Add(colvarUnitPrice);
TableSchema.TableColumn colvarQuantity = new TableSchema.TableColumn(schema);
colvarQuantity.ColumnName = "Quantity";
colvarQuantity.DataType = DbType.Int16;
colvarQuantity.MaxLength = 0;
colvarQuantity.AutoIncrement = false;
colvarQuantity.IsNullable = false;
colvarQuantity.IsPrimaryKey = false;
colvarQuantity.IsForeignKey = false;
colvarQuantity.IsReadOnly = false;
schema.Columns.Add(colvarQuantity);
TableSchema.TableColumn colvarDiscount = new TableSchema.TableColumn(schema);
colvarDiscount.ColumnName = "Discount";
colvarDiscount.DataType = DbType.Single;
colvarDiscount.MaxLength = 0;
colvarDiscount.AutoIncrement = false;
colvarDiscount.IsNullable = false;
colvarDiscount.IsPrimaryKey = false;
colvarDiscount.IsForeignKey = false;
colvarDiscount.IsReadOnly = false;
schema.Columns.Add(colvarDiscount);
TableSchema.TableColumn colvarExtendedPrice = new TableSchema.TableColumn(schema);
colvarExtendedPrice.ColumnName = "ExtendedPrice";
colvarExtendedPrice.DataType = DbType.Currency;
colvarExtendedPrice.MaxLength = 0;
colvarExtendedPrice.AutoIncrement = false;
colvarExtendedPrice.IsNullable = true;
colvarExtendedPrice.IsPrimaryKey = false;
colvarExtendedPrice.IsForeignKey = false;
colvarExtendedPrice.IsReadOnly = false;
schema.Columns.Add(colvarExtendedPrice);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["Northwind"].AddSchema("Order Details Extended",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public OrderDetailsExtended()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public OrderDetailsExtended(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public OrderDetailsExtended(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public OrderDetailsExtended(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("OrderID")]
[Bindable(true)]
public int OrderID
{
get
{
return GetColumnValue<int>("OrderID");
}
set
{
SetColumnValue("OrderID", value);
}
}
[XmlAttribute("ProductID")]
[Bindable(true)]
public int ProductID
{
get
{
return GetColumnValue<int>("ProductID");
}
set
{
SetColumnValue("ProductID", value);
}
}
[XmlAttribute("ProductName")]
[Bindable(true)]
public string ProductName
{
get
{
return GetColumnValue<string>("ProductName");
}
set
{
SetColumnValue("ProductName", value);
}
}
[XmlAttribute("UnitPrice")]
[Bindable(true)]
public decimal UnitPrice
{
get
{
return GetColumnValue<decimal>("UnitPrice");
}
set
{
SetColumnValue("UnitPrice", value);
}
}
[XmlAttribute("Quantity")]
[Bindable(true)]
public short Quantity
{
get
{
return GetColumnValue<short>("Quantity");
}
set
{
SetColumnValue("Quantity", value);
}
}
[XmlAttribute("Discount")]
[Bindable(true)]
public float Discount
{
get
{
return GetColumnValue<float>("Discount");
}
set
{
SetColumnValue("Discount", value);
}
}
[XmlAttribute("ExtendedPrice")]
[Bindable(true)]
public decimal? ExtendedPrice
{
get
{
return GetColumnValue<decimal?>("ExtendedPrice");
}
set
{
SetColumnValue("ExtendedPrice", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string OrderID = @"OrderID";
public static string ProductID = @"ProductID";
public static string ProductName = @"ProductName";
public static string UnitPrice = @"UnitPrice";
public static string Quantity = @"Quantity";
public static string Discount = @"Discount";
public static string ExtendedPrice = @"ExtendedPrice";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using System;
using UnityEngine.Events;
using System.Text.RegularExpressions;
namespace Xsolla
{
public abstract class ScreenBaseConroller<T> : MonoBehaviour
{
public delegate void RecieveError(XsollaError xsollaError);
public event Action<XsollaError> ErrorHandler;
protected Dictionary<string, GameObject> screenObjects;
private const string PrefabStatus = "Prefabs/SimpleView/Status";
private const string PrefabStatusWaiting = "Prefabs/SimpleView/StatusWaiting";
private const string PrefabTitle = "Prefabs/SimpleView/TitleNoImg";
private const string PrefabtwoTextPlate = "Prefabs/SimpleView/_ScreenCheckout/TwoTextGrayPlate";
private const string PrefabError = "Prefabs/SimpleView/Error";
private const string PrefabListView = "Prefabs/SimpleView/ListView";
private const string PrefabInstructions = "Prefabs/SimpleView/Instructions";
private const string PrefabButton = "Prefabs/SimpleView/Button";
private const string PrefabClose = "Prefabs/SimpleView/Close";
private const string PrefabEmpty = "Prefabs/SimpleView/Empty";
public ScreenBaseConroller(){
screenObjects = new Dictionary<string, GameObject> ();
}
public abstract void InitScreen (XsollaTranslations translations, T model);
private void DrawScreen (XsollaTranslations translations, T model){
}
protected void InitView()
{
foreach (KeyValuePair<string, GameObject> go in screenObjects)
{
screenObjects[go.Key] = Instantiate(go.Value) as GameObject;
}
}
protected GameObject GetObjectByTag(string tag)
{
if (screenObjects.ContainsKey (tag))
return screenObjects [tag];
return null;
}
protected GameObject GetOkStatus(string titleText){
if (titleText != null)
{
GameObject statusObj = GetObject(PrefabStatus);
SetText (statusObj, titleText);
return statusObj;
}
return null;
}
protected GameObject GetWaitingStatus(string titleText){
if (titleText != null)
{
GameObject statusObj = GetObject(PrefabStatusWaiting);
SetText (statusObj, titleText);
return statusObj;
}
return null;
}
protected GameObject GetTitle(string titleText){
if (titleText != null)
{
GameObject titleObj = GetObject(PrefabTitle);
SetText (titleObj, titleText);
return titleObj;
}
return null;
}
protected GameObject GetTwoTextPlate(string titleText, string valueText){
if (titleText != null)
{
GameObject textPlate = GetObject(PrefabtwoTextPlate);
Text[] texts = textPlate.GetComponentsInChildren<Text>();
texts[0].text = titleText;
texts[1].text = valueText;
return textPlate;
}
return null;
}
protected GameObject GetErrorByString(string error)
{
bool isError = error != null;
if (isError)
{
GameObject errorObj = GetObject(PrefabError);
SetText (errorObj, error);
return errorObj;
}
return null;
}
protected GameObject GetError(XsollaError error)
{
bool isError = error != null;
if (isError)
{
GameObject errorObj = GetObject(PrefabError);
SetText (errorObj, error.GetMessage());
return errorObj;
}
return null;
}
protected GameObject GetList(IBaseAdapter adapter)
{
if (adapter != null)
{
GameObject listViewObj = GetObject(PrefabListView);
ListView listView = listViewObj.GetComponent<ListView> ();
listView.SetAdapter(adapter);
listView.DrawList ();
return listViewObj;
}
return null;
}
protected GameObject GetTextPlate(string s)
{
if (s != null)
{
int start = s.IndexOf("<a");
int end = s.IndexOf("a>");
string taggedText = s.Substring(start, end - start + 2);
string[] linkedText = taggedText.Split(new Char [] {'<', '>'});
string newString = "<color=#a38dd8>" + linkedText[2] + "</color>";
s = s.Replace(taggedText, newString);
GameObject textPlate = GetObject(PrefabInstructions);
SetText(textPlate, s);
return textPlate;
}
return null;
}
protected GameObject GetButton(string text, UnityAction onClick)
{
if (text != null)
{
GameObject buttonObj = GetObject(PrefabButton);
SetText (buttonObj, text);
buttonObj.GetComponentInChildren<Button> ().onClick.AddListener (onClick);
return buttonObj;
}
return null;
}
protected GameObject GetHelp(XsollaTranslations translations)
{
if (translations != null)
{
GameObject helpObj = GetObject("Prefabs/SimpleView/Help");
Text[] texsts = helpObj.GetComponentsInChildren<Text>();
texsts[0].text = translations.Get(XsollaTranslations.SUPPORT_PHONE);
texsts[1].text = translations.Get(XsollaTranslations.SUPPORT_NEED_HELP);
texsts[2].text = "support@xsolla.com";
texsts[3].text = translations.Get(XsollaTranslations.SUPPORT_CUSTOMER_SUPPORT);
return helpObj;
}
return null;
}
protected GameObject GetClose(UnityAction onClick)
{
if (onClick != null)
{
GameObject buttonObj = GetObject(PrefabClose);
buttonObj.GetComponentInChildren<Button> ().onClick.AddListener (onClick);
return buttonObj;
}
return null;
}
protected GameObject GetEmpty()
{
return GetObject(PrefabEmpty);
}
protected void OnErrorRecived(XsollaError error)
{
if(ErrorHandler != null)
ErrorHandler(error);
}
public GameObject GetObject(String pathToPrefab){
return Instantiate (Resources.Load (pathToPrefab)) as GameObject;
}
public string GetFirstAHrefText(string s){
int start = s.IndexOf("<a");
int end = s.IndexOf("a>");
string taggedText = s.Substring(start, end - start + 2);
string[] text = taggedText.Split(new Char [] {'<', '>'});
return text [2];
}
protected void SetImage(GameObject go, string imgUrl)
{
Image[] i2 = go.GetComponentsInChildren<Image>();
GetComponent<ImageLoader>().LoadImage(i2[1], imgUrl);
}
protected void SetText(GameObject go, string s)
{
go.GetComponentInChildren<Text>().text = s;
}
protected void SetText(Text text, string s)
{
text.text = s;
}
protected void ResizeToParent()
{
RectTransform containerRectTransform = GetComponent<RectTransform>();
RectTransform parentRectTransform = transform.parent.gameObject.GetComponent<RectTransform> ();
float parentHeight = parentRectTransform.rect.height;
float parentWidth = parentRectTransform.rect.width;
float parentRatio = parentWidth/parentHeight;// > 1 horizontal
float width = containerRectTransform.rect.width;
if (parentRatio < 1) {
containerRectTransform.offsetMin = new Vector2 (-parentWidth/2, -parentHeight/2);
containerRectTransform.offsetMax = new Vector2 (parentWidth/2, parentHeight/2);
} else {
float newWidth = parentWidth/3;
if(width < newWidth){
containerRectTransform.offsetMin = new Vector2 (-newWidth/2, -parentHeight/2);
containerRectTransform.offsetMax = new Vector2 (newWidth/2, parentHeight/2);
}
}
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using Microsoft.Win32;
namespace OpenLiveWriter.CoreServices
{
/// <summary>
/// Summary description for mimeHelper.
///
/// Mime-types was originally defined in RFC 1341. After that a series of
/// improvment has been made. Some of this can be found in RFC 1521
/// and RFC 1522.
/// </summary>
public class MimeHelper
{
/// <summary>
/// This takes a file extension and returns the mime content type for
/// the file
/// </summary>
/// <param name="fileExtension">the file extension (i.e. '.gif')</param>
/// <returns>the content type (i.e. 'image/gif'). returns null if no contentType
/// is found for the file extension.</returns>
public static string GetContentType(string fileExtension)
{
return GetContentType(fileExtension, null);
}
/// <summary>
/// This sets the content type value in the registry for a given file
/// extension
/// </summary>
/// <param name="fileExtension">the file extension (i.e. '.gif')</param>
/// <param name="contentType">the content type (i.e. 'image/gif')</param>
public static void SetContentType(string fileExtension, string contentType)
{
// try to read the registry, throw mimehelper exception if it fails
try
{
RegistryKey extKey = Registry.ClassesRoot.CreateSubKey(fileExtension);
Debug.Assert(extKey != null, "Content Type Not Set");
using (extKey)
{
extKey.SetValue(CONTENT_TYPE_KEY, contentType);
}
}
catch (Exception e)
{
throw MimeHelperException.ForUnableToSetContentType(contentType, e);
}
}
/// <summary>
/// Application/octet-stream content type, a good default for
/// unrecognized content types.
/// </summary>
public const string APP_OCTET_STREAM = "application/octet-stream";
/// <summary>
/// Text/html content type
/// </summary>
public const string TEXT_HTML = "text/html";
public const string TEXT_XML = "text/xml";
/// <summary>
/// Text/plain content type
/// </summary>
public const string TEXT_PLAIN = "text/plain";
public const string IMAGE_JPG = "image/jpeg";
public const string IMAGE_GIF = "image/gif";
public const string IMAGE_PNG = "image/png";
public const string IMAGE_TIF = "image/tiff";
public const string IMAGE_BMP = "image/bmp";
public const string IMAGE_XPNG = "image/x-png";
public const string IMAGE_ICON = "image/x-icon";
public const string CONTENTTYPE_UNKNOWN = "application/x-internal-unknown-type";
/// <summary>
/// This takes a file extension and returns the mime content type for
/// the file. Returns the default if no content type is found.
/// </summary>
/// <param name="fileExtension">the file extension (i.e. '.gif')</param>
/// <param name="defaultValue">the content type value to be returned if no
/// content type can be located for this file extension</param>
/// <returns>the content type (i.e. 'image/gif')</returns>
public static string GetContentType(string fileExtension, string defaultValue)
{
// Sometimes registries get corrupted and don't contain these
// values, which causes Blogger image uploads to be rejected.
switch (fileExtension.ToUpperInvariant())
{
case ".GIF":
return "image/gif";
case ".JPE":
case ".JPEG":
case ".JPG":
return "image/jpeg";
case ".PNG":
return "image/png";
}
// ENHANCEMENT: Some extension (.js, .ashx, .css) may slip through and
// be base64 encoded even though they're text. We could force those to be
// QP encoded using a static hash of extensions...
// Open the registry key for the extension and return the
// content type, if possible
RegistryKey extKey = Registry.ClassesRoot.OpenSubKey(fileExtension, false);
if (extKey != null)
{
using (extKey)
{
object contentType = extKey.GetValue(CONTENT_TYPE_KEY, defaultValue);
// If there isn't a content type key for this file type
if (contentType == null)
return defaultValue;
else
return contentType.ToString();
}
}
else
return defaultValue;
}
/// <summary>
/// Gets the appropriate extension for a file based upon its content type.
/// </summary>
/// <param name="contentType">The content type for which to locate the extension</param>
/// <returns>The extension including the '.', null if no extension could be found</returns>
public static string GetExtensionFromContentType(string contentType)
{
string extension = null;
using (RegistryKey mimeKey = Registry.ClassesRoot.OpenSubKey("MIME\\Database\\Content Type"))
{
string[] subKeys = mimeKey.GetSubKeyNames();
if (new ArrayList(subKeys).Contains(contentType))
{
extension = (string)mimeKey.OpenSubKey(contentType).GetValue(EXTENSION);
}
}
return extension;
}
private const string MIME_DATABASE_CONTENTTYPE = "MIME\\Database\\Content Type";
private const string EXTENSION = "Extension";
//
// The below are an enumeration of the available encoding types
//
/// <summary>
/// Base 64 encoding
/// </summary>
public const string Base64 = "base64";
/// <summary>
/// 7bit Encoding (used only for low ascii plain text)
/// </summary>
public const string LowAscii = "7Bit";
/// <summary>
/// Quoted-printable encoding (used for all text)
/// </summary>
public const string QuotedPrintable = "quoted-printable";
/// <summary>
/// Gets the encoding type to use for this content type
/// </summary>
/// <param name="contentType">contentType to find encoding for</param>
/// <returns>encoding type</returns>
public static string GetEncodingType(string contentType, Stream input)
{
// if we recognize the mime type as text, use quoted printable
// which is more efficient for text
if (contentType.Trim().StartsWith("text", StringComparison.OrdinalIgnoreCase))
{
string encodingType = MimeHelper.QuotedPrintable;
// Look for any unicode characters
StreamReader reader = new StreamReader(input);
char[] chars = new char[1];
int ch;
while (reader.Peek() != -1)
{
ch = reader.Read();
if (ch > 127)
{
encodingType = MimeHelper.Base64;
break;
}
}
input.Position = 0;
//return encodingType;
return encodingType;
}
// if we're not sure its text, use base64, which can handle anything
// but is less efficient for text encoding
else
{
return MimeHelper.Base64;
}
}
/// <summary>
/// Write base64 encoded data
/// </summary>
/// <param name="input">the stream to base64 encode</param>
/// <param name="output">the output stream to write the MIME header to</param>
public static void EncodeBase64(Stream input, Stream output)
{
// Get a writer (use ASCII encoding since this will write 7 bit ascii text)
StreamWriter writer = new StreamWriter(output, ASCIIEncoding.ASCII);
// Each 3 byte sequence in the source data becomes a 4 byte
// sequence in the character array. (so the byte buffer is 3/4 the
// size of a line of characters
const int BUFFER_SIZE = (int)( MimeHelper.MAX_LINE_LENGTH * (3.0d / 4.0d ));
// Set up the buffers for read/write operations
byte[] unEncodedBytes = new byte[BUFFER_SIZE];
char[] encodedChars = new char[MimeHelper.MAX_LINE_LENGTH];
// do the encoding
int bytesRead = 0;
do
{
// put the bytes into the input stream
bytesRead = input.Read(unEncodedBytes, 0, BUFFER_SIZE);
if ( bytesRead > 0 )
{
// encode the bytes into the character array
int charsEncoded = Convert.ToBase64CharArray(
unEncodedBytes, 0 , bytesRead, encodedChars, 0);
// write the line to output
writer.WriteLine(encodedChars, 0, charsEncoded);
}
} while (bytesRead == BUFFER_SIZE);
// Flush this writer to make sure any internal buffer is empty.
writer.Flush();
}
/// <summary>
/// Writes quoted printable encoded characters to the output stream
/// Uses a state table defined in QpStateTable to drive the encoding.
/// </summary>
/// <param name="input">stream to encode</param>
/// <param name="output">streamwriter to write to</param>
public static void EncodeQuotedPrintable(Stream input, Stream output)
{
// Get a reader and writer on the streams
// (use ASCII encoding for the writer since this will write 7 bit ascii text)
StreamReader reader = new StreamReader(input);
StreamWriter writer = new StreamWriter(output, ASCIIEncoding.ASCII);
// init line position and current state
int linePosition = 1;
int currentState = SCANNING;
// do the encoding
int ch = reader.Peek();
while (ch != -1)
{
// get the character type
int charType = GetQpCharType(ch);
// get the actions for the current state and character type
int actions = QPStateTable[currentState, charType,ACTION];
// execute the actions for this character
if ((actions & OUTPUT) > 0)
{
writer.Write((char) ch);
linePosition += 1;
}
if ((actions & OUTPUT_ESCAPED) > 0)
{
writer.Write("={0:X2}", ch); // the format :X2 forces to hex encoding w/ a minimum of 2 characters
linePosition += 3;
}
if ((actions & OUTPUT_SOFT_CRLF) > 0)
{
writer.Write("=\r\n");
linePosition = 1;
}
if ((actions & OUTPUT_CRLF) > 0)
{
writer.Write("\r\n");
linePosition = 1;
}
// If there is no putback, read the character to dispose of it
// If there is a putback, do nothing, leaving the character in the stream
if ((actions & PUTBACK) == 0)
{
reader.Read();
}
// Get the new state
currentState = QPStateTable[currentState, charType,NEW_STATE];
// If the state is pending, we need to use the line position
// to determine what the new state should be be. The red zone
// means we're near the end of a line (76 characters wide) and
// so need to be careful.
if (currentState == PENDING)
{
if (linePosition >= REDZONE_LINE_POSITION)
currentState = REDZONE;
else
currentState = SCANNING;
}
// Lookahead to the next character
ch = reader.Peek();
}
// Flush this writer to make sure any internal buffer is empty.
writer.Flush();
}
/// <summary>
/// Determines whether the given content type is an image
/// </summary>
/// <param name="contentType">The content type string</param>
/// <returns>true if it is an image, otherwise false</returns>
public static bool IsContentTypeImage(string contentType)
{
if (contentType == null)
return false;
foreach(string imageContentType in m_imageContentTypes)
if (contentType.StartsWith(imageContentType, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
/// <summary>
/// Determines whether the given content type is a page
/// </summary>
/// <param name="contentType">The content type string</param>
/// <returns>true if it is a page, otherwise false</returns>
public static bool IsContentTypeWebPage(string contentType)
{
if (contentType == null)
return false;
foreach(string webPageContentType in m_webPageContentTypes)
if (contentType.StartsWith(webPageContentType, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
/// <summary>
/// Determines whether the given content type is a document (this is a loose definition based on our experience)
/// </summary>
/// <param name="contentType">The content type</param>
/// <returns>true if it is a document, otherwise false</returns>
public static bool IsContentTypeDocument(string contentType)
{
if (contentType == null)
return false;
foreach(string documentContentType in m_documentContentTypes)
if (contentType.StartsWith(documentContentType, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
/// <summary>
/// Determines whether the given content type is a file
/// </summary>
/// <param name="contentType">The content type string</param>
/// <returns>true if it is a file, otherwise false</returns>
public static bool IsContentTypeFile(string contentType)
{
if (contentType == null)
return false;
return !(IsContentTypeImage(contentType) || IsContentTypeWebPage(contentType)) && (contentType != CONTENTTYPE_UNKNOWN);
}
private static string[] m_imageContentTypes = new string[] {MimeHelper.IMAGE_GIF,MimeHelper.IMAGE_JPG,MimeHelper.IMAGE_PNG,MimeHelper.IMAGE_XPNG, MimeHelper.IMAGE_TIF, MimeHelper.IMAGE_ICON,"image/x-xbitmap"};
private static string[] m_webPageContentTypes = new string[] {"text/html", "html document", "application/x-httpd-php", "application/xhtml+xml", "htm file"};
private static string[] m_documentContentTypes =
new string[] { "application/pdf",
"application/postscript",
"application/msword",
"application/x-msexcel",
"application/x-mspowerpoint",
"application/vnd.ms-excel",
"application/vnd.ms-powerpoint",
"application/vnd.visio",
"text/rtf",
"application/rtf",
"application/vnd.ms-publisher",
"application/x-mspublisher",
"text/plain"};
/// <summary>
/// Returns the quoted printable character type for a given chacacter
/// </summary>
/// <param name="ascii">the character to determine type</param>
/// <returns>the character type</returns>
private static int GetQpCharType(int ascii)
{
// legal ascii-
if ((ascii >= 33 && ascii <= 60)||
(ascii >= 62 && ascii <= 126) ||
(ascii == 0))
return LEGAL_ASCII;
// tab or space
else if (ascii == 9 || ascii == 32)
return WHITESPACE;
// lineFeed
else if (ascii == 10)
return LINEFEED;
// carriage Return
else if (ascii == 13)
return CARRIAGE_RETURN;
// high or low illegal ascii value
else if ((ascii < 255 && ascii > 126)||(ascii > 0 && ascii < 33)||(ascii == 61))
return ILLEGAL_ASCII;
// ascii value that is unsupportable by this encoding
else
// Throw illegal character exception
throw MimeHelperException.ForIllegalEncodingCharacter((char) ascii, "quoted-printable", null);
}
// The states, actions, and inputs used in the quoted printable encoder
#region Quoted Printable State Table
/// states
private const int SCANNING = 0;
private const int LOOK_FOR_LF = 1;
private const int REDZONE = 2;
private const int END_OF_LINE = 3;
private const int PENDING = 4;
/// inputs
private const int LEGAL_ASCII = 0;
private const int ILLEGAL_ASCII = 1;
private const int WHITESPACE = 2;
private const int CARRIAGE_RETURN = 3;
private const int LINEFEED = 4;
/// actions
private const int NONE = 0;
private const int OUTPUT = 1;
private const int OUTPUT_ESCAPED = 2;
private const int OUTPUT_SOFT_CRLF = 4;
private const int OUTPUT_CRLF = 8;
private const int PUTBACK = 16;
/// aggregate actions
private const int CRLF_AND_PUTBACK = OUTPUT_CRLF | PUTBACK;
private const int SOFT_CRLF_AND_PUTBACK = OUTPUT_SOFT_CRLF | PUTBACK;
/// action / state pair
private const int ACTION = 0;
private const int NEW_STATE = 1;
/// determines which line position begins the redzone
private const int REDZONE_LINE_POSITION = MAX_LINE_LENGTH - 3;
/// <summary>
/// This is the overall state table for the quoted printable encoding
/// </summary>
private static int[,,] QPStateTable =
{
// SCANNING
{
{OUTPUT,PENDING}, // Legal Ascii
{OUTPUT_ESCAPED,PENDING}, // Illegal Ascii
{OUTPUT,PENDING}, // WriteSpace
{NONE,LOOK_FOR_LF}, // CarriageReturn
{OUTPUT_CRLF, SCANNING} // Linefeed
},
// LOOK_FOR_LF
{
{CRLF_AND_PUTBACK, SCANNING}, // Legal Ascii
{CRLF_AND_PUTBACK, SCANNING}, // Illegal Ascii
{CRLF_AND_PUTBACK, SCANNING}, // WhiteSpace
{CRLF_AND_PUTBACK, SCANNING}, // CarriageReturn
{OUTPUT_CRLF, SCANNING} // Linefeed
},
// REDZONE
{
{OUTPUT, END_OF_LINE}, // Legal Ascii
{OUTPUT_ESCAPED, END_OF_LINE}, // Illegal Ascii
{OUTPUT_ESCAPED, END_OF_LINE}, // WhiteSpace
{NONE, LOOK_FOR_LF}, // CarriageReturn
{OUTPUT_CRLF, SCANNING} // Linefeed
},
// END_OF_LINE
{
{SOFT_CRLF_AND_PUTBACK, SCANNING}, // Legal Ascii
{SOFT_CRLF_AND_PUTBACK, SCANNING}, // Illegal Ascii
{SOFT_CRLF_AND_PUTBACK, SCANNING}, // WhiteSpace
{NONE, LOOK_FOR_LF}, // CarriageReturn
{OUTPUT_CRLF, SCANNING} // Linefeed
}
};
#endregion
/// <summary>
/// Parses content-type header values of the form
/// mainValue;param1=value1;param2=value2
/// but taking into account folding whitespace, comments, quoting,
/// quoted-char, and all the other stuff that RFC2045/RFC2822
/// force us to deal with.
///
/// To get the mainValue, look for the key "" in the result table.
/// </summary>
public static IDictionary ParseContentType(string contentType, bool caseInsensitive)
{
IDictionary result = new Hashtable();
// get main value
string[] mainAndRest = contentType.Split(new char[] {';'}, 2);
result[""] = mainAndRest[0].Trim().ToLower(CultureInfo.InvariantCulture);
if (mainAndRest.Length > 1)
{
char[] chars = mainAndRest[1].ToCharArray();
StringBuilder paramName = new StringBuilder();
StringBuilder paramValue = new StringBuilder();
const byte READY_FOR_NAME = 0;
const byte IN_NAME = 1;
const byte READY_FOR_VALUE = 2;
const byte IN_VALUE = 3;
const byte IN_QUOTED_VALUE = 4;
const byte VALUE_DONE = 5;
const byte ERROR = 99;
byte state = READY_FOR_NAME;
for (int i = 0; i < chars.Length; i++)
{
char c = chars[i];
switch(state)
{
case ERROR:
if (c == ';')
state = READY_FOR_NAME;
break;
case READY_FOR_NAME:
if (c == '=')
{
Debug.Fail("Expected header param name, got '='");
state = ERROR;
break;
}
paramName = new StringBuilder();
paramValue = new StringBuilder();
state = IN_NAME;
goto case IN_NAME;
case IN_NAME:
if (c == '=')
{
if (paramName.Length == 0)
state = ERROR;
else
state = READY_FOR_VALUE;
break;
}
// not '='... just add to name
paramName.Append(c);
break;
case READY_FOR_VALUE:
bool gotoCaseInValue = false;
switch (c)
{
case ' ':
case '\t':
break; // ignore spaces, especially before '"'
case '"':
state = IN_QUOTED_VALUE;
break;
default:
state = IN_VALUE;
gotoCaseInValue = true;
break;
}
if (gotoCaseInValue)
goto case IN_VALUE;
else
break;
case IN_VALUE:
switch (c)
{
case ';':
result[paramName.ToString().Trim()] = paramValue.ToString().Trim();
state = READY_FOR_NAME;
break;
default:
paramValue.Append(c);
break;
}
break;
case IN_QUOTED_VALUE:
switch (c)
{
case '"':
// don't trim quoted strings; the spaces could be intentional.
result[paramName.ToString().Trim()] = paramValue.ToString();
state = VALUE_DONE;
break;
case '\\':
// quoted-char
if (i == chars.Length - 1)
{
state = ERROR;
}
else
{
i++;
paramValue.Append(chars[i]);
}
break;
default:
paramValue.Append(c);
break;
}
break;
case VALUE_DONE:
switch (c)
{
case ';':
state = READY_FOR_NAME;
break;
case ' ':
case '\t':
break;
default:
state = ERROR;
break;
}
break;
}
}
// done looping. check if anything is left over.
if (state == IN_VALUE || state == READY_FOR_VALUE)
{
result[paramName.ToString().Trim()] = paramValue.ToString().Trim();
}
}
if (caseInsensitive)
return CollectionsUtil.CreateCaseInsensitiveHashtable(result);
else
return result;
}
/// <summary>
/// The maximum length of a line in a Mime Multipart Document
/// </summary>
private const int MAX_LINE_LENGTH = 76;
// The registry key that stores the content type value
private const string CONTENT_TYPE_KEY = "Content Type";
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
namespace System.Runtime.Serialization.Json
{
internal class JavaScriptReader
{
TextReader r;
int line = 1, column = 0;
// bool raise_on_number_error; // FIXME: use it
public JavaScriptReader (TextReader reader, bool raiseOnNumberError)
{
if (reader == null)
throw new ArgumentNullException ("reader");
this.r = reader;
// raise_on_number_error = raiseOnNumberError;
}
public object Read ()
{
object v = ReadCore ();
SkipSpaces ();
if (r.Read () >= 0)
throw JsonError (String.Format ("extra characters in JSON input"));
return v;
}
object ReadCore ()
{
SkipSpaces ();
int c = PeekChar ();
if (c < 0)
throw JsonError ("Incomplete JSON input");
switch (c) {
case '[':
ReadChar ();
var list = new List<object> ();
SkipSpaces ();
if (PeekChar () == ']') {
ReadChar ();
return list;
}
while (true) {
list.Add (ReadCore ());
SkipSpaces ();
c = PeekChar ();
if (c != ',')
break;
ReadChar ();
continue;
}
if (ReadChar () != ']')
throw JsonError ("JSON array must end with ']'");
return list.ToArray ();
case '{':
ReadChar ();
var obj = new Dictionary<string,object> ();
SkipSpaces ();
if (PeekChar () == '}') {
ReadChar ();
return obj;
}
while (true) {
SkipSpaces ();
if (PeekChar () == '}')
break;
string name = ReadStringLiteral ();
SkipSpaces ();
Expect (':');
SkipSpaces ();
obj [name] = ReadCore (); // it does not reject duplicate names.
SkipSpaces ();
c = ReadChar ();
if (c == ',')
continue;
if (c == '}')
break;
}
#if MONOTOUCH
int idx = 0;
KeyValuePair<string, object> [] ret = new KeyValuePair<string, object>[obj.Count];
foreach (KeyValuePair <string, object> kvp in obj)
ret [idx++] = kvp;
return ret;
#else
return obj.ToArray ();
#endif
case 't':
Expect ("true");
return true;
case 'f':
Expect ("false");
return false;
case 'n':
Expect ("null");
// FIXME: what should we return?
return (string) null;
case '"':
return ReadStringLiteral ();
default:
if ('0' <= c && c <= '9' || c == '-')
return ReadNumericLiteral ();
else
throw JsonError (String.Format ("Unexpected character '{0}'", (char) c));
}
}
int peek;
bool has_peek;
bool prev_lf;
int PeekChar ()
{
if (!has_peek) {
peek = r.Read ();
has_peek = true;
}
return peek;
}
int ReadChar ()
{
int v = has_peek ? peek : r.Read ();
has_peek = false;
if (prev_lf) {
line++;
column = 0;
prev_lf = false;
}
if (v == '\n')
prev_lf = true;
column++;
return v;
}
void SkipSpaces ()
{
while (true) {
switch (PeekChar ()) {
case ' ': case '\t': case '\r': case '\n':
ReadChar ();
continue;
default:
return;
}
}
}
// It could return either int, long or decimal, depending on the parsed value.
object ReadNumericLiteral ()
{
bool negative = false;
if (PeekChar () == '-') {
negative = true;
ReadChar ();
if (PeekChar () < 0)
throw JsonError ("Invalid JSON numeric literal; extra negation");
}
int c;
decimal val = 0;
int x = 0;
bool zeroStart = PeekChar () == '0';
for (; ; x++) {
c = PeekChar ();
if (c < '0' || '9' < c)
break;
val = val * 10 + (c - '0');
ReadChar ();
if (zeroStart && x == 1 && c == '0')
throw JsonError ("leading multiple zeros are not allowed");
}
// fraction
bool hasFrac = false;
decimal frac = 0;
int fdigits = 0;
if (PeekChar () == '.') {
hasFrac = true;
ReadChar ();
if (PeekChar () < 0)
throw JsonError ("Invalid JSON numeric literal; extra dot");
decimal d = 10;
while (true) {
c = PeekChar ();
if (c < '0' || '9' < c)
break;
ReadChar ();
frac += (c - '0') / d;
d *= 10;
fdigits++;
}
if (fdigits == 0)
throw JsonError ("Invalid JSON numeric literal; extra dot");
}
#if __ANDROID__ || __IOS__ || MOBILE
frac = Decimal.Round(frac, fdigits);
#else
throw new NotImplementedException("Salesforce PCL Bite-n-Switch Not ImplementedException");
#endif
c = PeekChar ();
if (c != 'e' && c != 'E') {
if (!hasFrac) {
if (negative && int.MinValue <= -val ||
!negative && val <= int.MaxValue)
return (int) (negative ? -val : val);
if (negative && long.MinValue <= -val ||
!negative && val <= long.MaxValue)
return (long) (negative ? -val : val);
}
var v = val + frac;
return negative ? -v : v;
}
// exponent
ReadChar ();
int exp = 0;
if (PeekChar () < 0)
throw new ArgumentException ("Invalid JSON numeric literal; incomplete exponent");
bool negexp = false;
c = PeekChar ();
if (c == '-') {
ReadChar ();
negexp = true;
}
else if (c == '+')
ReadChar ();
if (PeekChar () < 0)
throw JsonError ("Invalid JSON numeric literal; incomplete exponent");
while (true) {
c = PeekChar ();
if (c < '0' || '9' < c)
break;
exp = exp * 10 + (c - '0');
ReadChar ();
}
// it is messy to handle exponent, so I just use Decimal.Parse() with assured JSON format.
if (negexp)
return new Decimal ((double) (val + frac) / Math.Pow (10, exp));
int [] bits = Decimal.GetBits (val + frac);
return new Decimal (bits [0], bits [1], bits [2], negative, (byte) exp);
}
StringBuilder vb = new StringBuilder ();
string ReadStringLiteral ()
{
if (PeekChar () != '"')
throw JsonError ("Invalid JSON string literal format");
ReadChar ();
vb.Length = 0;
while (true) {
int c = ReadChar ();
if (c < 0)
throw JsonError ("JSON string is not closed");
if (c == '"')
return vb.ToString ();
else if (c != '\\') {
vb.Append ((char) c);
continue;
}
// escaped expression
c = ReadChar ();
if (c < 0)
throw JsonError ("Invalid JSON string literal; incomplete escape sequence");
switch (c) {
case '"':
case '\\':
case '/':
vb.Append ((char) c);
break;
case 'b':
vb.Append ('\x8');
break;
case 'f':
vb.Append ('\f');
break;
case 'n':
vb.Append ('\n');
break;
case 'r':
vb.Append ('\r');
break;
case 't':
vb.Append ('\t');
break;
case 'u':
ushort cp = 0;
for (int i = 0; i < 4; i++) {
cp <<= 4;
if ((c = ReadChar ()) < 0)
throw JsonError ("Incomplete unicode character escape literal");
if ('0' <= c && c <= '9')
cp += (ushort) (c - '0');
if ('A' <= c && c <= 'F')
cp += (ushort) (c - 'A' + 10);
if ('a' <= c && c <= 'f')
cp += (ushort) (c - 'a' + 10);
}
vb.Append ((char) cp);
break;
default:
throw JsonError ("Invalid JSON string literal; unexpected escape character");
}
}
}
void Expect (char expected)
{
int c;
if ((c = ReadChar ()) != expected)
throw JsonError (String.Format ("Expected '{0}', got '{1}'", expected, (char) c));
}
void Expect (string expected)
{
for (int i = 0; i < expected.Length; i++)
if (ReadChar () != expected [i])
throw JsonError (String.Format ("Expected '{0}', differed at {1}", expected, i));
}
Exception JsonError (string msg)
{
return new ArgumentException (String.Format ("{0}. At line {1}, column {2}", msg, line, column));
}
}
}
| |
/***************************************************************************
* DiscUsageDisplay.cs
*
* Copyright (C) 2006 Novell, Inc.
* Written by Aaron Bockover <aaron@abock.org>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* 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 Gtk;
using Cairo;
using Hyena.Gui;
namespace Banshee.Widgets
{
public class DiscUsageDisplay : Gtk.DrawingArea
{
private static Color bound_color_a = new Cairo.Color(1, 0x66 / (double)0xff, 0x00);
private static Color bound_color_b = new Cairo.Color(1, 0xcc / (double)0xff, 0x00, 0.3);
private static Color disc_color_a = new Cairo.Color(1, 1, 1);
private static Color disc_color_b = new Cairo.Color(0.95, 0.95, 0.95);
private static Color red_color = new Cairo.Color(0xcc / (double)0xff, 0, 0, 0.5);
private RadialGradient bg_gradient;
private RadialGradient fg_gradient_full;
private RadialGradient fg_gradient;
private RadialGradient bound_gradient;
private Color fill_color_a;
private Color fill_color_b;
private Color fill_color_c;
private Color stroke_color;
private Color inner_stroke_color;
private Color text_color;
private Color text_bg_color;
private static readonly double a1 = 3 * Math.PI / 2;
private double x, y, radius, a2, base_line_width;
private long capacity;
private long usage;
public DiscUsageDisplay()
{
AppPaintable = true;
}
protected override void OnStyleSet(Gtk.Style style)
{
fill_color_a = CairoExtensions.GdkColorToCairoColor(Style.Background(StateType.Selected));
fill_color_b = CairoExtensions.GdkColorToCairoColor(Style.Foreground(StateType.Selected));
fill_color_c = CairoExtensions.GdkColorToCairoColor(Style.Background(StateType.Normal));
stroke_color = CairoExtensions.GdkColorToCairoColor(Style.Foreground(StateType.Normal), 0.6);
inner_stroke_color = CairoExtensions.GdkColorToCairoColor(Style.Foreground(StateType.Normal), 0.4);
text_color = CairoExtensions.GdkColorToCairoColor(Style.Foreground(StateType.Normal), 0.8);
text_bg_color = CairoExtensions.GdkColorToCairoColor(Style.Background(StateType.Normal), 0.6);
}
protected override void OnSizeAllocated(Gdk.Rectangle rect)
{
x = rect.Width / 2.0;
y = rect.Height / 2.0;
radius = Math.Min(rect.Width / 2, rect.Height / 2) - 5;
base_line_width = Math.Sqrt(radius) * 0.2;
bg_gradient = new RadialGradient(x, y, 0, x, y, radius);
bg_gradient.AddColorStop(0, disc_color_a);
bg_gradient.AddColorStop(1, disc_color_b);
fg_gradient = new RadialGradient(x, y, 0, x, y, radius * 2);
fg_gradient.AddColorStop(0, fill_color_a);
fg_gradient.AddColorStop(1, fill_color_b);
fg_gradient_full = new RadialGradient(x, y, 0, x, y, radius);
fg_gradient_full.AddColorStop(0, disc_color_b);
fg_gradient_full.AddColorStop(1, red_color);
bound_gradient = new RadialGradient(x, y, 0, x, y, radius * 2);
bound_gradient.AddColorStop(0, bound_color_a);
bound_gradient.AddColorStop(1, bound_color_b);
base.OnSizeAllocated(rect);
}
protected override bool OnExposeEvent(Gdk.EventExpose evnt)
{
if(!IsRealized) {
return false;
}
Cairo.Context cr = Gdk.CairoHelper.Create(GdkWindow);
foreach(Gdk.Rectangle rect in evnt.Region.GetRectangles()) {
cr.Rectangle(rect.X, rect.Y, rect.Width, rect.Height);
cr.Clip();
Draw(cr);
}
((IDisposable)cr).Dispose();
return false;
}
private void Draw(Cairo.Context cr)
{
cr.Antialias = Antialias.Subpixel;
cr.LineWidth = base_line_width / 1.5;
cr.Arc(x, y, radius, 0, 2 * Math.PI);
cr.Pattern = bg_gradient;
cr.Fill();
/*cr.LineTo(x, y);
cr.Arc(x, y, radius, a1 + 2 * Math.PI * 0.92, a1);
cr.LineTo(x, y);
cr.Pattern = bound_gradient;
cr.Fill();
cr.Stroke();*/
if(Capacity > 0) {
if(Fraction < 1.0) {
cr.LineTo(x, y);
cr.Arc(x, y, radius, a1, a2);
cr.LineTo(x, y);
} else {
cr.Arc(x, y, radius, 0, 2 * Math.PI);
}
cr.Pattern = Fraction >= 1.0 ? fg_gradient_full : fg_gradient;
cr.FillPreserve();
cr.Color = stroke_color;
cr.Stroke();
}
cr.Arc(x, y, radius / 2.75, 0, 2 * Math.PI);
cr.Color = fill_color_c;
cr.FillPreserve();
cr.Color = new Cairo.Color(1, 1, 1, 0.75);
cr.FillPreserve();
cr.LineWidth = base_line_width / 1.5;
cr.Color = stroke_color;
cr.Stroke();
cr.Arc(x, y, radius / 5.5, 0, 2 * Math.PI);
cr.Color = fill_color_c;
cr.FillPreserve();
cr.LineWidth = base_line_width / 2;
cr.Color = inner_stroke_color;
cr.Stroke();
cr.Arc(x, y, radius, 0, 2 * Math.PI);
cr.Stroke();
if(Capacity <= 0) {
// this sucks balls
cr.Rectangle(0, 0, Allocation.Width, Allocation.Height);
cr.Color = text_bg_color;
cr.FillPreserve();
cr.SelectFontFace("Sans", FontSlant.Normal, FontWeight.Bold);
cr.Color = text_color;
cr.SetFontSize(Allocation.Width * 0.2);
DrawText(cr, Mono.Unix.Catalog.GetString("Insert\nDisc"), 3);
}
}
private void DrawText(Cairo.Context cr, string text, double lineSpacing)
{
string [] lines = text.Split('\n');
double [] cuml_heights = new double[lines.Length];
double y_start = 0.0;
for(int i = 0; i < lines.Length; i++) {
TextExtents extents = cr.TextExtents(lines[i]);
double height = extents.Height + (i > 0 ? lineSpacing : 0);
cuml_heights[i] = i > 0 ? cuml_heights[i - 1] + height : height;
}
y_start = (Allocation.Height / 2) - (cuml_heights[cuml_heights.Length - 1] / 2);
for(int i = 0; i < lines.Length; i++) {
TextExtents extents = cr.TextExtents(lines[i]);
double x = (Allocation.Width / 2) - (extents.Width / 2);
double y = y_start + cuml_heights[i];
cr.MoveTo(x, y);
cr.ShowText(lines[i]);
}
}
private void CalculateA2()
{
a2 = a1 + 2 * Math.PI * Fraction;
}
private double Fraction {
get { return (double)Usage / (double)Capacity; }
}
public long Capacity {
get { return capacity; }
set {
capacity = value;
CalculateA2();
QueueDraw();
}
}
public long Usage {
get { return usage; }
set {
usage = value;
CalculateA2();
QueueDraw();
}
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Layouts;
/// <summary>
/// Sends log messages to the remote instance of NLog Viewer.
/// </summary>
/// <remarks>
/// <a href="https://github.com/nlog/nlog/wiki/NLogViewer-target">See NLog Wiki</a>
/// </remarks>
/// <seealso href="https://github.com/nlog/nlog/wiki/NLogViewer-target">Documentation on NLog Wiki</seealso>
/// <example>
/// <p>
/// To set up the target in the <a href="https://github.com/NLog/NLog/wiki/Configuration-file">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/NLogViewer/NLog.config" />
/// <p>
/// To set up the log target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/NLogViewer/Simple/Example.cs" />
/// </example>
[Target("NLogViewer")]
public class NLogViewerTarget : NetworkTarget, IIncludeContext
{
private readonly Log4JXmlEventLayout _log4JLayout = new Log4JXmlEventLayout();
/// <summary>
/// Initializes a new instance of the <see cref="NLogViewerTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code>
/// </remarks>
public NLogViewerTarget()
{
IncludeNLogData = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="NLogViewerTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}</code>
/// </remarks>
/// <param name="name">Name of the target.</param>
public NLogViewerTarget(string name) : this()
{
Name = name;
}
/// <summary>
/// Gets or sets a value indicating whether to include NLog-specific extensions to log4j schema.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public bool IncludeNLogData
{
get => Renderer.IncludeNLogData;
set => Renderer.IncludeNLogData = value;
}
/// <summary>
/// Gets or sets the AppInfo field. By default it's the friendly name of the current AppDomain.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public Layout AppInfo
{
get => Renderer.AppInfo;
set => Renderer.AppInfo = value;
}
/// <summary>
/// Gets or sets a value indicating whether to include call site (class and method name) in the information sent over the network.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public bool IncludeCallSite
{
get => Renderer.IncludeCallSite;
set => Renderer.IncludeCallSite = value;
}
/// <summary>
/// Gets or sets a value indicating whether to include source info (file name and line number) in the information sent over the network.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public bool IncludeSourceInfo
{
get => Renderer.IncludeSourceInfo;
set => Renderer.IncludeSourceInfo = value;
}
/// <summary>
/// Gets or sets a value indicating whether to include <see cref="MappedDiagnosticsContext"/> dictionary contents.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")]
[EditorBrowsable(EditorBrowsableState.Never)]
public bool IncludeMdc
{
get => Renderer.IncludeMdc;
set => Renderer.IncludeMdc = value;
}
/// <summary>
/// Gets or sets whether to include log4j:NDC in output from <see cref="ScopeContext"/> nested context.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public bool IncludeNdc
{
get => Renderer.IncludeNdc;
set => Renderer.IncludeNdc = value;
}
/// <inheritdoc/>
/// <docgen category='Layout Options' order='10' />
public bool IncludeEventProperties { get => Renderer.IncludeEventProperties; set => Renderer.IncludeEventProperties = value; }
/// <inheritdoc/>
/// <docgen category='Layout Options' order='10' />
public bool IncludeScopeProperties { get => Renderer.IncludeScopeProperties; set => Renderer.IncludeScopeProperties = value; }
/// <summary>
/// Gets or sets whether to include log4j:NDC in output from <see cref="ScopeContext"/> nested context.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public bool IncludeScopeNested { get => Renderer.IncludeScopeNested; set => Renderer.IncludeScopeNested = value; }
/// <summary>
/// Gets or sets the separator for <see cref="ScopeContext"/> operation-states-stack.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public string ScopeNestedSeparator { get => Renderer.ScopeNestedSeparator; set => Renderer.ScopeNestedSeparator = value; }
/// <summary>
/// Gets or sets the option to include all properties from the log events
/// </summary>
/// <docgen category='Layout Options' order='10' />
[Obsolete("Replaced by IncludeEventProperties. Marked obsolete on NLog 5.0")]
[EditorBrowsable(EditorBrowsableState.Never)]
public bool IncludeAllProperties { get => IncludeEventProperties; set => IncludeEventProperties = value; }
/// <summary>
/// Gets or sets a value indicating whether to include <see cref="MappedDiagnosticsLogicalContext"/> dictionary contents.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")]
[EditorBrowsable(EditorBrowsableState.Never)]
public bool IncludeMdlc { get => Renderer.IncludeMdlc; set => Renderer.IncludeMdlc = value; }
/// <summary>
/// Gets or sets a value indicating whether to include contents of the <see cref="NestedDiagnosticsLogicalContext"/> stack.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[Obsolete("Replaced by IncludeNdc. Marked obsolete on NLog 5.0")]
[EditorBrowsable(EditorBrowsableState.Never)]
public bool IncludeNdlc { get => Renderer.IncludeNdlc; set => Renderer.IncludeNdlc = value; }
/// <summary>
/// Gets or sets the stack separator for log4j:NDC in output from <see cref="ScopeContext"/> nested context.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[Obsolete("Replaced by NdcItemSeparator. Marked obsolete on NLog 5.0")]
[EditorBrowsable(EditorBrowsableState.Never)]
public string NdlcItemSeparator { get => Renderer.NdlcItemSeparator; set => Renderer.NdlcItemSeparator = value; }
/// <summary>
/// Gets or sets the stack separator for log4j:NDC in output from <see cref="ScopeContext"/> nested context.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public string NdcItemSeparator
{
get => Renderer.NdcItemSeparator;
set => Renderer.NdcItemSeparator = value;
}
/// <summary>
/// Gets or sets the renderer for log4j:event logger-xml-attribute (Default ${logger})
/// </summary>
/// <docgen category='Layout Options' order='10' />
public Layout LoggerName
{
get => Renderer.LoggerName;
set => Renderer.LoggerName = value;
}
/// <summary>
/// Gets the collection of parameters. Each parameter contains a mapping
/// between NLog layout and a named parameter.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[ArrayParameter(typeof(NLogViewerParameterInfo), "parameter")]
public IList<NLogViewerParameterInfo> Parameters => _log4JLayout.Parameters;
/// <summary>
/// Gets the layout renderer which produces Log4j-compatible XML events.
/// </summary>
[NLogConfigurationIgnoreProperty]
public Log4JXmlEventLayoutRenderer Renderer => _log4JLayout.Renderer;
/// <summary>
/// Gets or sets the instance of <see cref="Log4JXmlEventLayout"/> that is used to format log messages.
/// </summary>
/// <docgen category='Layout Options' order='1' />
public override Layout Layout
{
get
{
return _log4JLayout;
}
set
{
// Fixed Log4JXmlEventLayout
}
}
}
}
| |
namespace GitVersion
{
using System;
using LibGit2Sharp;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
public static class GitHelper
{
const string MergeMessageRegexPattern = "refs/heads/(pr|pull(-requests)?/(?<issuenumber>[0-9]*)/(merge|head))";
public static void NormalizeGitDirectory(string gitDirectory, Authentication authentication, bool noFetch)
{
//If noFetch is enabled, then GitVersion will assume that the git repository is normalized before execution, so that fetching from remotes is not required.
if (noFetch)
{
Logger.WriteInfo("Skipping fetching");
return;
}
using (var repo = new Repository(gitDirectory))
{
var remote = EnsureOnlyOneRemoteIsDefined(repo);
AddMissingRefSpecs(repo, remote);
Logger.WriteInfo(string.Format("Fetching from remote '{0}' using the following refspecs: {1}.",
remote.Name, string.Join(", ", remote.FetchRefSpecs.Select(r => r.Specification))));
var fetchOptions = BuildFetchOptions(authentication.Username, authentication.Password);
repo.Network.Fetch(remote, fetchOptions);
CreateMissingLocalBranchesFromRemoteTrackingOnes(repo, remote.Name);
var headSha = repo.Refs.Head.TargetIdentifier;
if (!repo.Info.IsHeadDetached)
{
Logger.WriteInfo(string.Format("HEAD points at branch '{0}'.", headSha));
return;
}
Logger.WriteInfo(string.Format("HEAD is detached and points at commit '{0}'.", headSha));
// In order to decide whether a fake branch is required or not, first check to see if any local branches have the same commit SHA of the head SHA.
// If they do, go ahead and checkout that branch
// If no, go ahead and check out a new branch, using the known commit SHA as the pointer
var localBranchesWhereCommitShaIsHead = repo.Branches.Where(b => !b.IsRemote && b.Tip.Sha == headSha).ToList();
if (localBranchesWhereCommitShaIsHead.Count > 1)
{
var branchNames = localBranchesWhereCommitShaIsHead.Select(r => r.CanonicalName);
var csvNames = string.Join(", ", branchNames);
const string moveBranchMsg = "Move one of the branches along a commit to remove warning";
Logger.WriteWarning(string.Format("Found more than one local branch pointing at the commit '{0}' ({1}).", headSha, csvNames));
var master = localBranchesWhereCommitShaIsHead.SingleOrDefault(n => n.Name == "master");
if (master != null)
{
Logger.WriteWarning("Because one of the branches is 'master', will build master." + moveBranchMsg);
master.Checkout();
}
else
{
var branchesWithoutSeparators = localBranchesWhereCommitShaIsHead.Where(b => !b.Name.Contains('/') && !b.Name.Contains('-')).ToList();
if (branchesWithoutSeparators.Count == 1)
{
var branchWithoutSeparator = branchesWithoutSeparators[0];
Logger.WriteWarning(string.Format("Choosing {0} as it is the only branch without / or - in it. " + moveBranchMsg, branchWithoutSeparator.CanonicalName));
branchWithoutSeparator.Checkout();
}
else
{
throw new WarningException("Failed to try and guess branch to use. " + moveBranchMsg);
}
}
}
else if (localBranchesWhereCommitShaIsHead.Count == 0)
{
Logger.WriteInfo(string.Format("No local branch pointing at the commit '{0}'. Fake branch needs to be created.", headSha));
CreateFakeBranchPointingAtThePullRequestTip(repo, authentication);
}
else
{
Logger.WriteInfo(string.Format("Checking out local branch 'refs/heads/{0}'.", localBranchesWhereCommitShaIsHead[0].Name));
repo.Branches[localBranchesWhereCommitShaIsHead[0].Name].Checkout();
}
}
}
public static bool LooksLikeAValidPullRequestNumber(string issueNumber)
{
if (string.IsNullOrEmpty(issueNumber))
{
return false;
}
uint res;
return uint.TryParse(issueNumber, out res);
}
public static string ExtractIssueNumber(string mergeMessage)
{
// Dynamic: refs/heads/pr/5
// Github Message: refs/heads/pull/5/merge
// Stash Message: refs/heads/pull-requests/5/merge
// refs/heads/pull/5/head
var regex = new Regex(MergeMessageRegexPattern);
var match = regex.Match(mergeMessage);
var issueNumber = match.Groups["issuenumber"].Value;
return issueNumber;
}
static void AddMissingRefSpecs(Repository repo, Remote remote)
{
if (remote.FetchRefSpecs.Any(r => r.Source == "refs/heads/*"))
return;
var allBranchesFetchRefSpec = string.Format("+refs/heads/*:refs/remotes/{0}/*", remote.Name);
Logger.WriteInfo(string.Format("Adding refspec: {0}", allBranchesFetchRefSpec));
repo.Network.Remotes.Update(remote,
r => r.FetchRefSpecs.Add(allBranchesFetchRefSpec));
}
static FetchOptions BuildFetchOptions(string username, string password)
{
var fetchOptions = new FetchOptions();
if (!string.IsNullOrEmpty(username))
{
fetchOptions.CredentialsProvider = (url, user, types) => new UsernamePasswordCredentials
{
Username = username,
Password = password
};
}
return fetchOptions;
}
static void CreateFakeBranchPointingAtThePullRequestTip(Repository repo, Authentication authentication)
{
var remote = repo.Network.Remotes.Single();
var remoteTips = string.IsNullOrEmpty(authentication.Username) ?
GetRemoteTipsForAnonymousUser(repo, remote) :
GetRemoteTipsUsingUsernamePasswordCredentials(repo, remote, authentication.Username, authentication.Password);
var headTipSha = repo.Head.Tip.Sha;
var refs = remoteTips.Where(r => r.TargetIdentifier == headTipSha).ToList();
if (refs.Count == 0)
{
var message = string.Format("Couldn't find any remote tips from remote '{0}' pointing at the commit '{1}'.", remote.Url, headTipSha);
throw new WarningException(message);
}
if (refs.Count > 1)
{
var names = string.Join(", ", refs.Select(r => r.CanonicalName));
var message = string.Format("Found more than one remote tip from remote '{0}' pointing at the commit '{1}'. Unable to determine which one to use ({2}).", remote.Url, headTipSha, names);
throw new WarningException(message);
}
var canonicalName = refs[0].CanonicalName;
Logger.WriteInfo(string.Format("Found remote tip '{0}' pointing at the commit '{1}'.", canonicalName, headTipSha));
if (!canonicalName.StartsWith("refs/pull/") && !canonicalName.StartsWith("refs/pull-requests/"))
{
var message = string.Format("Remote tip '{0}' from remote '{1}' doesn't look like a valid pull request.", canonicalName, remote.Url);
throw new WarningException(message);
}
var fakeBranchName = canonicalName.Replace("refs/pull/", "refs/heads/pull/").Replace("refs/pull-requests/", "refs/heads/pull-requests/");
Logger.WriteInfo(string.Format("Creating fake local branch '{0}'.", fakeBranchName));
repo.Refs.Add(fakeBranchName, new ObjectId(headTipSha));
Logger.WriteInfo(string.Format("Checking local branch '{0}' out.", fakeBranchName));
repo.Checkout(fakeBranchName);
}
internal static IEnumerable<DirectReference> GetRemoteTipsUsingUsernamePasswordCredentials(Repository repo, string repoUrl, string username, string password)
{
// This is a work-around as long as https://github.com/libgit2/libgit2sharp/issues/1099 is not fixed
var remote = repo.Network.Remotes.Add(Guid.NewGuid().ToString(), repoUrl);
try
{
return GetRemoteTipsUsingUsernamePasswordCredentials(repo, remote, username, password);
}
finally
{
repo.Network.Remotes.Remove(remote.Name);
}
}
static IEnumerable<DirectReference> GetRemoteTipsUsingUsernamePasswordCredentials(Repository repo, Remote remote, string username, string password)
{
return repo.Network.ListReferences(remote, (url, fromUrl, types) => new UsernamePasswordCredentials
{
Username = username,
Password = password
});
}
static IEnumerable<DirectReference> GetRemoteTipsForAnonymousUser(Repository repo, Remote remote)
{
return repo.Network.ListReferences(remote);
}
static void CreateMissingLocalBranchesFromRemoteTrackingOnes(Repository repo, string remoteName)
{
var prefix = string.Format("refs/remotes/{0}/", remoteName);
var remoteHeadCanonicalName = string.Format("{0}{1}", prefix, "HEAD");
foreach (var remoteTrackingReference in repo.Refs.FromGlob(prefix + "*").Where(r => r.CanonicalName != remoteHeadCanonicalName))
{
var remoteTrackingReferenceName = remoteTrackingReference.CanonicalName;
var branchName = remoteTrackingReferenceName.Substring(prefix.Length);
var localCanonicalName = "refs/heads/" + branchName;
if (repo.Refs.Any(x => x.CanonicalName == localCanonicalName))
{
Logger.WriteInfo(string.Format("Skipping local branch creation since it already exists '{0}'.", remoteTrackingReference.CanonicalName));
continue;
}
Logger.WriteInfo(string.Format("Creating local branch from remote tracking '{0}'.", remoteTrackingReference.CanonicalName));
var symbolicReference = remoteTrackingReference as SymbolicReference;
if (symbolicReference == null)
{
repo.Refs.Add(localCanonicalName, new ObjectId(remoteTrackingReference.TargetIdentifier), true);
}
else
{
repo.Refs.Add(localCanonicalName, new ObjectId(symbolicReference.ResolveToDirectReference().TargetIdentifier), true);
}
var branch = repo.Branches[branchName];
repo.Branches.Update(branch, b => b.TrackedBranch = remoteTrackingReferenceName);
}
}
static Remote EnsureOnlyOneRemoteIsDefined(IRepository repo)
{
var remotes = repo.Network.Remotes;
var howMany = remotes.Count();
if (howMany == 1)
{
var remote = remotes.Single();
Logger.WriteInfo(string.Format("One remote found ({0} -> '{1}').", remote.Name, remote.Url));
return remote;
}
var message = string.Format("{0} remote(s) have been detected. When being run on a TeamCity agent, the Git repository is expected to bear one (and no more than one) remote.", howMany);
throw new WarningException(message);
}
}
}
| |
// 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.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudioTools.Project;
using NativeMethods = Microsoft.VisualStudioTools.Project.NativeMethods;
using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants;
using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID;
using VsMenus = Microsoft.VisualStudioTools.Project.VsMenus;
namespace Microsoft.PythonTools.Project {
/// <summary>
/// Represents a package installed in a virtual env as a node in the Solution Explorer.
/// </summary>
[ComVisible(true)]
internal class InterpretersPackageNode : HierarchyNode {
private static readonly Regex PipFreezeRegex = new Regex(
"^(?<name>[^=]+)==(?<version>.+)$",
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase
);
private static readonly IEnumerable<string> CannotUninstall = new[] { "pip", "wsgiref" };
private readonly bool _canUninstall;
private readonly string _caption;
private readonly string _packageName;
public InterpretersPackageNode(PythonProjectNode project, string name)
: base(project, new VirtualProjectElement(project)) {
ExcludeNodeFromScc = true;
_packageName = name;
var match = PipFreezeRegex.Match(name);
if (match.Success) {
var namePart = match.Groups["name"].Value;
_caption = string.Format("{0} ({1})", namePart, match.Groups["version"]);
_canUninstall = !CannotUninstall.Contains(namePart);
} else {
_caption = name;
_canUninstall = false;
}
}
public override int MenuCommandId {
get { return PythonConstants.EnvironmentPackageMenuId; }
}
public override Guid MenuGroupId {
get { return GuidList.guidPythonToolsCmdSet; }
}
public override string Url {
get { return _packageName; }
}
public override Guid ItemTypeGuid {
get { return PythonConstants.InterpretersPackageItemTypeGuid; }
}
public new PythonProjectNode ProjectMgr {
get {
return (PythonProjectNode)base.ProjectMgr;
}
}
internal override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) {
return _canUninstall && deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_RemoveFromProject;
}
protected internal override void ShowDeleteMessage(IList<HierarchyNode> nodes, __VSDELETEITEMOPERATION action, out bool cancel, out bool useStandardDialog) {
if (nodes.All(n => n is InterpretersPackageNode) &&
nodes.Cast<InterpretersPackageNode>().All(n => n.Parent == Parent)) {
string message;
if (nodes.Count == 1) {
message = Strings.UninstallPackage.FormatUI(
Caption,
Parent._factory.Configuration.FullDescription,
Parent._factory.Configuration.PrefixPath
);
} else {
message = Strings.UninstallPackages.FormatUI(
string.Join(Environment.NewLine, nodes.Select(n => n.Caption)),
Parent._factory.Configuration.FullDescription,
Parent._factory.Configuration.PrefixPath
);
}
useStandardDialog = false;
cancel = VsShellUtilities.ShowMessageBox(
ProjectMgr.Site,
string.Empty,
message,
OLEMSGICON.OLEMSGICON_WARNING,
OLEMSGBUTTON.OLEMSGBUTTON_OKCANCEL,
OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST
) != NativeMethods.IDOK;
} else {
useStandardDialog = false;
cancel = true;
}
}
public override bool Remove(bool removeFromStorage) {
PythonProjectNode.BeginUninstallPackage(Parent._factory, ProjectMgr.Site, Url, Parent);
return true;
}
public new InterpretersNode Parent {
get {
return (InterpretersNode)base.Parent;
}
}
/// <summary>
/// Show the name of the package.
/// </summary>
public override string Caption {
get {
return _caption;
}
}
/// <summary>
/// Disable inline editing of Caption of a package node
/// </summary>
public override string GetEditLabel() {
return null;
}
protected override bool SupportsIconMonikers {
get { return true; }
}
protected override ImageMoniker GetIconMoniker(bool open) {
return KnownMonikers.PythonPackage;
}
/// <summary>
/// Package node cannot be dragged.
/// </summary>
protected internal override string PrepareSelectedNodesForClipBoard() {
return null;
}
/// <summary>
/// Package node cannot be excluded.
/// </summary>
internal override int ExcludeFromProject() {
return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
}
internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) {
if (cmdGroup == VsMenus.guidStandardCommandSet97) {
switch ((VsCommands)cmd) {
case VsCommands.Copy:
case VsCommands.Cut:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.INVISIBLE;
return VSConstants.S_OK;
case VsCommands.Delete:
if (!_canUninstall) {
// If we can't uninstall the package, still show the
// item but disable it. Otherwise, let the default
// query handle it, which will display "Remove".
result |= QueryStatusResult.SUPPORTED;
return VSConstants.S_OK;
}
break;
}
}
return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result);
}
/// <summary>
/// Defines whether this node is valid node for painting the package icon.
/// </summary>
/// <returns></returns>
protected override bool CanShowDefaultIcon() {
return true;
}
public override bool CanAddFiles {
get {
return false;
}
}
protected override NodeProperties CreatePropertiesObject() {
return new InterpretersPackageNodeProperties(this);
}
}
}
| |
using System;
using System.Globalization;
using System.Text;
using System.Threading;
namespace CatLib._3rd.ICSharpCode.SharpZipLib.Zip
{
#region Enumerations
/// <summary>
/// Determines how entries are tested to see if they should use Zip64 extensions or not.
/// </summary>
public enum UseZip64
{
/// <summary>
/// Zip64 will not be forced on entries during processing.
/// </summary>
/// <remarks>An entry can have this overridden if required <see cref="ZipEntry.ForceZip64"></see></remarks>
Off,
/// <summary>
/// Zip64 should always be used.
/// </summary>
On,
/// <summary>
/// #ZipLib will determine use based on entry values when added to archive.
/// </summary>
Dynamic,
}
/// <summary>
/// The kind of compression used for an entry in an archive
/// </summary>
public enum CompressionMethod
{
/// <summary>
/// A direct copy of the file contents is held in the archive
/// </summary>
Stored = 0,
/// <summary>
/// Common Zip compression method using a sliding dictionary
/// of up to 32KB and secondary compression from Huffman/Shannon-Fano trees
/// </summary>
Deflated = 8,
/// <summary>
/// An extension to deflate with a 64KB window. Not supported by #Zip currently
/// </summary>
Deflate64 = 9,
/// <summary>
/// BZip2 compression. Not supported by #Zip.
/// </summary>
BZip2 = 11,
/// <summary>
/// WinZip special for AES encryption, Now supported by #Zip.
/// </summary>
WinZipAES = 99,
}
/// <summary>
/// Identifies the encryption algorithm used for an entry
/// </summary>
public enum EncryptionAlgorithm
{
/// <summary>
/// No encryption has been used.
/// </summary>
None = 0,
/// <summary>
/// Encrypted using PKZIP 2.0 or 'classic' encryption.
/// </summary>
PkzipClassic = 1,
/// <summary>
/// DES encryption has been used.
/// </summary>
Des = 0x6601,
/// <summary>
/// RC2 encryption has been used for encryption.
/// </summary>
RC2 = 0x6602,
/// <summary>
/// Triple DES encryption with 168 bit keys has been used for this entry.
/// </summary>
TripleDes168 = 0x6603,
/// <summary>
/// Triple DES with 112 bit keys has been used for this entry.
/// </summary>
TripleDes112 = 0x6609,
/// <summary>
/// AES 128 has been used for encryption.
/// </summary>
Aes128 = 0x660e,
/// <summary>
/// AES 192 has been used for encryption.
/// </summary>
Aes192 = 0x660f,
/// <summary>
/// AES 256 has been used for encryption.
/// </summary>
Aes256 = 0x6610,
/// <summary>
/// RC2 corrected has been used for encryption.
/// </summary>
RC2Corrected = 0x6702,
/// <summary>
/// Blowfish has been used for encryption.
/// </summary>
Blowfish = 0x6720,
/// <summary>
/// Twofish has been used for encryption.
/// </summary>
Twofish = 0x6721,
/// <summary>
/// RC4 has been used for encryption.
/// </summary>
RC4 = 0x6801,
/// <summary>
/// An unknown algorithm has been used for encryption.
/// </summary>
Unknown = 0xffff
}
/// <summary>
/// Defines the contents of the general bit flags field for an archive entry.
/// </summary>
[Flags]
public enum GeneralBitFlags
{
/// <summary>
/// Bit 0 if set indicates that the file is encrypted
/// </summary>
Encrypted = 0x0001,
/// <summary>
/// Bits 1 and 2 - Two bits defining the compression method (only for Method 6 Imploding and 8,9 Deflating)
/// </summary>
Method = 0x0006,
/// <summary>
/// Bit 3 if set indicates a trailing data desciptor is appended to the entry data
/// </summary>
Descriptor = 0x0008,
/// <summary>
/// Bit 4 is reserved for use with method 8 for enhanced deflation
/// </summary>
ReservedPKware4 = 0x0010,
/// <summary>
/// Bit 5 if set indicates the file contains Pkzip compressed patched data.
/// Requires version 2.7 or greater.
/// </summary>
Patched = 0x0020,
/// <summary>
/// Bit 6 if set indicates strong encryption has been used for this entry.
/// </summary>
StrongEncryption = 0x0040,
/// <summary>
/// Bit 7 is currently unused
/// </summary>
Unused7 = 0x0080,
/// <summary>
/// Bit 8 is currently unused
/// </summary>
Unused8 = 0x0100,
/// <summary>
/// Bit 9 is currently unused
/// </summary>
Unused9 = 0x0200,
/// <summary>
/// Bit 10 is currently unused
/// </summary>
Unused10 = 0x0400,
/// <summary>
/// Bit 11 if set indicates the filename and
/// comment fields for this file must be encoded using UTF-8.
/// </summary>
UnicodeText = 0x0800,
/// <summary>
/// Bit 12 is documented as being reserved by PKware for enhanced compression.
/// </summary>
EnhancedCompress = 0x1000,
/// <summary>
/// Bit 13 if set indicates that values in the local header are masked to hide
/// their actual values, and the central directory is encrypted.
/// </summary>
/// <remarks>
/// Used when encrypting the central directory contents.
/// </remarks>
HeaderMasked = 0x2000,
/// <summary>
/// Bit 14 is documented as being reserved for use by PKware
/// </summary>
ReservedPkware14 = 0x4000,
/// <summary>
/// Bit 15 is documented as being reserved for use by PKware
/// </summary>
ReservedPkware15 = 0x8000
}
#endregion
/// <summary>
/// This class contains constants used for Zip format files
/// </summary>
public sealed class ZipConstants
{
#region Versions
/// <summary>
/// The version made by field for entries in the central header when created by this library
/// </summary>
/// <remarks>
/// This is also the Zip version for the library when comparing against the version required to extract
/// for an entry. See <see cref="ZipEntry.CanDecompress"/>.
/// </remarks>
public const int VersionMadeBy = 51; // was 45 before AES
/// <summary>
/// The version made by field for entries in the central header when created by this library
/// </summary>
/// <remarks>
/// This is also the Zip version for the library when comparing against the version required to extract
/// for an entry. See ZipInputStream.CanDecompressEntry.
/// </remarks>
[Obsolete("Use VersionMadeBy instead")]
public const int VERSION_MADE_BY = 51;
/// <summary>
/// The minimum version required to support strong encryption
/// </summary>
public const int VersionStrongEncryption = 50;
/// <summary>
/// The minimum version required to support strong encryption
/// </summary>
[Obsolete("Use VersionStrongEncryption instead")]
public const int VERSION_STRONG_ENCRYPTION = 50;
/// <summary>
/// Version indicating AES encryption
/// </summary>
public const int VERSION_AES = 51;
/// <summary>
/// The version required for Zip64 extensions (4.5 or higher)
/// </summary>
public const int VersionZip64 = 45;
#endregion
#region Header Sizes
/// <summary>
/// Size of local entry header (excluding variable length fields at end)
/// </summary>
public const int LocalHeaderBaseSize = 30;
/// <summary>
/// Size of local entry header (excluding variable length fields at end)
/// </summary>
[Obsolete("Use LocalHeaderBaseSize instead")]
public const int LOCHDR = 30;
/// <summary>
/// Size of Zip64 data descriptor
/// </summary>
public const int Zip64DataDescriptorSize = 24;
/// <summary>
/// Size of data descriptor
/// </summary>
public const int DataDescriptorSize = 16;
/// <summary>
/// Size of data descriptor
/// </summary>
[Obsolete("Use DataDescriptorSize instead")]
public const int EXTHDR = 16;
/// <summary>
/// Size of central header entry (excluding variable fields)
/// </summary>
public const int CentralHeaderBaseSize = 46;
/// <summary>
/// Size of central header entry
/// </summary>
[Obsolete("Use CentralHeaderBaseSize instead")]
public const int CENHDR = 46;
/// <summary>
/// Size of end of central record (excluding variable fields)
/// </summary>
public const int EndOfCentralRecordBaseSize = 22;
/// <summary>
/// Size of end of central record (excluding variable fields)
/// </summary>
[Obsolete("Use EndOfCentralRecordBaseSize instead")]
public const int ENDHDR = 22;
/// <summary>
/// Size of 'classic' cryptographic header stored before any entry data
/// </summary>
public const int CryptoHeaderSize = 12;
/// <summary>
/// Size of cryptographic header stored before entry data
/// </summary>
[Obsolete("Use CryptoHeaderSize instead")]
public const int CRYPTO_HEADER_SIZE = 12;
#endregion
#region Header Signatures
/// <summary>
/// Signature for local entry header
/// </summary>
public const int LocalHeaderSignature = 'P' | ('K' << 8) | (3 << 16) | (4 << 24);
/// <summary>
/// Signature for local entry header
/// </summary>
[Obsolete("Use LocalHeaderSignature instead")]
public const int LOCSIG = 'P' | ('K' << 8) | (3 << 16) | (4 << 24);
/// <summary>
/// Signature for spanning entry
/// </summary>
public const int SpanningSignature = 'P' | ('K' << 8) | (7 << 16) | (8 << 24);
/// <summary>
/// Signature for spanning entry
/// </summary>
[Obsolete("Use SpanningSignature instead")]
public const int SPANNINGSIG = 'P' | ('K' << 8) | (7 << 16) | (8 << 24);
/// <summary>
/// Signature for temporary spanning entry
/// </summary>
public const int SpanningTempSignature = 'P' | ('K' << 8) | ('0' << 16) | ('0' << 24);
/// <summary>
/// Signature for temporary spanning entry
/// </summary>
[Obsolete("Use SpanningTempSignature instead")]
public const int SPANTEMPSIG = 'P' | ('K' << 8) | ('0' << 16) | ('0' << 24);
/// <summary>
/// Signature for data descriptor
/// </summary>
/// <remarks>
/// This is only used where the length, Crc, or compressed size isnt known when the
/// entry is created and the output stream doesnt support seeking.
/// The local entry cannot be 'patched' with the correct values in this case
/// so the values are recorded after the data prefixed by this header, as well as in the central directory.
/// </remarks>
public const int DataDescriptorSignature = 'P' | ('K' << 8) | (7 << 16) | (8 << 24);
/// <summary>
/// Signature for data descriptor
/// </summary>
/// <remarks>
/// This is only used where the length, Crc, or compressed size isnt known when the
/// entry is created and the output stream doesnt support seeking.
/// The local entry cannot be 'patched' with the correct values in this case
/// so the values are recorded after the data prefixed by this header, as well as in the central directory.
/// </remarks>
[Obsolete("Use DataDescriptorSignature instead")]
public const int EXTSIG = 'P' | ('K' << 8) | (7 << 16) | (8 << 24);
/// <summary>
/// Signature for central header
/// </summary>
[Obsolete("Use CentralHeaderSignature instead")]
public const int CENSIG = 'P' | ('K' << 8) | (1 << 16) | (2 << 24);
/// <summary>
/// Signature for central header
/// </summary>
public const int CentralHeaderSignature = 'P' | ('K' << 8) | (1 << 16) | (2 << 24);
/// <summary>
/// Signature for Zip64 central file header
/// </summary>
public const int Zip64CentralFileHeaderSignature = 'P' | ('K' << 8) | (6 << 16) | (6 << 24);
/// <summary>
/// Signature for Zip64 central file header
/// </summary>
[Obsolete("Use Zip64CentralFileHeaderSignature instead")]
public const int CENSIG64 = 'P' | ('K' << 8) | (6 << 16) | (6 << 24);
/// <summary>
/// Signature for Zip64 central directory locator
/// </summary>
public const int Zip64CentralDirLocatorSignature = 'P' | ('K' << 8) | (6 << 16) | (7 << 24);
/// <summary>
/// Signature for archive extra data signature (were headers are encrypted).
/// </summary>
public const int ArchiveExtraDataSignature = 'P' | ('K' << 8) | (6 << 16) | (7 << 24);
/// <summary>
/// Central header digitial signature
/// </summary>
public const int CentralHeaderDigitalSignature = 'P' | ('K' << 8) | (5 << 16) | (5 << 24);
/// <summary>
/// Central header digitial signature
/// </summary>
[Obsolete("Use CentralHeaderDigitalSignaure instead")]
public const int CENDIGITALSIG = 'P' | ('K' << 8) | (5 << 16) | (5 << 24);
/// <summary>
/// End of central directory record signature
/// </summary>
public const int EndOfCentralDirectorySignature = 'P' | ('K' << 8) | (5 << 16) | (6 << 24);
/// <summary>
/// End of central directory record signature
/// </summary>
[Obsolete("Use EndOfCentralDirectorySignature instead")]
public const int ENDSIG = 'P' | ('K' << 8) | (5 << 16) | (6 << 24);
#endregion
/// <remarks>
/// The original Zip specification (https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT) states
/// that file names should only be encoded with IBM Code Page 437 or UTF-8.
/// In practice, most zip apps use OEM or system encoding (typically cp437 on Windows).
/// Let's be good citizens and default to UTF-8 http://utf8everywhere.org/
/// </remarks>
static int defaultCodePage = Encoding.UTF8.CodePage;
/// <summary>
/// Default encoding used for string conversion. 0 gives the default system OEM code page.
/// Using the default code page isnt the full solution neccessarily
/// there are many variable factors, codepage 850 is often a good choice for
/// European users, however be careful about compatability.
/// </summary>
public static int DefaultCodePage {
get {
return defaultCodePage;
}
set {
if ((value < 0) || (value > 65535) ||
(value == 1) || (value == 2) || (value == 3) || (value == 42)) {
throw new ArgumentOutOfRangeException("value");
}
defaultCodePage = value;
}
}
/// <summary>
/// Convert a portion of a byte array to a string.
/// </summary>
/// <param name="data">
/// Data to convert to string
/// </param>
/// <param name="count">
/// Number of bytes to convert starting from index 0
/// </param>
/// <returns>
/// data[0]..data[count - 1] converted to a string
/// </returns>
public static string ConvertToString(byte[] data, int count)
{
if (data == null) {
return string.Empty;
}
return Encoding.GetEncoding(DefaultCodePage).GetString(data, 0, count);
}
/// <summary>
/// Convert a byte array to string
/// </summary>
/// <param name="data">
/// Byte array to convert
/// </param>
/// <returns>
/// <paramref name="data">data</paramref>converted to a string
/// </returns>
public static string ConvertToString(byte[] data)
{
if (data == null) {
return string.Empty;
}
return ConvertToString(data, data.Length);
}
/// <summary>
/// Convert a byte array to string
/// </summary>
/// <param name="flags">The applicable general purpose bits flags</param>
/// <param name="data">
/// Byte array to convert
/// </param>
/// <param name="count">The number of bytes to convert.</param>
/// <returns>
/// <paramref name="data">data</paramref>converted to a string
/// </returns>
public static string ConvertToStringExt(int flags, byte[] data, int count)
{
if (data == null) {
return string.Empty;
}
if ((flags & (int)GeneralBitFlags.UnicodeText) != 0) {
return Encoding.UTF8.GetString(data, 0, count);
} else {
return ConvertToString(data, count);
}
}
/// <summary>
/// Convert a byte array to string
/// </summary>
/// <param name="data">
/// Byte array to convert
/// </param>
/// <param name="flags">The applicable general purpose bits flags</param>
/// <returns>
/// <paramref name="data">data</paramref>converted to a string
/// </returns>
public static string ConvertToStringExt(int flags, byte[] data)
{
if (data == null) {
return string.Empty;
}
if ((flags & (int)GeneralBitFlags.UnicodeText) != 0) {
return Encoding.UTF8.GetString(data, 0, data.Length);
} else {
return ConvertToString(data, data.Length);
}
}
/// <summary>
/// Convert a string to a byte array
/// </summary>
/// <param name="str">
/// String to convert to an array
/// </param>
/// <returns>Converted array</returns>
public static byte[] ConvertToArray(string str)
{
if (str == null) {
return new byte[0];
}
return Encoding.GetEncoding(DefaultCodePage).GetBytes(str);
}
/// <summary>
/// Convert a string to a byte array
/// </summary>
/// <param name="flags">The applicable <see cref="GeneralBitFlags">general purpose bits flags</see></param>
/// <param name="str">
/// String to convert to an array
/// </param>
/// <returns>Converted array</returns>
public static byte[] ConvertToArray(int flags, string str)
{
if (str == null) {
return new byte[0];
}
if ((flags & (int)GeneralBitFlags.UnicodeText) != 0) {
return Encoding.UTF8.GetBytes(str);
} else {
return ConvertToArray(str);
}
}
/// <summary>
/// Initialise default instance of <see cref="ZipConstants">ZipConstants</see>
/// </summary>
/// <remarks>
/// Private to prevent instances being created.
/// </remarks>
ZipConstants()
{
// Do nothing
}
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2011 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit wiki.developer.mindtouch.com;
* please review the licensing section.
*
* 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.Diagnostics;
using System.IO;
using System.Threading;
using log4net;
using MindTouch.IO;
using MindTouch.Tasking;
using MindTouch.Web;
using MindTouch.Xml;
using NUnit.Framework;
using MindTouch.Extensions.Time;
namespace MindTouch.Dream.Test {
using Yield = IEnumerator<IYield>;
[TestFixture]
public class PlugTests {
//--- Class Fields ---
private static readonly ILog _log = LogUtils.CreateLog();
[TearDown]
public void Teardown() {
MockPlug.DeregisterAll();
}
[Test]
public void With_and_without_cookiejar() {
DreamCookie global = new DreamCookie("test", "global", new XUri("http://baz.com/foo"));
List<DreamCookie> globalCollection = new List<DreamCookie>();
globalCollection.Add(global);
Plug.GlobalCookies.Update(globalCollection, null);
DreamCookie local = new DreamCookie("test", "local", new XUri("http://baz.com/foo"));
List<DreamCookie> localCollection = new List<DreamCookie>();
localCollection.Add(local);
DreamCookieJar localJar = new DreamCookieJar();
localJar.Update(localCollection, null);
Plug globalPlug = Plug.New("http://baz.com/foo/bar");
Plug localPlug = globalPlug.WithCookieJar(localJar);
Plug globalPlug2 = localPlug.WithoutCookieJar();
Assert.AreEqual("global", globalPlug.CookieJar.Fetch(globalPlug.Uri)[0].Value);
Assert.AreEqual("local", localPlug.CookieJar.Fetch(localPlug.Uri)[0].Value);
Assert.AreEqual("global", globalPlug2.CookieJar.Fetch(globalPlug2.Uri)[0].Value);
}
[Test]
public void Get_via_exthttp_hits_dream_over_wire() {
using(var hostInfo = DreamTestHelper.CreateRandomPortHost()) {
var mock = MockService.CreateMockService(hostInfo);
mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
if(string.IsNullOrEmpty(request.Headers.DreamPublicUri)) {
throw new DreamBadRequestException(string.Format("got origin header '{0}', indicating we didn't arrive via local://", request.Headers.DreamOrigin));
}
response.Return(DreamMessage.Ok());
};
var r = Plug.New(mock.AtLocalHost.Uri.WithScheme("ext-http")).GetAsync().Wait();
Assert.IsTrue(r.IsSuccessful, r.HasDocument ? r.ToDocument()["message"].AsText : "request failed: " + r.Status);
}
}
[Test]
public void Get_via_http_hits_dream_via_local_pathway() {
using(var hostInfo = DreamTestHelper.CreateRandomPortHost()) {
var mock = MockService.CreateMockService(hostInfo);
mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
if(!string.IsNullOrEmpty(request.Headers.DreamPublicUri)) {
throw new DreamBadRequestException(string.Format("got origin header '{0}', indicating we didn't arrive via local://", request.Headers.DreamOrigin));
}
response.Return(DreamMessage.Ok());
};
var r = mock.AtLocalHost.GetAsync().Wait();
Assert.IsTrue(r.IsSuccessful, r.HasDocument ? r.ToDocument()["message"].AsText : "request failed: " + r.Status);
}
}
[Test]
public void Get_via_exthttp_and_AutoRedirect_off_shows_302() {
using(var hostInfo = DreamTestHelper.CreateRandomPortHost()) {
var mock = MockService.CreateMockService(hostInfo);
var redirectCalled = 0;
var redirectUri = new XUri("mock://foo/bar");
mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
var msg = "nothing here";
if(context.Uri.LastSegment == "redirect") {
_log.Debug("called redirect");
redirectCalled++;
response.Return(DreamMessage.Redirect(redirectUri));
return;
}
_log.DebugFormat("called uri: {0} => {1}", context.Uri, msg);
response.Return(DreamMessage.NotFound(msg));
};
var uri = mock.AtLocalHost.Uri.WithScheme("ext-http").At("redirect");
_log.DebugFormat("calling redirect service at {0}", uri);
var r = Plug.New(uri).WithHeader("h", "y").WithoutAutoRedirects().GetAsync().Wait();
Assert.AreEqual(DreamStatus.Found, r.Status, r.HasDocument ? r.ToDocument()["message"].AsText : "request failed: " + r.Status);
Assert.AreEqual(1, redirectCalled, "redirect called incorrectly");
Assert.AreEqual(redirectUri.ToString(), r.Headers.Location.ToString());
}
}
[Test]
public void Get_via_exthttp_follows_301_and_forwards_headers() {
using(var hostInfo = DreamTestHelper.CreateRandomPortHost()) {
var mock = MockService.CreateMockService(hostInfo);
var redirectCalled = 0;
var targetCalled = 0;
mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
var msg = "nothing here";
var h = request.Headers["h"];
if(context.Uri.LastSegment == "redirect") {
_log.Debug("called redirect");
if(h == "y") {
redirectCalled++;
var headers = new DreamHeaders();
headers.Add(DreamHeaders.LOCATION, context.Service.Self.Uri.At("target").AsPublicUri().ToString());
response.Return(new DreamMessage(DreamStatus.MovedPermanently, headers));
return;
}
msg = "redirect request lacked header";
}
if(context.Uri.LastSegment == "target") {
_log.Debug("called target");
if(h == "y") {
_log.Debug("target request had header");
targetCalled++;
response.Return(DreamMessage.Ok());
return;
}
msg = "target request lacked header ({1}";
}
_log.DebugFormat("called uri: {0} => {1}", context.Uri, msg);
response.Return(DreamMessage.NotFound(msg));
};
var uri = mock.AtLocalHost.Uri.WithScheme("ext-http").At("redirect");
_log.DebugFormat("calling redirect service at {0}", uri);
var r = Plug.New(uri).WithHeader("h", "y").GetAsync().Wait();
Assert.IsTrue(r.IsSuccessful, r.HasDocument ? r.ToDocument()["message"].AsText : "request failed: " + r.Status);
Assert.AreEqual(1, redirectCalled, "redirect called incorrectly");
Assert.AreEqual(1, targetCalled, "target called incorrectly");
}
}
[Test]
public void Get_via_exthttp_follows_301_but_expects_query_to_be_in_location() {
using(var hostInfo = DreamTestHelper.CreateRandomPortHost()) {
var mock = MockService.CreateMockService(hostInfo);
var redirectCalled = 0;
var targetCalled = 0;
mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
var msg = "nothing here";
var q = context.Uri.GetParam("q");
var forward = context.Uri.GetParam("forward");
if(context.Uri.LastSegment == "redirect") {
_log.Debug("called redirect");
var redirect = context.Service.Self.Uri.At("target").AsPublicUri();
if(forward == "true") {
redirect = redirect.With("q", q);
}
redirectCalled++;
var headers = new DreamHeaders();
headers.Add(DreamHeaders.LOCATION, redirect.ToString());
response.Return(new DreamMessage(DreamStatus.MovedPermanently, headers));
return;
}
if(context.Uri.LastSegment == "target") {
_log.Debug("called target");
if(q == "x") {
_log.Debug("target request had query");
targetCalled++;
response.Return(DreamMessage.Ok());
return;
}
response.Return(DreamMessage.BadRequest("missing query param"));
return;
}
_log.DebugFormat("called uri: {0} => {1}", context.Uri, msg);
response.Return(DreamMessage.NotFound(msg));
};
var uri = mock.AtLocalHost.Uri.WithScheme("ext-http").At("redirect");
_log.DebugFormat("calling redirect service at {0}", uri);
var r = Plug.New(uri).With("q", "x").GetAsync().Wait();
Assert.AreEqual(DreamStatus.BadRequest, r.Status);
Assert.AreEqual(1, redirectCalled, "redirect without forward called incorrectly");
Assert.AreEqual(0, targetCalled, "target without forward called incorrectly");
redirectCalled = 0;
targetCalled = 0;
r = Plug.New(uri).With("q", "x").With("forward", "true").GetAsync().Wait();
Assert.IsTrue(r.IsSuccessful, r.HasDocument ? r.ToDocument()["message"].AsText : "request failed: " + r.Status);
Assert.AreEqual(1, redirectCalled, "redirect with forward called incorrectly");
Assert.AreEqual(1, targetCalled, "target with forward called incorrectly");
}
}
[Test]
public void Get_via_exthttp_follows_302_and_forwards_headers() {
using(var hostInfo = DreamTestHelper.CreateRandomPortHost()) {
var mock = MockService.CreateMockService(hostInfo);
var redirectCalled = 0;
var targetCalled = 0;
mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
var msg = "nothing here";
var h = request.Headers["h"];
if(context.Uri.LastSegment == "redirect") {
_log.Debug("called redirect");
if(h == "y") {
redirectCalled++;
response.Return(DreamMessage.Redirect(context.Service.Self.Uri.At("target").AsPublicUri()));
return;
}
msg = "redirect request lacked header";
}
if(context.Uri.LastSegment == "target") {
_log.Debug("called target");
if(h == "y") {
_log.Debug("target request had header");
targetCalled++;
response.Return(DreamMessage.Ok());
return;
}
msg = "target request lacked header ({1}";
}
_log.DebugFormat("called uri: {0} => {1}", context.Uri, msg);
response.Return(DreamMessage.NotFound(msg));
};
var uri = mock.AtLocalHost.Uri.WithScheme("ext-http").At("redirect");
_log.DebugFormat("calling redirect service at {0}", uri);
var r = Plug.New(uri).WithHeader("h", "y").GetAsync().Wait();
Assert.IsTrue(r.IsSuccessful, r.HasDocument ? r.ToDocument()["message"].AsText : "request failed: " + r.Status);
Assert.AreEqual(1, redirectCalled, "redirect called incorrectly");
Assert.AreEqual(1, targetCalled, "target called incorrectly");
}
}
[Test]
public void Get_via_exthttp_follows_but_expects_query_to_be_in_location() {
using(var hostInfo = DreamTestHelper.CreateRandomPortHost()) {
var mock = MockService.CreateMockService(hostInfo);
var redirectCalled = 0;
var targetCalled = 0;
mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
var msg = "nothing here";
var q = context.Uri.GetParam("q");
var forward = context.Uri.GetParam("forward");
if(context.Uri.LastSegment == "redirect") {
_log.Debug("called redirect");
var redirect = context.Service.Self.Uri.At("target").AsPublicUri();
if(forward == "true") {
redirect = redirect.With("q", q);
}
redirectCalled++;
response.Return(DreamMessage.Redirect(redirect));
return;
}
if(context.Uri.LastSegment == "target") {
_log.Debug("called target");
if(q == "x") {
_log.Debug("target request had query");
targetCalled++;
response.Return(DreamMessage.Ok());
return;
}
response.Return(DreamMessage.BadRequest("missing query param"));
return;
}
_log.DebugFormat("called uri: {0} => {1}", context.Uri, msg);
response.Return(DreamMessage.NotFound(msg));
};
var uri = mock.AtLocalHost.Uri.WithScheme("ext-http").At("redirect");
_log.DebugFormat("calling redirect service at {0}", uri);
var r = Plug.New(uri).With("q", "x").GetAsync().Wait();
Assert.AreEqual(DreamStatus.BadRequest, r.Status);
Assert.AreEqual(1, redirectCalled, "redirect without forward called incorrectly");
Assert.AreEqual(0, targetCalled, "target without forward called incorrectly");
redirectCalled = 0;
targetCalled = 0;
r = Plug.New(uri).With("q", "x").With("forward", "true").GetAsync().Wait();
Assert.IsTrue(r.IsSuccessful, r.HasDocument ? r.ToDocument()["message"].AsText : "request failed: " + r.Status);
Assert.AreEqual(1, redirectCalled, "redirect with forward called incorrectly");
Assert.AreEqual(1, targetCalled, "target with forward called incorrectly");
}
}
[Test]
public void Get_via_internal_routing_and_AutoRedirect_off_shows_302() {
using(var hostInfo = DreamTestHelper.CreateRandomPortHost()) {
var mock = MockService.CreateMockService(hostInfo);
var redirectCalled = 0;
var redirectUri = new XUri("mock://foo/bar");
mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
var msg = "nothing here";
if(context.Uri.LastSegment == "redirect") {
_log.Debug("called redirect");
redirectCalled++;
response.Return(DreamMessage.Redirect(redirectUri));
return;
}
_log.DebugFormat("called uri: {0} => {1}", context.Uri, msg);
response.Return(DreamMessage.NotFound(msg));
};
var uri = mock.AtLocalMachine.At("redirect");
_log.DebugFormat("calling redirect service at {0}", uri);
var r = Plug.New(uri).WithHeader("h", "y").WithoutAutoRedirects().GetAsync().Wait();
Assert.AreEqual(DreamStatus.Found, r.Status, r.HasDocument ? r.ToDocument()["message"].AsText : "request failed: " + r.Status);
Assert.AreEqual(1, redirectCalled, "redirect called incorrectly");
Assert.AreEqual(redirectUri.ToString(), r.Headers.Location.ToString());
}
}
[Test]
public void Get_via_internal_routing_follows_301_and_forwards_headers() {
using(var hostInfo = DreamTestHelper.CreateRandomPortHost()) {
var mock = MockService.CreateMockService(hostInfo);
var redirectCalled = 0;
var targetCalled = 0;
mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
var msg = "nothing here";
var h = request.Headers["h"];
if(context.Uri.LastSegment == "redirect") {
_log.Debug("called redirect");
if(h == "y") {
redirectCalled++;
var headers = new DreamHeaders();
headers.Add(DreamHeaders.LOCATION, context.Service.Self.Uri.At("target").AsPublicUri().ToString());
response.Return(new DreamMessage(DreamStatus.MovedPermanently, headers));
return;
}
msg = "redirect request lacked header";
}
if(context.Uri.LastSegment == "target") {
_log.Debug("called target");
if(h == "y") {
_log.Debug("target request had header");
targetCalled++;
response.Return(DreamMessage.Ok());
return;
}
msg = "target request lacked header ({1}";
}
_log.DebugFormat("called uri: {0} => {1}", context.Uri, msg);
response.Return(DreamMessage.NotFound(msg));
};
var uri = mock.AtLocalMachine.At("redirect");
_log.DebugFormat("calling redirect service at {0}", uri);
var r = Plug.New(uri).WithHeader("h", "y").GetAsync().Wait();
Assert.IsTrue(r.IsSuccessful, r.HasDocument ? r.ToDocument()["message"].AsText : "request failed: " + r.Status);
Assert.AreEqual(1, redirectCalled, "redirect called incorrectly");
Assert.AreEqual(1, targetCalled, "target called incorrectly");
}
}
[Test]
public void Get_via_internal_routing_follows_301_but_expects_query_to_be_in_location() {
using(var hostInfo = DreamTestHelper.CreateRandomPortHost()) {
var mock = MockService.CreateMockService(hostInfo);
var redirectCalled = 0;
var targetCalled = 0;
mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
var msg = "nothing here";
var q = context.Uri.GetParam("q");
var forward = context.Uri.GetParam("forward");
if(context.Uri.LastSegment == "redirect") {
_log.Debug("called redirect");
var redirect = context.Service.Self.Uri.At("target").AsPublicUri();
if(forward == "true") {
redirect = redirect.With("q", q);
}
redirectCalled++;
var headers = new DreamHeaders();
headers.Add(DreamHeaders.LOCATION, redirect.ToString());
response.Return(new DreamMessage(DreamStatus.MovedPermanently, headers));
return;
}
if(context.Uri.LastSegment == "target") {
_log.Debug("called target");
if(q == "x") {
_log.Debug("target request had query");
targetCalled++;
response.Return(DreamMessage.Ok());
return;
}
response.Return(DreamMessage.BadRequest("missing query param"));
return;
}
_log.DebugFormat("called uri: {0} => {1}", context.Uri, msg);
response.Return(DreamMessage.NotFound(msg));
};
var uri = mock.AtLocalMachine.At("redirect");
_log.DebugFormat("calling redirect service at {0}", uri);
var r = Plug.New(uri).With("q", "x").GetAsync().Wait();
Assert.AreEqual(DreamStatus.BadRequest, r.Status);
Assert.AreEqual(1, redirectCalled, "redirect without forward called incorrectly");
Assert.AreEqual(0, targetCalled, "target without forward called incorrectly");
redirectCalled = 0;
targetCalled = 0;
r = Plug.New(uri).With("q", "x").With("forward", "true").GetAsync().Wait();
Assert.IsTrue(r.IsSuccessful, r.HasDocument ? r.ToDocument()["message"].AsText : "request failed: " + r.Status);
Assert.AreEqual(1, redirectCalled, "redirect with forward called incorrectly");
Assert.AreEqual(1, targetCalled, "target with forward called incorrectly");
}
}
[Test]
public void Get_via_internal_routing_follows_302_and_forwards_headers() {
using(var hostInfo = DreamTestHelper.CreateRandomPortHost()) {
var mock = MockService.CreateMockService(hostInfo);
var redirectCalled = 0;
var targetCalled = 0;
mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
var msg = "nothing here";
var h = request.Headers["h"];
if(context.Uri.LastSegment == "redirect") {
_log.Debug("called redirect");
if(h == "y") {
redirectCalled++;
response.Return(DreamMessage.Redirect(context.Service.Self.Uri.At("target").AsPublicUri()));
return;
}
msg = "redirect request lacked header";
}
if(context.Uri.LastSegment == "target") {
_log.Debug("called target");
if(h == "y") {
_log.Debug("target request had header");
targetCalled++;
response.Return(DreamMessage.Ok());
return;
}
msg = "target request lacked header ({1}";
}
_log.DebugFormat("called uri: {0} => {1}", context.Uri, msg);
response.Return(DreamMessage.NotFound(msg));
};
var uri = mock.AtLocalMachine.At("redirect");
_log.DebugFormat("calling redirect service at {0}", uri);
var r = Plug.New(uri).WithHeader("h", "y").GetAsync().Wait();
Assert.IsTrue(r.IsSuccessful, r.HasDocument ? r.ToDocument()["message"].AsText : "request failed: " + r.Status);
Assert.AreEqual(1, redirectCalled, "redirect called incorrectly");
Assert.AreEqual(1, targetCalled, "target called incorrectly");
}
}
[Test]
public void Get_via_internal_routing_follows_but_expects_query_to_be_in_location() {
using(var hostInfo = DreamTestHelper.CreateRandomPortHost()) {
var mock = MockService.CreateMockService(hostInfo);
var redirectCalled = 0;
var targetCalled = 0;
mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
var msg = "nothing here";
var q = context.Uri.GetParam("q");
var forward = context.Uri.GetParam("forward");
if(context.Uri.LastSegment == "redirect") {
_log.Debug("called redirect");
var redirect = context.Service.Self.Uri.At("target").AsPublicUri();
if(forward == "true") {
redirect = redirect.With("q", q);
}
redirectCalled++;
response.Return(DreamMessage.Redirect(redirect));
return;
}
if(context.Uri.LastSegment == "target") {
_log.Debug("called target");
if(q == "x") {
_log.Debug("target request had query");
targetCalled++;
response.Return(DreamMessage.Ok());
return;
}
response.Return(DreamMessage.BadRequest("missing query param"));
return;
}
_log.DebugFormat("called uri: {0} => {1}", context.Uri, msg);
response.Return(DreamMessage.NotFound(msg));
};
var uri = mock.AtLocalMachine.At("redirect");
_log.DebugFormat("calling redirect service at {0}", uri);
var r = Plug.New(uri).With("q", "x").GetAsync().Wait();
Assert.AreEqual(DreamStatus.BadRequest, r.Status);
Assert.AreEqual(1, redirectCalled, "redirect without forward called incorrectly");
Assert.AreEqual(0, targetCalled, "target without forward called incorrectly");
redirectCalled = 0;
targetCalled = 0;
r = Plug.New(uri).With("q", "x").With("forward", "true").GetAsync().Wait();
Assert.IsTrue(r.IsSuccessful, r.HasDocument ? r.ToDocument()["message"].AsText : "request failed: " + r.Status);
Assert.AreEqual(1, redirectCalled, "redirect with forward called incorrectly");
Assert.AreEqual(1, targetCalled, "target with forward called incorrectly");
}
}
[Test]
public void New_plug_gets_default_redirects() {
Assert.AreEqual(Plug.DEFAULT_MAX_AUTO_REDIRECTS, Plug.New("http://foo/").MaxAutoRedirects);
}
[Test]
public void AutoRedirect_only_follows_specified_times() {
using(var hostInfo = DreamTestHelper.CreateRandomPortHost()) {
var mock = MockService.CreateMockService(hostInfo);
var totalCalls = 0;
mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
totalCalls++;
_log.DebugFormat("call {0} to redirect", totalCalls);
response.Return(DreamMessage.Redirect(context.Uri.WithoutQuery().With("c", totalCalls.ToString())));
};
var uri = mock.AtLocalMachine.At("redirect");
var redirects = 10;
var expectedCalls = redirects + 1;
var r = Plug.New(uri).WithAutoRedirects(10).GetAsync().Wait();
Assert.AreEqual(DreamStatus.Found, r.Status);
Assert.AreEqual(expectedCalls, totalCalls, "redirect without forward called incorrectly");
Assert.AreEqual(uri.With("c", expectedCalls.ToString()).ToString(), r.Headers.Location.ToString());
}
}
[Ignore("need to run by hand.. test is too slow for regular execution")]
[Test]
public void Upload_a_bunch_of_large_files_via_local___SLOW_TEST() {
Upload_Files(true);
}
[Ignore("need to run by hand.. test is too slow for regular execution")]
[Test]
public void Upload_a_bunch_of_large_files_via_http___SLOW_TEST() {
Upload_Files(false);
}
[Test]
public void Plug_uses_own_timeout_to_govern_request_and_results_in_RequestConnectionTimeout() {
MockPlug.Register(new XUri("mock://mock"), (plug, verb, uri, request, response) => {
Thread.Sleep(TimeSpan.FromSeconds(10));
response.Return(DreamMessage.Ok());
});
var stopwatch = Stopwatch.StartNew();
var r = Plug.New(MockPlug.DefaultUri)
.WithTimeout(TimeSpan.FromSeconds(1))
.InvokeEx(Verb.GET, DreamMessage.Ok(), new Result<DreamMessage>(TimeSpan.MaxValue)).Block();
stopwatch.Stop();
Assert.LessOrEqual(stopwatch.Elapsed.Seconds, 2);
Assert.IsFalse(r.HasTimedOut);
Assert.IsFalse(r.HasException);
Assert.AreEqual(DreamStatus.RequestConnectionTimeout, r.Value.Status);
}
[Test]
public void Result_timeout_superceeds_plug_timeout_and_results_in_RequestConnectionTimeout() {
MockPlug.Register(new XUri("mock://mock"), (plug, verb, uri, request, response) => {
Thread.Sleep(TimeSpan.FromSeconds(10));
response.Return(DreamMessage.Ok());
});
var stopwatch = Stopwatch.StartNew();
var r = Plug.New(MockPlug.DefaultUri)
.WithTimeout(TimeSpan.FromSeconds(20))
.InvokeEx(Verb.GET, DreamMessage.Ok(), new Result<DreamMessage>(1.Seconds())).Block();
stopwatch.Stop();
Assert.LessOrEqual(stopwatch.Elapsed.Seconds, 2);
Assert.IsFalse(r.HasTimedOut);
Assert.IsFalse(r.HasException);
Assert.AreEqual(DreamStatus.RequestConnectionTimeout, r.Value.Status);
}
[Test]
public void Plug_timeout_is_not_used_for_message_memorization() {
var blockingStream = new MockBlockingStream();
MockPlug.Register(new XUri("mock://mock"), (plug, verb, uri, request, response) => {
_log.Debug("returning blocking stream");
response.Return(new DreamMessage(DreamStatus.Ok, null, MimeType.TEXT, -1, blockingStream));
});
var stopwatch = Stopwatch.StartNew();
var msg = Plug.New(MockPlug.DefaultUri)
.WithTimeout(TimeSpan.FromSeconds(1))
.InvokeEx(Verb.GET, DreamMessage.Ok(), new Result<DreamMessage>()).Wait();
stopwatch.Stop();
_log.Debug("completed request");
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.LessOrEqual(stopwatch.Elapsed.Seconds, 1);
stopwatch = Stopwatch.StartNew();
_log.Debug("memorizing request");
var r = msg.Memorize(new Result(1.Seconds())).Block();
stopwatch.Stop();
blockingStream.Unblock();
_log.Debug("completed request memorization");
Assert.LessOrEqual(stopwatch.Elapsed.Seconds, 2);
Assert.IsTrue(r.HasTimedOut);
}
[Test]
public void Result_timeout_is_used_for_message_memorization_and_results_in_ResponseDataTransferTimeout() {
var blockingStream = new MockBlockingStream();
MockPlug.Register(new XUri("mock://mock"), (plug, verb, uri, request, response) => {
_log.Debug("returning blocking stream");
response.Return(new DreamMessage(DreamStatus.Ok, null, MimeType.TEXT, -1, blockingStream));
});
var stopwatch = Stopwatch.StartNew();
_log.Debug("calling plug");
var r = Plug.New(MockPlug.DefaultUri)
.WithTimeout(1.Seconds())
.Get(new Result<DreamMessage>(3.Seconds())).Block();
_log.Debug("plug done");
stopwatch.Stop();
blockingStream.Unblock();
Assert.GreaterOrEqual(stopwatch.Elapsed.Seconds, 3);
Assert.LessOrEqual(stopwatch.Elapsed.Seconds, 4);
Assert.IsFalse(r.HasTimedOut);
Assert.IsFalse(r.HasException);
Assert.AreEqual(DreamStatus.ResponseDataTransferTimeout, r.Value.Status);
}
[Test]
public void Plug_timeout_on_request_returns_RequestConnectionTimeout_not_ResponseDataTransferTimeout() {
var blockingStream = new MockBlockingStream();
MockPlug.Register(new XUri("mock://mock"), (plug, verb, uri, request, response) => {
_log.Debug("blocking request");
Thread.Sleep(5.Seconds());
_log.Debug("returning blocking stream");
response.Return(new DreamMessage(DreamStatus.Ok, null, MimeType.TEXT, -1, blockingStream));
});
var stopwatch = Stopwatch.StartNew();
_log.Debug("calling plug");
var r = Plug.New(MockPlug.DefaultUri)
.WithTimeout(1.Seconds())
.Get(new Result<DreamMessage>(5.Seconds())).Block();
_log.Debug("plug done");
stopwatch.Stop();
blockingStream.Unblock();
Assert.GreaterOrEqual(stopwatch.Elapsed.Seconds, 1);
Assert.LessOrEqual(stopwatch.Elapsed.Seconds, 3);
Assert.IsFalse(r.HasTimedOut);
Assert.IsFalse(r.HasException);
Assert.AreEqual(DreamStatus.RequestConnectionTimeout, r.Value.Status);
}
[Test]
public void Can_use_Plug_extension_to_return_document_result() {
var autoMockPlug = MockPlug.Register(new XUri("mock://mock"));
autoMockPlug.Expect().Verb("GET").Response(DreamMessage.Ok(new XDoc("works")));
Assert.AreEqual("works", Plug.New("mock://mock").Get(new Result<XDoc>()).Wait().Name);
}
[Test]
public void Plug_extension_to_return_document_sets_exception_on_non_OK_response() {
var autoMockPlug = MockPlug.Register(new XUri("mock://mock"));
autoMockPlug.Expect().Verb("GET").Response(DreamMessage.BadRequest("bad puppy"));
var r = Plug.New("mock://mock").Get(new Result<XDoc>()).Block();
Assert.IsTrue(r.HasException);
Assert.AreEqual(typeof(DreamResponseException), r.Exception.GetType());
Assert.AreEqual(DreamStatus.BadRequest, ((DreamResponseException)r.Exception).Response.Status);
}
[Test]
public void Can_append_trailing_slash() {
var plug = Plug.New("http://foo/bar").WithTrailingSlash();
Assert.IsTrue(plug.Uri.TrailingSlash);
Assert.AreEqual("http://foo/bar/", plug.ToString());
}
[Test]
public void WithTrailingSlash_only_adds_when_needed() {
var plug = Plug.New("http://foo/bar/");
Assert.IsTrue(plug.Uri.TrailingSlash);
plug = plug.WithTrailingSlash();
Assert.IsTrue(plug.Uri.TrailingSlash);
Assert.AreEqual("http://foo/bar/", plug.ToString());
}
[Test]
public void Can_remove_trailing_slash() {
var plug = Plug.New("http://foo/bar/").WithoutTrailingSlash();
Assert.IsFalse(plug.Uri.TrailingSlash);
Assert.AreEqual("http://foo/bar", plug.ToString());
}
[Test]
public void WithoutTrailingSlash_only_removes_when_needed() {
var plug = Plug.New("http://foo/bar");
Assert.IsFalse(plug.Uri.TrailingSlash);
plug = plug.WithoutTrailingSlash();
Assert.IsFalse(plug.Uri.TrailingSlash);
Assert.AreEqual("http://foo/bar", plug.ToString());
}
private void Upload_Files(bool local) {
using(var hostInfo = DreamTestHelper.CreateRandomPortHost()) {
var mock = MockService.CreateMockService(hostInfo);
mock.Service.CatchAllCallbackAsync = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
return Coroutine.Invoke(Upload_Helper, context, request, response);
};
var mockPlug = local
? mock.AtLocalHost
: Plug.New(mock.AtLocalHost.Uri.WithScheme("ext-http")).WithTimeout(TimeSpan.FromMinutes(10));
for(var i = 0; i <= 4; i++) {
Stream stream = new MockAsyncReadableStream(150 * 1024 * 1024);
_log.DebugFormat("uploading {0}", i);
var response = mockPlug.PutAsync(new DreamMessage(DreamStatus.Ok, null, MimeType.BINARY, stream.Length, stream)).Wait();
if(!response.IsSuccessful) {
_log.DebugFormat("upload failed");
Assert.Fail(string.Format("unable to upload: {0}", response.ToText()));
}
}
}
}
private Yield Upload_Helper(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
using(var stream = request.ToStream()) {
var total = 0;
var buffer = new byte[1024 * 1024];
while(total < request.ContentLength) {
Result<int> read;
yield return read = stream.Read(buffer, 0, buffer.Length, new Result<int>());
//int read = stream.Read(buffer, 0, buffer.Length);
if(read.Value == 0) {
break;
}
total += read.Value;
//fake some latency
yield return Async.Sleep(TimeSpan.FromMilliseconds(1));
}
_log.DebugFormat("read {0}/{1} bytes", total, request.ContentLength);
if(total != request.ContentLength) {
throw new DreamBadRequestException(string.Format("was supposed to read {0} bytes, only read {1}", request.ContentLength, total));
}
}
response.Return(DreamMessage.Ok());
}
}
public class MockBlockingStream : Stream {
//--- Class Fields ---
private static readonly ILog _log = LogUtils.CreateLog();
private readonly ManualResetEvent _blockEvent = new ManualResetEvent(false);
private int _readCount;
public override void Flush() { }
public override long Seek(long offset, SeekOrigin origin) {
throw new NotImplementedException();
}
public override void SetLength(long value) { }
public override int Read(byte[] buffer, int offset, int count) {
_readCount++;
if(_readCount > 1) {
return 0;
}
_log.DebugFormat("blocking read {0}", _readCount);
_blockEvent.WaitOne();
return 0;
}
public override void Write(byte[] buffer, int offset, int count) { }
public override bool CanRead { get { return true; } }
public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return false; } }
public override long Length { get { throw new NotImplementedException(); } }
public override long Position {
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public void Unblock() {
_blockEvent.Set();
}
}
public class MockAsyncReadableStream : Stream {
private readonly long _size;
private int _position;
public MockAsyncReadableStream(long size) {
_position = 0;
_size = size;
}
public override bool CanRead { get { return true; } }
public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return false; } }
public override long Length { get { return _size; } }
public override long Position {
get { return _position; }
set { throw new NotImplementedException(); }
}
public override void Flush() { }
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) {
var asyncResult = new MockAsyncResult {
AsyncState = state,
Buffer = buffer,
Count = count,
Offset = offset
};
Async.Fork(() => callback(asyncResult));
return asyncResult;
}
public override int EndRead(IAsyncResult asyncResult) {
// some artificial latency
//Thread.Sleep(1);
var result = (MockAsyncResult)asyncResult;
var read = 0;
for(var i = 0; i < result.Count; i++) {
if(_position == _size) {
return read;
}
result.Buffer[result.Offset + i] = 0;
_position++;
read++;
}
return read;
}
public override long Seek(long offset, SeekOrigin origin) {
throw new NotImplementedException();
}
public override void SetLength(long value) {
throw new NotImplementedException();
}
public override int Read(byte[] buffer, int offset, int count) {
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count) {
throw new NotImplementedException();
}
}
public class MockAsyncResult : IAsyncResult {
public bool IsCompleted { get; set; }
public WaitHandle AsyncWaitHandle { get; set; }
public object AsyncState { get; set; }
public bool CompletedSynchronously { get; set; }
public byte[] Buffer;
public int Offset;
public int Count;
}
}
| |
/*
* 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 log4net;
using Mono.Addins;
using Nini.Config;
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Data;
using OpenSim.Server.Base;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LocalInventoryServicesConnector")]
public class LocalInventoryServicesConnector : ISharedRegionModule, IInventoryService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Scene used by this module. This currently needs to be publicly settable for HGInventoryBroker.
/// </summary>
public Scene Scene { get; set; }
private IInventoryService m_InventoryService;
private IUserManagement m_UserManager;
private IUserManagement UserManager
{
get
{
if (m_UserManager == null)
{
m_UserManager = Scene.RequestModuleInterface<IUserManagement>();
}
return m_UserManager;
}
}
private bool m_Enabled = false;
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "LocalInventoryServicesConnector"; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("InventoryServices", "");
if (name == Name)
{
IConfig inventoryConfig = source.Configs["InventoryService"];
if (inventoryConfig == null)
{
m_log.Error("[LOCAL INVENTORY SERVICES CONNECTOR]: InventoryService missing from OpenSim.ini");
return;
}
string serviceDll = inventoryConfig.GetString("LocalServiceModule", String.Empty);
if (serviceDll == String.Empty)
{
m_log.Error("[LOCAL INVENTORY SERVICES CONNECTOR]: No LocalServiceModule named in section InventoryService");
return;
}
Object[] args = new Object[] { source };
m_log.DebugFormat("[LOCAL INVENTORY SERVICES CONNECTOR]: Service dll = {0}", serviceDll);
m_InventoryService = ServerUtils.LoadPlugin<IInventoryService>(serviceDll, args);
if (m_InventoryService == null)
{
m_log.Error("[LOCAL INVENTORY SERVICES CONNECTOR]: Can't load inventory service");
throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's");
}
m_Enabled = true;
m_log.Info("[LOCAL INVENTORY SERVICES CONNECTOR]: Local inventory connector enabled");
}
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
scene.RegisterModuleInterface<IInventoryService>(this);
if (Scene == null)
Scene = scene;
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
}
#region IInventoryService
public bool CreateUserInventory(UUID user)
{
return m_InventoryService.CreateUserInventory(user);
}
public List<InventoryFolderBase> GetInventorySkeleton(UUID userId)
{
return m_InventoryService.GetInventorySkeleton(userId);
}
public InventoryFolderBase GetRootFolder(UUID userID)
{
return m_InventoryService.GetRootFolder(userID);
}
public InventoryFolderBase GetFolderForType(UUID userID, AssetType type)
{
return m_InventoryService.GetFolderForType(userID, type);
}
public InventoryCollection GetFolderContent(UUID userID, UUID folderID)
{
InventoryCollection invCol = m_InventoryService.GetFolderContent(userID, folderID);
if (UserManager != null)
{
// Protect ourselves against the caller subsequently modifying the items list
List<InventoryItemBase> items = new List<InventoryItemBase>(invCol.Items);
Util.RunThreadNoTimeout(delegate
{
foreach (InventoryItemBase item in items)
if (!string.IsNullOrEmpty(item.CreatorData))
UserManager.AddUser(item.CreatorIdAsUuid, item.CreatorData);
}, "GetFolderContent", null);
}
return invCol;
}
public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID)
{
return m_InventoryService.GetFolderItems(userID, folderID);
}
/// <summary>
/// Add a new folder to the user's inventory
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully added</returns>
public bool AddFolder(InventoryFolderBase folder)
{
return m_InventoryService.AddFolder(folder);
}
/// <summary>
/// Update a folder in the user's inventory
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully updated</returns>
public bool UpdateFolder(InventoryFolderBase folder)
{
return m_InventoryService.UpdateFolder(folder);
}
/// <summary>
/// Move an inventory folder to a new location
/// </summary>
/// <param name="folder">A folder containing the details of the new location</param>
/// <returns>true if the folder was successfully moved</returns>
public bool MoveFolder(InventoryFolderBase folder)
{
return m_InventoryService.MoveFolder(folder);
}
public bool DeleteFolders(UUID ownerID, List<UUID> folderIDs)
{
return m_InventoryService.DeleteFolders(ownerID, folderIDs);
}
/// <summary>
/// Purge an inventory folder of all its items and subfolders.
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully purged</returns>
public bool PurgeFolder(InventoryFolderBase folder)
{
return m_InventoryService.PurgeFolder(folder);
}
public bool AddItem(InventoryItemBase item)
{
// m_log.DebugFormat(
// "[LOCAL INVENTORY SERVICES CONNECTOR]: Adding inventory item {0} to user {1} folder {2}",
// item.Name, item.Owner, item.Folder);
return m_InventoryService.AddItem(item);
}
/// <summary>
/// Update an item in the user's inventory
/// </summary>
/// <param name="item"></param>
/// <returns>true if the item was successfully updated</returns>
public bool UpdateItem(InventoryItemBase item)
{
return m_InventoryService.UpdateItem(item);
}
public bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
{
return m_InventoryService.MoveItems(ownerID, items);
}
/// <summary>
/// Delete an item from the user's inventory
/// </summary>
/// <param name="item"></param>
/// <returns>true if the item was successfully deleted</returns>
public bool DeleteItems(UUID ownerID, List<UUID> itemIDs)
{
return m_InventoryService.DeleteItems(ownerID, itemIDs);
}
public InventoryItemBase GetItem(InventoryItemBase item)
{
// m_log.DebugFormat("[LOCAL INVENTORY SERVICES CONNECTOR]: Requesting inventory item {0}", item.ID);
// UUID requestedItemId = item.ID;
item = m_InventoryService.GetItem(item);
// if (null == item)
// m_log.ErrorFormat(
// "[LOCAL INVENTORY SERVICES CONNECTOR]: Could not find item with id {0}", requestedItemId);
return item;
}
public InventoryFolderBase GetFolder(InventoryFolderBase folder)
{
return m_InventoryService.GetFolder(folder);
}
/// <summary>
/// Does the given user have an inventory structure?
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
public bool HasInventoryForUser(UUID userID)
{
return m_InventoryService.HasInventoryForUser(userID);
}
public List<InventoryItemBase> GetActiveGestures(UUID userId)
{
return m_InventoryService.GetActiveGestures(userId);
}
public int GetAssetPermissions(UUID userID, UUID assetID)
{
return m_InventoryService.GetAssetPermissions(userID, assetID);
}
#endregion IInventoryService
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="Int32Collection.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using MS.Internal.Collections;
using MS.Internal.PresentationCore;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.ComponentModel.Design.Serialization;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Windows.Media.Imaging;
using System.Windows.Markup;
using System.Windows.Media.Converters;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
// These types are aliased to match the unamanaged names used in interop
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;
namespace System.Windows.Media
{
/// <summary>
/// A collection of ints.
/// </summary>
[TypeConverter(typeof(Int32CollectionConverter))]
[ValueSerializer(typeof(Int32CollectionValueSerializer))] // Used by MarkupWriter
public sealed partial class Int32Collection : Freezable, IFormattable, IList, IList<int>
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Shadows inherited Clone() with a strongly typed
/// version for convenience.
/// </summary>
public new Int32Collection Clone()
{
return (Int32Collection)base.Clone();
}
/// <summary>
/// Shadows inherited CloneCurrentValue() with a strongly typed
/// version for convenience.
/// </summary>
public new Int32Collection CloneCurrentValue()
{
return (Int32Collection)base.CloneCurrentValue();
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region IList<T>
/// <summary>
/// Adds "value" to the list
/// </summary>
public void Add(int value)
{
AddHelper(value);
}
/// <summary>
/// Removes all elements from the list
/// </summary>
public void Clear()
{
WritePreamble();
_collection.Clear();
++_version;
WritePostscript();
}
/// <summary>
/// Determines if the list contains "value"
/// </summary>
public bool Contains(int value)
{
ReadPreamble();
return _collection.Contains(value);
}
/// <summary>
/// Returns the index of "value" in the list
/// </summary>
public int IndexOf(int value)
{
ReadPreamble();
return _collection.IndexOf(value);
}
/// <summary>
/// Inserts "value" into the list at the specified position
/// </summary>
public void Insert(int index, int value)
{
WritePreamble();
_collection.Insert(index, value);
++_version;
WritePostscript();
}
/// <summary>
/// Removes "value" from the list
/// </summary>
public bool Remove(int value)
{
WritePreamble();
int index = IndexOf(value);
if (index >= 0)
{
// we already have index from IndexOf so instead of using Remove,
// which will search the collection a second time, we'll use RemoveAt
_collection.RemoveAt(index);
++_version;
WritePostscript();
return true;
}
// Collection_Remove returns true, calls WritePostscript,
// increments version, and does UpdateResource if it succeeds
return false;
}
/// <summary>
/// Removes the element at the specified index
/// </summary>
public void RemoveAt(int index)
{
RemoveAtWithoutFiringPublicEvents(index);
// RemoveAtWithoutFiringPublicEvents incremented the version
WritePostscript();
}
/// <summary>
/// Removes the element at the specified index without firing
/// the public Changed event.
/// The caller - typically a public method - is responsible for calling
/// WritePostscript if appropriate.
/// </summary>
internal void RemoveAtWithoutFiringPublicEvents(int index)
{
WritePreamble();
_collection.RemoveAt(index);
++_version;
// No WritePostScript to avoid firing the Changed event.
}
/// <summary>
/// Indexer for the collection
/// </summary>
public int this[int index]
{
get
{
ReadPreamble();
return _collection[index];
}
set
{
WritePreamble();
_collection[ index ] = value;
++_version;
WritePostscript();
}
}
#endregion
#region ICollection<T>
/// <summary>
/// The number of elements contained in the collection.
/// </summary>
public int Count
{
get
{
ReadPreamble();
return _collection.Count;
}
}
/// <summary>
/// Copies the elements of the collection into "array" starting at "index"
/// </summary>
public void CopyTo(int[] array, int index)
{
ReadPreamble();
if (array == null)
{
throw new ArgumentNullException("array");
}
// This will not throw in the case that we are copying
// from an empty collection. This is consistent with the
// BCL Collection implementations. (Windows 1587365)
if (index < 0 || (index + _collection.Count) > array.Length)
{
throw new ArgumentOutOfRangeException("index");
}
_collection.CopyTo(array, index);
}
bool ICollection<int>.IsReadOnly
{
get
{
ReadPreamble();
return IsFrozen;
}
}
#endregion
#region IEnumerable<T>
/// <summary>
/// Returns an enumerator for the collection
/// </summary>
public Enumerator GetEnumerator()
{
ReadPreamble();
return new Enumerator(this);
}
IEnumerator<int> IEnumerable<int>.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region IList
bool IList.IsReadOnly
{
get
{
return ((ICollection<int>)this).IsReadOnly;
}
}
bool IList.IsFixedSize
{
get
{
ReadPreamble();
return IsFrozen;
}
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
// Forwards to typed implementation
this[index] = Cast(value);
}
}
int IList.Add(object value)
{
// Forward to typed helper
return AddHelper(Cast(value));
}
bool IList.Contains(object value)
{
if (value is int)
{
return Contains((int)value);
}
return false;
}
int IList.IndexOf(object value)
{
if (value is int)
{
return IndexOf((int)value);
}
return -1;
}
void IList.Insert(int index, object value)
{
// Forward to IList<T> Insert
Insert(index, Cast(value));
}
void IList.Remove(object value)
{
if (value is int)
{
Remove((int)value);
}
}
#endregion
#region ICollection
void ICollection.CopyTo(Array array, int index)
{
ReadPreamble();
if (array == null)
{
throw new ArgumentNullException("array");
}
// This will not throw in the case that we are copying
// from an empty collection. This is consistent with the
// BCL Collection implementations. (Windows 1587365)
if (index < 0 || (index + _collection.Count) > array.Length)
{
throw new ArgumentOutOfRangeException("index");
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Get(SRID.Collection_BadRank));
}
// Elsewhere in the collection we throw an AE when the type is
// bad so we do it here as well to be consistent
try
{
int count = _collection.Count;
for (int i = 0; i < count; i++)
{
array.SetValue(_collection[i], index + i);
}
}
catch (InvalidCastException e)
{
throw new ArgumentException(SR.Get(SRID.Collection_BadDestArray, this.GetType().Name), e);
}
}
bool ICollection.IsSynchronized
{
get
{
ReadPreamble();
return IsFrozen || Dispatcher != null;
}
}
object ICollection.SyncRoot
{
get
{
ReadPreamble();
return this;
}
}
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region Internal Helpers
/// <summary>
/// A frozen empty Int32Collection.
/// </summary>
internal static Int32Collection Empty
{
get
{
if (s_empty == null)
{
Int32Collection collection = new Int32Collection();
collection.Freeze();
s_empty = collection;
}
return s_empty;
}
}
/// <summary>
/// Helper to return read only access.
/// </summary>
internal int Internal_GetItem(int i)
{
return _collection[i];
}
#endregion
#region Private Helpers
private int Cast(object value)
{
if( value == null )
{
throw new System.ArgumentNullException("value");
}
if (!(value is int))
{
throw new System.ArgumentException(SR.Get(SRID.Collection_BadType, this.GetType().Name, value.GetType().Name, "int"));
}
return (int) value;
}
// IList.Add returns int and IList<T>.Add does not. This
// is called by both Adds and IList<T>'s just ignores the
// integer
private int AddHelper(int value)
{
int index = AddWithoutFiringPublicEvents(value);
// AddAtWithoutFiringPublicEvents incremented the version
WritePostscript();
return index;
}
internal int AddWithoutFiringPublicEvents(int value)
{
int index = -1;
WritePreamble();
index = _collection.Add(value);
++_version;
// No WritePostScript to avoid firing the Changed event.
return index;
}
#endregion Private Helpers
private static Int32Collection s_empty;
#region Public Properties
#endregion Public Properties
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new Int32Collection();
}
/// <summary>
/// Implementation of Freezable.CloneCore()
/// </summary>
protected override void CloneCore(Freezable source)
{
Int32Collection sourceInt32Collection = (Int32Collection) source;
base.CloneCore(source);
int count = sourceInt32Collection._collection.Count;
_collection = new FrugalStructList<int>(count);
for (int i = 0; i < count; i++)
{
_collection.Add(sourceInt32Collection._collection[i]);
}
}
/// <summary>
/// Implementation of Freezable.CloneCurrentValueCore()
/// </summary>
protected override void CloneCurrentValueCore(Freezable source)
{
Int32Collection sourceInt32Collection = (Int32Collection) source;
base.CloneCurrentValueCore(source);
int count = sourceInt32Collection._collection.Count;
_collection = new FrugalStructList<int>(count);
for (int i = 0; i < count; i++)
{
_collection.Add(sourceInt32Collection._collection[i]);
}
}
/// <summary>
/// Implementation of Freezable.GetAsFrozenCore()
/// </summary>
protected override void GetAsFrozenCore(Freezable source)
{
Int32Collection sourceInt32Collection = (Int32Collection) source;
base.GetAsFrozenCore(source);
int count = sourceInt32Collection._collection.Count;
_collection = new FrugalStructList<int>(count);
for (int i = 0; i < count; i++)
{
_collection.Add(sourceInt32Collection._collection[i]);
}
}
/// <summary>
/// Implementation of Freezable.GetCurrentValueAsFrozenCore()
/// </summary>
protected override void GetCurrentValueAsFrozenCore(Freezable source)
{
Int32Collection sourceInt32Collection = (Int32Collection) source;
base.GetCurrentValueAsFrozenCore(source);
int count = sourceInt32Collection._collection.Count;
_collection = new FrugalStructList<int>(count);
for (int i = 0; i < count; i++)
{
_collection.Add(sourceInt32Collection._collection[i]);
}
}
#endregion ProtectedMethods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
/// <summary>
/// Creates a string representation of this object based on the current culture.
/// </summary>
/// <returns>
/// A string representation of this object.
/// </returns>
public override string ToString()
{
ReadPreamble();
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(null /* format string */, null /* format provider */);
}
/// <summary>
/// Creates a string representation of this object based on the IFormatProvider
/// passed in. If the provider is null, the CurrentCulture is used.
/// </summary>
/// <returns>
/// A string representation of this object.
/// </returns>
public string ToString(IFormatProvider provider)
{
ReadPreamble();
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(null /* format string */, provider);
}
/// <summary>
/// Creates a string representation of this object based on the format string
/// and IFormatProvider passed in.
/// If the provider is null, the CurrentCulture is used.
/// See the documentation for IFormattable for more information.
/// </summary>
/// <returns>
/// A string representation of this object.
/// </returns>
string IFormattable.ToString(string format, IFormatProvider provider)
{
ReadPreamble();
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(format, provider);
}
/// <summary>
/// Creates a string representation of this object based on the format string
/// and IFormatProvider passed in.
/// If the provider is null, the CurrentCulture is used.
/// See the documentation for IFormattable for more information.
/// </summary>
/// <returns>
/// A string representation of this object.
/// </returns>
internal string ConvertToString(string format, IFormatProvider provider)
{
if (_collection.Count == 0)
{
return String.Empty;
}
StringBuilder str = new StringBuilder();
// Consider using this separator
// Helper to get the numeric list separator for a given culture.
// char separator = MS.Internal.TokenizerHelper.GetNumericListSeparator(provider);
for (int i=0; i<_collection.Count; i++)
{
str.AppendFormat(
provider,
"{0:" + format + "}",
_collection[i]);
if (i != _collection.Count-1)
{
str.Append(" ");
}
}
return str.ToString();
}
/// <summary>
/// Parse - returns an instance converted from the provided string
/// using the current culture
/// <param name="source"> string with Int32Collection data </param>
/// </summary>
public static Int32Collection Parse(string source)
{
IFormatProvider formatProvider = System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS;
TokenizerHelper th = new TokenizerHelper(source, formatProvider);
Int32Collection resource = new Int32Collection();
int value;
while (th.NextToken())
{
value = Convert.ToInt32(th.GetCurrentToken(), formatProvider);
resource.Add(value);
}
return resource;
}
#endregion Internal Properties
//------------------------------------------------------
//
// Dependency Properties
//
//------------------------------------------------------
#region Dependency Properties
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
internal FrugalStructList<int> _collection;
internal uint _version = 0;
#endregion Internal Fields
#region Enumerator
/// <summary>
/// Enumerates the items in a intCollection
/// </summary>
public struct Enumerator : IEnumerator, IEnumerator<int>
{
#region Constructor
internal Enumerator(Int32Collection list)
{
Debug.Assert(list != null, "list may not be null.");
_list = list;
_version = list._version;
_index = -1;
_current = default(int);
}
#endregion
#region Methods
void IDisposable.Dispose()
{
}
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// true if the enumerator was successfully advanced to the next element,
/// false if the enumerator has passed the end of the collection.
/// </returns>
public bool MoveNext()
{
_list.ReadPreamble();
if (_version == _list._version)
{
if (_index > -2 && _index < _list._collection.Count - 1)
{
_current = _list._collection[++_index];
return true;
}
else
{
_index = -2; // -2 indicates "past the end"
return false;
}
}
else
{
throw new InvalidOperationException(SR.Get(SRID.Enumerator_CollectionChanged));
}
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the
/// first element in the collection.
/// </summary>
public void Reset()
{
_list.ReadPreamble();
if (_version == _list._version)
{
_index = -1;
}
else
{
throw new InvalidOperationException(SR.Get(SRID.Enumerator_CollectionChanged));
}
}
#endregion
#region Properties
object IEnumerator.Current
{
get
{
return this.Current;
}
}
/// <summary>
/// Current element
///
/// The behavior of IEnumerable<T>.Current is undefined
/// before the first MoveNext and after we have walked
/// off the end of the list. However, the IEnumerable.Current
/// contract requires that we throw exceptions
/// </summary>
public int Current
{
get
{
if (_index > -1)
{
return _current;
}
else if (_index == -1)
{
throw new InvalidOperationException(SR.Get(SRID.Enumerator_NotStarted));
}
else
{
Debug.Assert(_index == -2, "expected -2, got " + _index + "\n");
throw new InvalidOperationException(SR.Get(SRID.Enumerator_ReachedEnd));
}
}
}
#endregion
#region Data
private int _current;
private Int32Collection _list;
private uint _version;
private int _index;
#endregion
}
#endregion
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
/// <summary>
/// Initializes a new instance that is empty.
/// </summary>
public Int32Collection()
{
_collection = new FrugalStructList<int>();
}
/// <summary>
/// Initializes a new instance that is empty and has the specified initial capacity.
/// </summary>
/// <param name="capacity"> int - The number of elements that the new list is initially capable of storing. </param>
public Int32Collection(int capacity)
{
_collection = new FrugalStructList<int>(capacity);
}
/// <summary>
/// Creates a Int32Collection with all of the same elements as collection
/// </summary>
public Int32Collection(IEnumerable<int> collection)
{
// The WritePreamble and WritePostscript aren't technically necessary
// in the constructor as of 1/20/05 but they are put here in case
// their behavior changes at a later date
WritePreamble();
if (collection != null)
{
ICollection<int> icollectionOfT = collection as ICollection<int>;
if (icollectionOfT != null)
{
_collection = new FrugalStructList<int>(icollectionOfT);
}
else
{
ICollection icollection = collection as ICollection;
if (icollection != null) // an IC but not and IC<T>
{
_collection = new FrugalStructList<int>(icollection);
}
else // not a IC or IC<T> so fall back to the slower Add
{
_collection = new FrugalStructList<int>();
foreach (int item in collection)
{
_collection.Add(item);
}
}
}
WritePostscript();
}
else
{
throw new ArgumentNullException("collection");
}
}
#endregion Constructors
}
}
| |
// 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.Runtime.InteropServices;
using System.Security;
namespace System.DirectoryServices.Protocols
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal class Luid
{
private int _lowPart;
private int _highPart;
public int LowPart => _lowPart;
public int HighPart => _highPart;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal sealed class SEC_WINNT_AUTH_IDENTITY_EX
{
public int version;
public int length;
public string user;
public int userLength;
public string domain;
public int domainLength;
public string password;
public int passwordLength;
public int flags;
public string packageList;
public int packageListLength;
}
internal enum BindMethod : uint
{
LDAP_AUTH_OTHERKIND = 0x86,
LDAP_AUTH_SICILY = LDAP_AUTH_OTHERKIND | 0x0200,
LDAP_AUTH_MSN = LDAP_AUTH_OTHERKIND | 0x0800,
LDAP_AUTH_NTLM = LDAP_AUTH_OTHERKIND | 0x1000,
LDAP_AUTH_DPA = LDAP_AUTH_OTHERKIND | 0x2000,
LDAP_AUTH_NEGOTIATE = LDAP_AUTH_OTHERKIND | 0x0400,
LDAP_AUTH_SSPI = LDAP_AUTH_NEGOTIATE,
LDAP_AUTH_DIGEST = LDAP_AUTH_OTHERKIND | 0x4000,
LDAP_AUTH_EXTERNAL = LDAP_AUTH_OTHERKIND | 0x0020
}
internal enum LdapOption
{
LDAP_OPT_DESC = 0x01,
LDAP_OPT_DEREF = 0x02,
LDAP_OPT_SIZELIMIT = 0x03,
LDAP_OPT_TIMELIMIT = 0x04,
LDAP_OPT_REFERRALS = 0x08,
LDAP_OPT_RESTART = 0x09,
LDAP_OPT_SSL = 0x0a,
LDAP_OPT_REFERRAL_HOP_LIMIT = 0x10,
LDAP_OPT_VERSION = 0x11,
LDAP_OPT_API_FEATURE_INFO = 0x15,
LDAP_OPT_HOST_NAME = 0x30,
LDAP_OPT_ERROR_NUMBER = 0x31,
LDAP_OPT_ERROR_STRING = 0x32,
LDAP_OPT_SERVER_ERROR = 0x33,
LDAP_OPT_SERVER_EXT_ERROR = 0x34,
LDAP_OPT_HOST_REACHABLE = 0x3E,
LDAP_OPT_PING_KEEP_ALIVE = 0x36,
LDAP_OPT_PING_WAIT_TIME = 0x37,
LDAP_OPT_PING_LIMIT = 0x38,
LDAP_OPT_DNSDOMAIN_NAME = 0x3B,
LDAP_OPT_GETDSNAME_FLAGS = 0x3D,
LDAP_OPT_PROMPT_CREDENTIALS = 0x3F,
LDAP_OPT_TCP_KEEPALIVE = 0x40,
LDAP_OPT_FAST_CONCURRENT_BIND = 0x41,
LDAP_OPT_SEND_TIMEOUT = 0x42,
LDAP_OPT_REFERRAL_CALLBACK = 0x70,
LDAP_OPT_CLIENT_CERTIFICATE = 0x80,
LDAP_OPT_SERVER_CERTIFICATE = 0x81,
LDAP_OPT_AUTO_RECONNECT = 0x91,
LDAP_OPT_SSPI_FLAGS = 0x92,
LDAP_OPT_SSL_INFO = 0x93,
LDAP_OPT_SIGN = 0x95,
LDAP_OPT_ENCRYPT = 0x96,
LDAP_OPT_SASL_METHOD = 0x97,
LDAP_OPT_AREC_EXCLUSIVE = 0x98,
LDAP_OPT_SECURITY_CONTEXT = 0x99,
LDAP_OPT_ROOTDSE_CACHE = 0x9a
}
internal enum ResultAll
{
LDAP_MSG_ALL = 1,
LDAP_MSG_RECEIVED = 2,
LDAP_MSG_POLLINGALL = 3
}
[StructLayout(LayoutKind.Sequential)]
internal sealed class LDAP_TIMEVAL
{
public int tv_sec;
public int tv_usec;
}
[StructLayout(LayoutKind.Sequential)]
internal sealed class berval
{
public int bv_len = 0;
public IntPtr bv_val = IntPtr.Zero;
public berval() { }
}
[StructLayout(LayoutKind.Sequential)]
internal sealed class SafeBerval
{
public int bv_len = 0;
public IntPtr bv_val = IntPtr.Zero;
~SafeBerval()
{
if (bv_val != IntPtr.Zero)
{
Marshal.FreeHGlobal(bv_val);
}
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal sealed class LdapControl
{
public IntPtr ldctl_oid = IntPtr.Zero;
public berval ldctl_value = null;
public bool ldctl_iscritical = false;
public LdapControl() { }
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct LdapReferralCallback
{
public int sizeofcallback;
public QUERYFORCONNECTIONInternal query;
public NOTIFYOFNEWCONNECTIONInternal notify;
public DEREFERENCECONNECTIONInternal dereference;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct CRYPTOAPI_BLOB
{
public int cbData;
public IntPtr pbData;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct SecPkgContext_IssuerListInfoEx
{
public IntPtr aIssuers;
public int cIssuers;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal sealed class LdapMod
{
public int type = 0;
public IntPtr attribute = IntPtr.Zero;
public IntPtr values = IntPtr.Zero;
~LdapMod()
{
if (attribute != IntPtr.Zero)
{
Marshal.FreeHGlobal(attribute);
}
if (values != IntPtr.Zero)
{
Marshal.FreeHGlobal(values);
}
}
}
[SuppressUnmanagedCodeSecurity]
internal class Wldap32
{
private const string Wldap32dll = "wldap32.dll";
public const int SEC_WINNT_AUTH_IDENTITY_UNICODE = 0x2;
public const int SEC_WINNT_AUTH_IDENTITY_VERSION = 0x200;
public const string MICROSOFT_KERBEROS_NAME_W = "Kerberos";
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_bind_sW", CharSet = CharSet.Unicode)]
public static extern int ldap_bind_s([In]ConnectionHandle ldapHandle, string dn, SEC_WINNT_AUTH_IDENTITY_EX credentials, BindMethod method);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_initW", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_init(string hostName, int portNumber);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, EntryPoint = "ldap_connect", CharSet = CharSet.Unicode)]
public static extern int ldap_connect([In] ConnectionHandle ldapHandle, LDAP_TIMEVAL timeout);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, EntryPoint = "ldap_unbind", CharSet = CharSet.Unicode)]
public static extern int ldap_unbind([In] IntPtr ldapHandle);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_get_option_int([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref int outValue);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_set_option_int([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref int inValue);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_get_option_ptr([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref IntPtr outValue);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_set_option_ptr([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref IntPtr inValue);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_get_option_sechandle([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref SecurityHandle outValue);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_get_option_secInfo([In] ConnectionHandle ldapHandle, [In] LdapOption option, [In, Out] SecurityPackageContextConnectionInformation outValue);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_set_option_referral([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref LdapReferralCallback outValue);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_set_option_clientcert([In] ConnectionHandle ldapHandle, [In] LdapOption option, QUERYCLIENTCERT outValue);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_set_option_servercert([In] ConnectionHandle ldapHandle, [In] LdapOption option, VERIFYSERVERCERT outValue);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "LdapGetLastError")]
public static extern int LdapGetLastError();
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "cldap_openW", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr cldap_open(string hostName, int portNumber);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_simple_bind_sW", CharSet = CharSet.Unicode)]
public static extern int ldap_simple_bind_s([In] ConnectionHandle ldapHandle, string distinguishedName, string password);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_delete_extW", CharSet = CharSet.Unicode)]
public static extern int ldap_delete_ext([In] ConnectionHandle ldapHandle, string dn, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_result", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern int ldap_result([In] ConnectionHandle ldapHandle, int messageId, int all, LDAP_TIMEVAL timeout, ref IntPtr Mesage);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_parse_resultW", CharSet = CharSet.Unicode)]
public static extern int ldap_parse_result([In] ConnectionHandle ldapHandle, [In] IntPtr result, ref int serverError, ref IntPtr dn, ref IntPtr message, ref IntPtr referral, ref IntPtr control, byte freeIt);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_parse_resultW", CharSet = CharSet.Unicode)]
public static extern int ldap_parse_result_referral([In] ConnectionHandle ldapHandle, [In] IntPtr result, IntPtr serverError, IntPtr dn, IntPtr message, ref IntPtr referral, IntPtr control, byte freeIt);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_memfreeW", CharSet = CharSet.Unicode)]
public static extern void ldap_memfree([In] IntPtr value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_value_freeW", CharSet = CharSet.Unicode)]
public static extern int ldap_value_free([In] IntPtr value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_controls_freeW", CharSet = CharSet.Unicode)]
public static extern int ldap_controls_free([In] IntPtr value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_abandon", CharSet = CharSet.Unicode)]
public static extern int ldap_abandon([In] ConnectionHandle ldapHandle, [In] int messagId);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_start_tls_sW", CharSet = CharSet.Unicode)]
public static extern int ldap_start_tls(ConnectionHandle ldapHandle, ref int ServerReturnValue, ref IntPtr Message, IntPtr ServerControls, IntPtr ClientControls);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_stop_tls_s", CharSet = CharSet.Unicode)]
public static extern byte ldap_stop_tls(ConnectionHandle ldapHandle);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_rename_extW", CharSet = CharSet.Unicode)]
public static extern int ldap_rename([In] ConnectionHandle ldapHandle, string dn, string newRdn, string newParentDn, int deleteOldRdn, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_compare_extW", CharSet = CharSet.Unicode)]
public static extern int ldap_compare([In] ConnectionHandle ldapHandle, string dn, string attributeName, string strValue, berval binaryValue, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_add_extW", CharSet = CharSet.Unicode)]
public static extern int ldap_add([In] ConnectionHandle ldapHandle, string dn, IntPtr attrs, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_modify_extW", CharSet = CharSet.Unicode)]
public static extern int ldap_modify([In] ConnectionHandle ldapHandle, string dn, IntPtr attrs, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_extended_operationW", CharSet = CharSet.Unicode)]
public static extern int ldap_extended_operation([In] ConnectionHandle ldapHandle, string oid, berval data, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_parse_extended_resultW", CharSet = CharSet.Unicode)]
public static extern int ldap_parse_extended_result([In] ConnectionHandle ldapHandle, [In] IntPtr result, ref IntPtr oid, ref IntPtr data, byte freeIt);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_msgfree", CharSet = CharSet.Unicode)]
public static extern int ldap_msgfree([In] IntPtr result);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_search_extW", CharSet = CharSet.Unicode)]
public static extern int ldap_search([In] ConnectionHandle ldapHandle, string dn, int scope, string filter, IntPtr attributes, bool attributeOnly, IntPtr servercontrol, IntPtr clientcontrol, int timelimit, int sizelimit, ref int messageNumber);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_first_entry", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_first_entry([In] ConnectionHandle ldapHandle, [In] IntPtr result);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_next_entry", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_next_entry([In] ConnectionHandle ldapHandle, [In] IntPtr result);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_first_reference", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_first_reference([In] ConnectionHandle ldapHandle, [In] IntPtr result);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_next_reference", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_next_reference([In] ConnectionHandle ldapHandle, [In] IntPtr result);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_dnW", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_get_dn([In] ConnectionHandle ldapHandle, [In] IntPtr result);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_first_attributeW", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_first_attribute([In] ConnectionHandle ldapHandle, [In] IntPtr result, ref IntPtr address);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_next_attributeW", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_next_attribute([In] ConnectionHandle ldapHandle, [In] IntPtr result, [In, Out] IntPtr address);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_free", CharSet = CharSet.Unicode)]
public static extern IntPtr ber_free([In] IntPtr berelement, int option);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_values_lenW", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_get_values_len([In] ConnectionHandle ldapHandle, [In] IntPtr result, string name);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_value_free_len", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_value_free_len([In] IntPtr berelement);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_parse_referenceW", CharSet = CharSet.Unicode)]
public static extern int ldap_parse_reference([In] ConnectionHandle ldapHandle, [In] IntPtr result, ref IntPtr referrals);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_alloc_t", CharSet = CharSet.Unicode)]
public static extern IntPtr ber_alloc(int option);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_printf", CharSet = CharSet.Unicode)]
public static extern int ber_printf_emptyarg(BerSafeHandle berElement, string format);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_printf", CharSet = CharSet.Unicode)]
public static extern int ber_printf_int(BerSafeHandle berElement, string format, int value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_printf", CharSet = CharSet.Unicode)]
public static extern int ber_printf_bytearray(BerSafeHandle berElement, string format, HGlobalMemHandle value, int length);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_printf", CharSet = CharSet.Unicode)]
public static extern int ber_printf_berarray(BerSafeHandle berElement, string format, IntPtr value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_flatten", CharSet = CharSet.Unicode)]
public static extern int ber_flatten(BerSafeHandle berElement, ref IntPtr value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_init", CharSet = CharSet.Unicode)]
public static extern IntPtr ber_init(berval value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_scanf", CharSet = CharSet.Unicode)]
public static extern int ber_scanf(BerSafeHandle berElement, string format);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_scanf", CharSet = CharSet.Unicode)]
public static extern int ber_scanf_int(BerSafeHandle berElement, string format, ref int value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_scanf", CharSet = CharSet.Unicode)]
public static extern int ber_scanf_ptr(BerSafeHandle berElement, string format, ref IntPtr value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_scanf", CharSet = CharSet.Unicode)]
public static extern int ber_scanf_bitstring(BerSafeHandle berElement, string format, ref IntPtr value, ref int length);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_bvfree", CharSet = CharSet.Unicode)]
public static extern int ber_bvfree(IntPtr value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_bvecfree", CharSet = CharSet.Unicode)]
public static extern int ber_bvecfree(IntPtr value);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_create_sort_controlW", CharSet = CharSet.Unicode)]
public static extern int ldap_create_sort_control(ConnectionHandle handle, IntPtr keys, byte critical, ref IntPtr control);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_control_freeW", CharSet = CharSet.Unicode)]
public static extern int ldap_control_free(IntPtr control);
[DllImport("Crypt32.dll", EntryPoint = "CertFreeCRLContext", CharSet = CharSet.Unicode)]
public static extern int CertFreeCRLContext(IntPtr certContext);
[DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_result2error", CharSet = CharSet.Unicode)]
public static extern int ldap_result2error([In] ConnectionHandle ldapHandle, [In] IntPtr result, int freeIt);
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.XPath;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Models;
using Umbraco.Web.Routing;
namespace Umbraco.Web.Models
{
/// <summary>
/// Represents an IPublishedContent which is created based on an Xml structure
/// </summary>
[Serializable]
[XmlType(Namespace = "http://umbraco.org/webservices/")]
internal class XmlPublishedContent : PublishedContentBase
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="xmlNode"></param>
public XmlPublishedContent(XmlNode xmlNode)
{
_pageXmlNode = xmlNode;
InitializeStructure();
Initialize();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="xmlNode"></param>
/// <param name="disableInitializing"></param>
internal XmlPublishedContent(XmlNode xmlNode, bool disableInitializing)
{
_pageXmlNode = xmlNode;
InitializeStructure();
if (!disableInitializing)
Initialize();
}
private bool _initialized = false;
private readonly ICollection<IPublishedContent> _children = new Collection<IPublishedContent>();
private IPublishedContent _parent = null;
private int _id;
private int _template;
private string _name;
private string _docTypeAlias;
private int _docTypeId;
private string _writerName;
private string _creatorName;
private int _writerId;
private int _creatorId;
private string _urlName;
private string _path;
private DateTime _createDate;
private DateTime _updateDate;
private Guid _version;
private readonly Collection<IPublishedContentProperty> _properties = new Collection<IPublishedContentProperty>();
private readonly XmlNode _pageXmlNode;
private int _sortOrder;
private int _level;
public override IEnumerable<IPublishedContent> Children
{
get
{
if (!_initialized)
Initialize();
return _children.OrderBy(x => x.SortOrder);
}
}
public override IPublishedContentProperty GetProperty(string alias)
{
return Properties.FirstOrDefault(x => x.Alias.InvariantEquals(alias));
}
/// <summary>
/// returns 'Content' as the ItemType
/// </summary>
public override PublishedItemType ItemType
{
get { return PublishedItemType.Content; }
}
public override IPublishedContent Parent
{
get
{
if (!_initialized)
Initialize();
return _parent;
}
}
public override int Id
{
get
{
if (!_initialized)
Initialize();
return _id;
}
}
public override int TemplateId
{
get
{
if (!_initialized)
Initialize();
return _template;
}
}
public override int SortOrder
{
get
{
if (!_initialized)
Initialize();
return _sortOrder;
}
}
public override string Name
{
get
{
if (!_initialized)
Initialize();
return _name;
}
}
public override string DocumentTypeAlias
{
get
{
if (!_initialized)
Initialize();
return _docTypeAlias;
}
}
public override int DocumentTypeId
{
get
{
if (!_initialized)
Initialize();
return _docTypeId;
}
}
public override string WriterName
{
get
{
if (!_initialized)
Initialize();
return _writerName;
}
}
public override string CreatorName
{
get
{
if (!_initialized)
Initialize();
return _creatorName;
}
}
public override int WriterId
{
get
{
if (!_initialized)
Initialize();
return _writerId;
}
}
public override int CreatorId
{
get
{
if (!_initialized)
Initialize();
return _creatorId;
}
}
public override string Path
{
get
{
if (!_initialized)
Initialize();
return _path;
}
}
public override DateTime CreateDate
{
get
{
if (!_initialized)
Initialize();
return _createDate;
}
}
public override DateTime UpdateDate
{
get
{
if (!_initialized)
Initialize();
return _updateDate;
}
}
public override Guid Version
{
get
{
if (!_initialized)
Initialize();
return _version;
}
}
public override string UrlName
{
get
{
if (!_initialized)
Initialize();
return _urlName;
}
}
public override int Level
{
get
{
if (!_initialized)
Initialize();
return _level;
}
}
public override ICollection<IPublishedContentProperty> Properties
{
get
{
if (!_initialized)
Initialize();
return _properties;
}
}
private void InitializeStructure()
{
// Load parent if it exists and is a node
if (_pageXmlNode != null && _pageXmlNode.SelectSingleNode("..") != null)
{
XmlNode parent = _pageXmlNode.SelectSingleNode("..");
if (parent != null && (parent.Name == "node" || (parent.Attributes != null && parent.Attributes.GetNamedItem("isDoc") != null)))
_parent = new XmlPublishedContent(parent, true);
}
}
private void Initialize()
{
if (_pageXmlNode != null)
{
_initialized = true;
if (_pageXmlNode.Attributes != null)
{
_id = int.Parse(_pageXmlNode.Attributes.GetNamedItem("id").Value);
if (_pageXmlNode.Attributes.GetNamedItem("template") != null)
_template = int.Parse(_pageXmlNode.Attributes.GetNamedItem("template").Value);
if (_pageXmlNode.Attributes.GetNamedItem("sortOrder") != null)
_sortOrder = int.Parse(_pageXmlNode.Attributes.GetNamedItem("sortOrder").Value);
if (_pageXmlNode.Attributes.GetNamedItem("nodeName") != null)
_name = _pageXmlNode.Attributes.GetNamedItem("nodeName").Value;
if (_pageXmlNode.Attributes.GetNamedItem("writerName") != null)
_writerName = _pageXmlNode.Attributes.GetNamedItem("writerName").Value;
if (_pageXmlNode.Attributes.GetNamedItem("urlName") != null)
_urlName = _pageXmlNode.Attributes.GetNamedItem("urlName").Value;
// Creatorname is new in 2.1, so published xml might not have it!
try
{
_creatorName = _pageXmlNode.Attributes.GetNamedItem("creatorName").Value;
}
catch
{
_creatorName = _writerName;
}
//Added the actual userID, as a user cannot be looked up via full name only...
if (_pageXmlNode.Attributes.GetNamedItem("creatorID") != null)
_creatorId = int.Parse(_pageXmlNode.Attributes.GetNamedItem("creatorID").Value);
if (_pageXmlNode.Attributes.GetNamedItem("writerID") != null)
_writerId = int.Parse(_pageXmlNode.Attributes.GetNamedItem("writerID").Value);
if (UmbracoSettings.UseLegacyXmlSchema)
{
if (_pageXmlNode.Attributes.GetNamedItem("nodeTypeAlias") != null)
_docTypeAlias = _pageXmlNode.Attributes.GetNamedItem("nodeTypeAlias").Value;
}
else
{
_docTypeAlias = _pageXmlNode.Name;
}
if (_pageXmlNode.Attributes.GetNamedItem("nodeType") != null)
_docTypeId = int.Parse(_pageXmlNode.Attributes.GetNamedItem("nodeType").Value);
if (_pageXmlNode.Attributes.GetNamedItem("path") != null)
_path = _pageXmlNode.Attributes.GetNamedItem("path").Value;
if (_pageXmlNode.Attributes.GetNamedItem("version") != null)
_version = new Guid(_pageXmlNode.Attributes.GetNamedItem("version").Value);
if (_pageXmlNode.Attributes.GetNamedItem("createDate") != null)
_createDate = DateTime.Parse(_pageXmlNode.Attributes.GetNamedItem("createDate").Value);
if (_pageXmlNode.Attributes.GetNamedItem("updateDate") != null)
_updateDate = DateTime.Parse(_pageXmlNode.Attributes.GetNamedItem("updateDate").Value);
if (_pageXmlNode.Attributes.GetNamedItem("level") != null)
_level = int.Parse(_pageXmlNode.Attributes.GetNamedItem("level").Value);
}
// load data
var dataXPath = UmbracoSettings.UseLegacyXmlSchema ? "data" : "* [not(@isDoc)]";
foreach (XmlNode n in _pageXmlNode.SelectNodes(dataXPath))
_properties.Add(new XmlPublishedContentProperty(n));
// load children
var childXPath = UmbracoSettings.UseLegacyXmlSchema ? "node" : "* [@isDoc]";
var nav = _pageXmlNode.CreateNavigator();
var expr = nav.Compile(childXPath);
expr.AddSort("@sortOrder", XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Number);
var iterator = nav.Select(expr);
while (iterator.MoveNext())
{
_children.Add(
new XmlPublishedContent(((IHasXmlNode)iterator.Current).GetNode(), true)
);
}
}
// else
// throw new ArgumentNullException("Node xml source is null");
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Media;
using Avalonia.Platform;
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Avalonia.Skia
{
public class FormattedTextImpl : IFormattedTextImpl
{
public FormattedTextImpl(
string text,
Typeface typeface,
TextAlignment textAlignment,
TextWrapping wrapping,
Size constraint,
IReadOnlyList<FormattedTextStyleSpan> spans)
{
Text = text ?? string.Empty;
// Replace 0 characters with zero-width spaces (200B)
Text = Text.Replace((char)0, (char)0x200B);
var skiaTypeface = TypefaceCache.GetTypeface(
typeface?.FontFamilyName ?? "monospace",
typeface?.Style ?? FontStyle.Normal,
typeface?.Weight ?? FontWeight.Normal);
_paint = new SKPaint();
//currently Skia does not measure properly with Utf8 !!!
//Paint.TextEncoding = SKTextEncoding.Utf8;
_paint.TextEncoding = SKTextEncoding.Utf16;
_paint.IsStroke = false;
_paint.IsAntialias = true;
_paint.LcdRenderText = true;
_paint.SubpixelText = true;
_paint.Typeface = skiaTypeface;
_paint.TextSize = (float)(typeface?.FontSize ?? 12);
_paint.TextAlign = textAlignment.ToSKTextAlign();
_wrapping = wrapping;
_constraint = constraint;
if (spans != null)
{
foreach (var span in spans)
{
if (span.ForegroundBrush != null)
{
SetForegroundBrush(span.ForegroundBrush, span.StartIndex, span.Length);
}
}
}
Rebuild();
}
public Size Constraint => _constraint;
public Size Size => _size;
public IEnumerable<FormattedTextLine> GetLines()
{
return _lines;
}
public TextHitTestResult HitTestPoint(Point point)
{
float y = (float)point.Y;
var line = _skiaLines.Find(l => l.Top <= y && (l.Top + l.Height) > y);
if (!line.Equals(default(AvaloniaFormattedTextLine)))
{
var rects = GetRects();
for (int c = line.Start; c < line.Start + line.TextLength; c++)
{
var rc = rects[c];
if (rc.Contains(point))
{
return new TextHitTestResult
{
IsInside = !(line.TextLength > line.Length),
TextPosition = c,
IsTrailing = (point.X - rc.X) > rc.Width / 2
};
}
}
int offset = 0;
if (point.X >= (rects[line.Start].X + line.Width) / 2 && line.Length > 0)
{
offset = line.TextLength > line.Length ?
line.Length : (line.Length - 1);
}
return new TextHitTestResult
{
IsInside = false,
TextPosition = line.Start + offset,
IsTrailing = Text.Length == (line.Start + offset + 1)
};
}
bool end = point.X > _size.Width || point.Y > _lines.Sum(l => l.Height);
return new TextHitTestResult()
{
IsInside = false,
IsTrailing = end,
TextPosition = end ? Text.Length - 1 : 0
};
}
public Rect HitTestTextPosition(int index)
{
var rects = GetRects();
if (index < 0 || index >= rects.Count)
{
var r = rects.LastOrDefault();
return new Rect(r.X + r.Width, r.Y, 0, _lineHeight);
}
if (rects.Count == 0)
{
return new Rect(0, 0, 1, _lineHeight);
}
if (index == rects.Count)
{
var lr = rects[rects.Count - 1];
return new Rect(new Point(lr.X + lr.Width, lr.Y), rects[index - 1].Size);
}
return rects[index];
}
public IEnumerable<Rect> HitTestTextRange(int index, int length)
{
List<Rect> result = new List<Rect>();
var rects = GetRects();
int lastIndex = index + length - 1;
foreach (var line in _skiaLines.Where(l =>
(l.Start + l.Length) > index &&
lastIndex >= l.Start))
{
int lineEndIndex = line.Start + (line.Length > 0 ? line.Length - 1 : 0);
double left = rects[line.Start > index ? line.Start : index].X;
double right = rects[lineEndIndex > lastIndex ? lastIndex : lineEndIndex].Right;
result.Add(new Rect(left, line.Top, right - left, line.Height));
}
return result;
}
public override string ToString()
{
return Text;
}
internal void Draw(DrawingContextImpl context,
SKCanvas canvas, SKPoint origin,
DrawingContextImpl.PaintWrapper foreground)
{
/* TODO: This originated from Native code, it might be useful for debugging character positions as
* we improve the FormattedText support. Will need to port this to C# obviously. Rmove when
* not needed anymore.
SkPaint dpaint;
ctx->Canvas->save();
ctx->Canvas->translate(origin.fX, origin.fY);
for (int c = 0; c < Lines.size(); c++)
{
dpaint.setARGB(255, 0, 0, 0);
SkRect rc;
rc.fLeft = 0;
rc.fTop = Lines[c].Top;
rc.fRight = Lines[c].Width;
rc.fBottom = rc.fTop + LineOffset;
ctx->Canvas->drawRect(rc, dpaint);
}
for (int c = 0; c < Length; c++)
{
dpaint.setARGB(255, c % 10 * 125 / 10 + 125, (c * 7) % 10 * 250 / 10, (c * 13) % 10 * 250 / 10);
dpaint.setStyle(SkPaint::kFill_Style);
ctx->Canvas->drawRect(Rects[c], dpaint);
}
ctx->Canvas->restore();
*/
using (var paint = _paint.Clone())
{
IDisposable currd = null;
var currentWrapper = foreground;
SKPaint currentPaint = null;
try
{
ApplyWrapperTo(ref currentPaint, foreground, ref currd, paint);
bool hasCusomFGBrushes = _foregroundBrushes.Any();
for (int c = 0; c < _skiaLines.Count; c++)
{
AvaloniaFormattedTextLine line = _skiaLines[c];
float x = TransformX(origin.X, 0, paint.TextAlign);
if (!hasCusomFGBrushes)
{
var subString = Text.Substring(line.Start, line.Length);
canvas.DrawText(subString, x, origin.Y + line.Top + _lineOffset, paint);
}
else
{
float currX = x;
string subStr;
int len;
for (int i = line.Start; i < line.Start + line.Length;)
{
var fb = GetNextForegroundBrush(ref line, i, out len);
if (fb != null)
{
//TODO: figure out how to get the brush size
currentWrapper = context.CreatePaint(fb, new Size());
}
else
{
if (!currentWrapper.Equals(foreground)) currentWrapper.Dispose();
currentWrapper = foreground;
}
subStr = Text.Substring(i, len);
ApplyWrapperTo(ref currentPaint, currentWrapper, ref currd, paint);
canvas.DrawText(subStr, currX, origin.Y + line.Top + _lineOffset, paint);
i += len;
currX += paint.MeasureText(subStr);
}
}
}
}
finally
{
if (!currentWrapper.Equals(foreground)) currentWrapper.Dispose();
currd?.Dispose();
}
}
}
private const float MAX_LINE_WIDTH = 10000;
private readonly List<KeyValuePair<FBrushRange, IBrush>> _foregroundBrushes =
new List<KeyValuePair<FBrushRange, IBrush>>();
private readonly List<FormattedTextLine> _lines = new List<FormattedTextLine>();
private readonly SKPaint _paint;
private readonly List<Rect> _rects = new List<Rect>();
public string Text { get; }
private readonly TextWrapping _wrapping;
private Size _constraint = new Size(double.PositiveInfinity, double.PositiveInfinity);
private float _lineHeight = 0;
private float _lineOffset = 0;
private Size _size;
private List<AvaloniaFormattedTextLine> _skiaLines;
private static void ApplyWrapperTo(ref SKPaint current, DrawingContextImpl.PaintWrapper wrapper,
ref IDisposable curr, SKPaint paint)
{
if (current == wrapper.Paint)
return;
curr?.Dispose();
curr = wrapper.ApplyTo(paint);
}
private static bool IsBreakChar(char c)
{
//white space or zero space whitespace
return char.IsWhiteSpace(c) || c == '\u200B';
}
private static int LineBreak(string textInput, int textIndex, int stop,
SKPaint paint, float maxWidth,
out int trailingCount)
{
int lengthBreak;
if (maxWidth == -1)
{
lengthBreak = stop - textIndex;
}
else
{
float measuredWidth;
string subText = textInput.Substring(textIndex, stop - textIndex);
lengthBreak = (int)paint.BreakText(subText, maxWidth, out measuredWidth) / 2;
}
//Check for white space or line breakers before the lengthBreak
int startIndex = textIndex;
int index = textIndex;
int word_start = textIndex;
bool prevBreak = true;
trailingCount = 0;
while (index < stop)
{
int prevText = index;
char currChar = textInput[index++];
bool currBreak = IsBreakChar(currChar);
if (!currBreak && prevBreak)
{
word_start = prevText;
}
prevBreak = currBreak;
if (index > startIndex + lengthBreak)
{
if (currBreak)
{
// eat the rest of the whitespace
while (index < stop && IsBreakChar(textInput[index]))
{
index++;
}
trailingCount = index - prevText;
}
else
{
// backup until a whitespace (or 1 char)
if (word_start == startIndex)
{
if (prevText > startIndex)
{
index = prevText;
}
}
else
{
index = word_start;
}
}
break;
}
if ('\n' == currChar)
{
int ret = index - startIndex;
int lineBreakSize = 1;
if (index < stop)
{
currChar = textInput[index++];
if ('\r' == currChar)
{
ret = index - startIndex;
++lineBreakSize;
}
}
trailingCount = lineBreakSize;
return ret;
}
if ('\r' == currChar)
{
int ret = index - startIndex;
int lineBreakSize = 1;
if (index < stop)
{
currChar = textInput[index++];
if ('\n' == currChar)
{
ret = index - startIndex;
++lineBreakSize;
}
}
trailingCount = lineBreakSize;
return ret;
}
}
return index - startIndex;
}
private void BuildRects()
{
// Build character rects
var fm = _paint.FontMetrics;
SKTextAlign align = _paint.TextAlign;
for (int li = 0; li < _skiaLines.Count; li++)
{
var line = _skiaLines[li];
float prevRight = TransformX(0, line.Width, align);
double nextTop = line.Top + line.Height;
if (li + 1 < _skiaLines.Count)
{
nextTop = _skiaLines[li + 1].Top;
}
for (int i = line.Start; i < line.Start + line.TextLength; i++)
{
float w = _paint.MeasureText(Text[i].ToString());
_rects.Add(new Rect(
prevRight,
line.Top,
w,
nextTop - line.Top));
prevRight += w;
}
}
}
private IBrush GetNextForegroundBrush(ref AvaloniaFormattedTextLine line, int index, out int length)
{
IBrush result = null;
int len = length = line.Start + line.Length - index;
if (_foregroundBrushes.Any())
{
var bi = _foregroundBrushes.FindIndex(b =>
b.Key.StartIndex <= index &&
b.Key.EndIndex > index
);
if (bi > -1)
{
var match = _foregroundBrushes[bi];
len = match.Key.EndIndex - index + 1;
result = match.Value;
if (len > 0 && len < length)
{
length = len;
}
}
int endIndex = index + length;
int max = bi == -1 ? _foregroundBrushes.Count : bi;
var next = _foregroundBrushes.Take(max)
.Where(b => b.Key.StartIndex < endIndex &&
b.Key.StartIndex > index)
.OrderBy(b => b.Key.StartIndex)
.FirstOrDefault();
if (next.Value != null)
{
length = next.Key.StartIndex - index;
}
}
return result;
}
private List<Rect> GetRects()
{
if (Text.Length > _rects.Count)
{
BuildRects();
}
return _rects;
}
private void Rebuild()
{
var length = Text.Length;
_lines.Clear();
_rects.Clear();
_skiaLines = new List<AvaloniaFormattedTextLine>();
int curOff = 0;
float curY = 0;
var metrics = _paint.FontMetrics;
var mTop = metrics.Top; // The greatest distance above the baseline for any glyph (will be <= 0).
var mBottom = metrics.Bottom; // The greatest distance below the baseline for any glyph (will be >= 0).
var mLeading = metrics.Leading; // The recommended distance to add between lines of text (will be >= 0).
var mDescent = metrics.Descent; //The recommended distance below the baseline. Will be >= 0.
var mAscent = metrics.Ascent; //The recommended distance above the baseline. Will be <= 0.
var lastLineDescent = mBottom - mDescent;
// This seems like the best measure of full vertical extent
// matches Direct2D line height
_lineHeight = mDescent - mAscent;
// Rendering is relative to baseline
_lineOffset = (-metrics.Ascent);
string subString;
float widthConstraint = (_constraint.Width != double.PositiveInfinity)
? (float)_constraint.Width
: -1;
for (int c = 0; curOff < length; c++)
{
float lineWidth = -1;
int measured;
int trailingnumber = 0;
subString = Text.Substring(curOff);
float constraint = -1;
if (_wrapping == TextWrapping.Wrap)
{
constraint = widthConstraint <= 0 ? MAX_LINE_WIDTH : widthConstraint;
if (constraint > MAX_LINE_WIDTH)
constraint = MAX_LINE_WIDTH;
}
measured = LineBreak(Text, curOff, length, _paint, constraint, out trailingnumber);
AvaloniaFormattedTextLine line = new AvaloniaFormattedTextLine();
line.TextLength = measured;
subString = Text.Substring(line.Start, line.TextLength);
lineWidth = _paint.MeasureText(subString);
line.Start = curOff;
line.Length = measured - trailingnumber;
line.Width = lineWidth;
line.Height = _lineHeight;
line.Top = curY;
_skiaLines.Add(line);
curY += _lineHeight;
curY += mLeading;
curOff += measured;
}
// Now convert to Avalonia data formats
_lines.Clear();
float maxX = 0;
for (var c = 0; c < _skiaLines.Count; c++)
{
var w = _skiaLines[c].Width;
if (maxX < w)
maxX = w;
_lines.Add(new FormattedTextLine(_skiaLines[c].TextLength, _skiaLines[c].Height));
}
if (_skiaLines.Count == 0)
{
_lines.Add(new FormattedTextLine(0, _lineHeight));
_size = new Size(0, _lineHeight);
}
else
{
var lastLine = _skiaLines[_skiaLines.Count - 1];
_size = new Size(maxX, lastLine.Top + lastLine.Height);
}
}
private float TransformX(float originX, float lineWidth, SKTextAlign align)
{
float x = 0;
if (align == SKTextAlign.Left)
{
x = originX;
}
else
{
double width = Constraint.Width > 0 && !double.IsPositiveInfinity(Constraint.Width) ?
Constraint.Width :
_size.Width;
switch (align)
{
case SKTextAlign.Center: x = originX + (float)(width - lineWidth) / 2; break;
case SKTextAlign.Right: x = originX + (float)(width - lineWidth); break;
}
}
return x;
}
private void SetForegroundBrush(IBrush brush, int startIndex, int length)
{
var key = new FBrushRange(startIndex, length);
int index = _foregroundBrushes.FindIndex(v => v.Key.Equals(key));
if (index > -1)
{
_foregroundBrushes.RemoveAt(index);
}
if (brush != null)
{
brush = brush.ToImmutable();
_foregroundBrushes.Insert(0, new KeyValuePair<FBrushRange, IBrush>(key, brush));
}
}
private struct AvaloniaFormattedTextLine
{
public float Height;
public int Length;
public int Start;
public int TextLength;
public float Top;
public float Width;
};
private struct FBrushRange
{
public FBrushRange(int startIndex, int length)
{
StartIndex = startIndex;
Length = length;
}
public int EndIndex => StartIndex + Length - 1;
public int Length { get; private set; }
public int StartIndex { get; private set; }
public bool Intersects(int index, int len) =>
(index + len) > StartIndex &&
(StartIndex + Length) > index;
public override string ToString()
{
return $"{StartIndex}-{EndIndex}";
}
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Threading;
using Spring.Pool;
using Spring.Threading;
using NUnit.Framework;
namespace Spring.Threading
{
[TestFixture]
public class SemaphoreTest
{
private static long SHORT_DELAY_MS = 300;
[Test]
public void UsingLikeAMutex ()
{
Semaphore semaphore = new Semaphore (1);
Latch latch = new Latch ();
Helper helper = new Helper (semaphore, latch);
Thread thread = new Thread (new ThreadStart (helper.Go));
semaphore.Acquire ();
thread.Start ();
latch.Acquire ();
Assert.IsFalse (helper.gone);
semaphore.Release ();
thread.Join ();
Assert.IsTrue (helper.gone, "not gone");
}
[Test]
public void AquireInSameThrad()
{
Semaphore s = new Semaphore(2);
Assert.AreEqual(2, s.Permits);
s.Acquire();
s.Acquire();
Assert.AreEqual(0, s.Permits);
}
[Test]
public void ReleaseMultipleTimesInSameThread()
{
Semaphore s = new Semaphore(2);
Assert.AreEqual(2, s.Permits);
s.Acquire();
s.Acquire();
s.Release(2);
Assert.AreEqual(2, s.Permits);
}
[Test]
public void AttemptWithNegativeMillisInSameThread()
{
Semaphore s = new Semaphore(2);
Assert.AreEqual(2, s.Permits);
s.Acquire();
Assert.IsTrue(s.Attempt(-400));
s.Release(2);
Assert.AreEqual(2, s.Permits);
}
[Test]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ReleaseMultipleBadArgument()
{
Semaphore s = new Semaphore(2);
Assert.AreEqual(2, s.Permits);
s.Acquire();
s.Acquire();
s.Release(-2);
Assert.AreEqual(2, s.Permits);
}
[Test]
public void AttemptInSameThread()
{
Semaphore s = new Semaphore(1);
Assert.IsTrue(s.Attempt(SHORT_DELAY_MS));
s.Release();
Assert.IsTrue(s.Attempt(SHORT_DELAY_MS));
s.Release();
Assert.IsTrue(s.Attempt(SHORT_DELAY_MS));
s.Release();
Assert.IsTrue(s.Attempt(SHORT_DELAY_MS));
s.Release();
Assert.IsTrue(s.Attempt(SHORT_DELAY_MS));
s.Release();
Assert.AreEqual(1, s.Permits);
}
//TODO tests that interrupt a thread.
[Test]
public void AquireReleaseInSameThread()
{
Semaphore s = new Semaphore(1);
s.Acquire();
s.Release();
s.Acquire();
s.Release();
s.Acquire();
s.Release();
s.Acquire();
s.Release();
s.Acquire();
s.Release();
s.Acquire();
s.Release();
Assert.AreEqual(1, s.Permits);
}
[Test]
public void AcquireReleaseInDifferentThreads()
{
Semaphore s = new Semaphore(0);
AcquireReleaseWorker worker1 = new AcquireReleaseWorker(s);
Thread thread1 = new Thread(new ThreadStart(worker1.DoWork));
thread1.Start();
Thread.Sleep(300);
s.Release();
s.Release();
s.Acquire();
s.Acquire();
s.Release();
thread1.Join();
}
[Test]
public void AttemptReleaseInDifferentThreads()
{
Semaphore s = new Semaphore(0);
AttemptReleaseWorker worker1 = new AttemptReleaseWorker(s);
Thread thread1 = new Thread(new ThreadStart(worker1.DoWork));
thread1.Start();
//TODO investigate...
//Assert.IsTrue(s.Attempt(SHORT_DELAY_MS));
s.Attempt(SHORT_DELAY_MS);
s.Release();
//Assert.IsTrue(s.Attempt(SHORT_DELAY_MS));
s.Attempt(SHORT_DELAY_MS);
s.Release();
s.Release();
thread1.Join();
}
[Test]
public void TimetoMillis()
{
long millis = Utils.CurrentTimeMillis;
//hmm should be using UtcNow, the impl in CurrentTimeMillis doesn't use UTC.
long epochTime = ((DateTime.Now-new DateTime (1970, 1, 1)).Ticks)/TimeSpan.TicksPerMillisecond;
long delta = epochTime-millis;
Assert.IsTrue(delta < 500);
}
}
public class AcquireReleaseWorker
{
private Semaphore sem;
public AcquireReleaseWorker(Semaphore s)
{
sem = s;
}
public void DoWork()
{
sem.Acquire();
sem.Release();
sem.Release();
sem.Acquire();
}
}
public class AttemptReleaseWorker
{
private Semaphore sem;
public AttemptReleaseWorker(Semaphore s)
{
sem = s;
}
public void DoWork()
{
long SHORT_DELAY_MS = 300;
sem.Release();
//TODO can we do Assert.IsTrue here?
sem.Attempt(SHORT_DELAY_MS);
sem.Release();
sem.Attempt(SHORT_DELAY_MS);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: bgs/low/pb/client/game_utilities_types.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Bgs.Protocol.GameUtilities.V1 {
/// <summary>Holder for reflection information generated from bgs/low/pb/client/game_utilities_types.proto</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class GameUtilitiesTypesReflection {
#region Descriptor
/// <summary>File descriptor for bgs/low/pb/client/game_utilities_types.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static GameUtilitiesTypesReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CixiZ3MvbG93L3BiL2NsaWVudC9nYW1lX3V0aWxpdGllc190eXBlcy5wcm90",
"bxIeYmdzLnByb3RvY29sLmdhbWVfdXRpbGl0aWVzLnYxGidiZ3MvbG93L3Bi",
"L2NsaWVudC9hdHRyaWJ1dGVfdHlwZXMucHJvdG8aJGJncy9sb3cvcGIvY2xp",
"ZW50L2VudGl0eV90eXBlcy5wcm90byJ3Cg9QbGF5ZXJWYXJpYWJsZXMSKAoI",
"aWRlbnRpdHkYASABKAsyFi5iZ3MucHJvdG9jb2wuSWRlbnRpdHkSDgoGcmF0",
"aW5nGAIgASgBEioKCWF0dHJpYnV0ZRgDIAMoCzIXLmJncy5wcm90b2NvbC5B",
"dHRyaWJ1dGUiQAoKQ2xpZW50SW5mbxIWCg5jbGllbnRfYWRkcmVzcxgBIAEo",
"CRIaChJwcml2aWxlZ2VkX25ldHdvcmsYAiABKAhCPAofYm5ldC5wcm90b2Nv",
"bC5nYW1lX3V0aWxpdGllcy52MUIXR2FtZVV0aWxpdGllc1R5cGVzUHJvdG9I",
"AmIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Bgs.Protocol.AttributeTypesReflection.Descriptor, global::Bgs.Protocol.EntityTypesReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.GameUtilities.V1.PlayerVariables), global::Bgs.Protocol.GameUtilities.V1.PlayerVariables.Parser, new[]{ "Identity", "Rating", "Attribute" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.GameUtilities.V1.ClientInfo), global::Bgs.Protocol.GameUtilities.V1.ClientInfo.Parser, new[]{ "ClientAddress", "PrivilegedNetwork" }, null, null, null)
}));
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class PlayerVariables : pb::IMessage<PlayerVariables> {
private static readonly pb::MessageParser<PlayerVariables> _parser = new pb::MessageParser<PlayerVariables>(() => new PlayerVariables());
public static pb::MessageParser<PlayerVariables> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Bgs.Protocol.GameUtilities.V1.GameUtilitiesTypesReflection.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public PlayerVariables() {
OnConstruction();
}
partial void OnConstruction();
public PlayerVariables(PlayerVariables other) : this() {
Identity = other.identity_ != null ? other.Identity.Clone() : null;
rating_ = other.rating_;
attribute_ = other.attribute_.Clone();
}
public PlayerVariables Clone() {
return new PlayerVariables(this);
}
/// <summary>Field number for the "identity" field.</summary>
public const int IdentityFieldNumber = 1;
private global::Bgs.Protocol.Identity identity_;
public global::Bgs.Protocol.Identity Identity {
get { return identity_; }
set {
identity_ = value;
}
}
/// <summary>Field number for the "rating" field.</summary>
public const int RatingFieldNumber = 2;
private double rating_;
public double Rating {
get { return rating_; }
set {
rating_ = value;
}
}
/// <summary>Field number for the "attribute" field.</summary>
public const int AttributeFieldNumber = 3;
private static readonly pb::FieldCodec<global::Bgs.Protocol.Attribute> _repeated_attribute_codec
= pb::FieldCodec.ForMessage(26, global::Bgs.Protocol.Attribute.Parser);
private readonly pbc::RepeatedField<global::Bgs.Protocol.Attribute> attribute_ = new pbc::RepeatedField<global::Bgs.Protocol.Attribute>();
public pbc::RepeatedField<global::Bgs.Protocol.Attribute> Attribute {
get { return attribute_; }
}
public override bool Equals(object other) {
return Equals(other as PlayerVariables);
}
public bool Equals(PlayerVariables other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Identity, other.Identity)) return false;
if (Rating != other.Rating) return false;
if(!attribute_.Equals(other.attribute_)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
hash ^= Identity.GetHashCode();
if (Rating != 0D) hash ^= Rating.GetHashCode();
hash ^= attribute_.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
{
output.WriteRawTag(10);
output.WriteMessage(Identity);
}
if (Rating != 0D) {
output.WriteRawTag(17);
output.WriteDouble(Rating);
}
attribute_.WriteTo(output, _repeated_attribute_codec);
}
public int CalculateSize() {
int size = 0;
{
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Identity);
}
if (Rating != 0D) {
size += 1 + 8;
}
size += attribute_.CalculateSize(_repeated_attribute_codec);
return size;
}
public void MergeFrom(PlayerVariables other) {
if (other == null) {
return;
}
if (other.identity_ != null) {
if (identity_ == null) {
identity_ = new global::Bgs.Protocol.Identity();
}
Identity.MergeFrom(other.Identity);
}
if (other.Rating != 0D) {
Rating = other.Rating;
}
attribute_.Add(other.attribute_);
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (identity_ == null) {
identity_ = new global::Bgs.Protocol.Identity();
}
input.ReadMessage(identity_);
break;
}
case 17: {
Rating = input.ReadDouble();
break;
}
case 26: {
attribute_.AddEntriesFrom(input, _repeated_attribute_codec);
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ClientInfo : pb::IMessage<ClientInfo> {
private static readonly pb::MessageParser<ClientInfo> _parser = new pb::MessageParser<ClientInfo>(() => new ClientInfo());
public static pb::MessageParser<ClientInfo> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Bgs.Protocol.GameUtilities.V1.GameUtilitiesTypesReflection.Descriptor.MessageTypes[1]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public ClientInfo() {
OnConstruction();
}
partial void OnConstruction();
public ClientInfo(ClientInfo other) : this() {
clientAddress_ = other.clientAddress_;
privilegedNetwork_ = other.privilegedNetwork_;
}
public ClientInfo Clone() {
return new ClientInfo(this);
}
/// <summary>Field number for the "client_address" field.</summary>
public const int ClientAddressFieldNumber = 1;
private string clientAddress_ = "";
public string ClientAddress {
get { return clientAddress_; }
set {
clientAddress_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "privileged_network" field.</summary>
public const int PrivilegedNetworkFieldNumber = 2;
private bool privilegedNetwork_;
public bool PrivilegedNetwork {
get { return privilegedNetwork_; }
set {
privilegedNetwork_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as ClientInfo);
}
public bool Equals(ClientInfo other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ClientAddress != other.ClientAddress) return false;
if (PrivilegedNetwork != other.PrivilegedNetwork) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (ClientAddress.Length != 0) hash ^= ClientAddress.GetHashCode();
if (PrivilegedNetwork != false) hash ^= PrivilegedNetwork.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (ClientAddress.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ClientAddress);
}
if (PrivilegedNetwork != false) {
output.WriteRawTag(16);
output.WriteBool(PrivilegedNetwork);
}
}
public int CalculateSize() {
int size = 0;
if (ClientAddress.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ClientAddress);
}
if (PrivilegedNetwork != false) {
size += 1 + 1;
}
return size;
}
public void MergeFrom(ClientInfo other) {
if (other == null) {
return;
}
if (other.ClientAddress.Length != 0) {
ClientAddress = other.ClientAddress;
}
if (other.PrivilegedNetwork != false) {
PrivilegedNetwork = other.PrivilegedNetwork;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
ClientAddress = input.ReadString();
break;
}
case 16: {
PrivilegedNetwork = input.ReadBool();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Roslyn.Test.EditorUtilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
{
public class ITextSnapshotLineExtensionsTests
{
[Fact]
public void GetFirstNonWhitespacePosition_EmptyLineReturnsNull()
{
var position = GetFirstNonWhitespacePosition(string.Empty);
Assert.Null(position);
}
[Fact]
public void GetFirstNonWhitespacePosition_WhitespaceLineReturnsNull1()
{
var position = GetFirstNonWhitespacePosition(" ");
Assert.Null(position);
}
[Fact]
public void GetFirstNonWhitespacePosition_WhitespaceLineReturnsNull2()
{
var position = GetFirstNonWhitespacePosition(" \t ");
Assert.Null(position);
}
[Fact]
public void GetFirstNonWhitespacePosition_WhitespaceLineReturnsNull3()
{
var position = GetFirstNonWhitespacePosition("\t\t");
Assert.Null(position);
}
[Fact]
public void GetFirstNonWhitespacePosition_TextLine()
{
var position = GetFirstNonWhitespacePosition("Foo");
Assert.Equal(0, position.Value);
}
[Fact]
public void GetFirstNonWhitespacePosition_TextLineStartingWithWhitespace1()
{
var position = GetFirstNonWhitespacePosition(" Foo");
Assert.Equal(4, position.Value);
}
[Fact]
public void GetFirstNonWhitespacePosition_TextLineStartingWithWhitespace2()
{
var position = GetFirstNonWhitespacePosition(" \t Foo");
Assert.Equal(3, position.Value);
}
[Fact]
public void GetFirstNonWhitespacePosition_TextLineStartingWithWhitespace3()
{
var position = GetFirstNonWhitespacePosition("\t\tFoo");
Assert.Equal(2, position.Value);
}
[Fact]
public void GetLastNonWhitespacePosition_EmptyLineReturnsNull()
{
var position = GetLastNonWhitespacePosition(string.Empty);
Assert.Null(position);
}
[Fact]
public void GetLastNonWhitespacePosition_WhitespaceLineReturnsNull1()
{
var position = GetLastNonWhitespacePosition(" ");
Assert.Null(position);
}
[Fact]
public void GetLastNonWhitespacePosition_WhitespaceLineReturnsNull2()
{
var position = GetLastNonWhitespacePosition(" \t ");
Assert.Null(position);
}
[Fact]
public void GetLastNonWhitespacePosition_WhitespaceLineReturnsNull3()
{
var position = GetLastNonWhitespacePosition("\t\t");
Assert.Null(position);
}
[Fact]
public void GetLastNonWhitespacePosition_TextLine()
{
var position = GetLastNonWhitespacePosition("Foo");
Assert.Equal(2, position.Value);
}
[Fact]
public void GetLastNonWhitespacePosition_TextLineEndingWithWhitespace1()
{
var position = GetLastNonWhitespacePosition("Foo ");
Assert.Equal(2, position.Value);
}
[Fact]
public void GetLastNonWhitespacePosition_TextLineEndingWithWhitespace2()
{
var position = GetLastNonWhitespacePosition("Foo \t ");
Assert.Equal(2, position.Value);
}
[Fact]
public void GetLastNonWhitespacePosition_TextLineEndingWithWhitespace3()
{
var position = GetLastNonWhitespacePosition("Foo\t\t");
Assert.Equal(2, position.Value);
}
[Fact]
public void IsEmptyOrWhitespace_EmptyLineReturnsTrue()
{
var value = IsEmptyOrWhitespace(string.Empty);
Assert.True(value);
}
[Fact]
public void IsEmptyOrWhitespace_WhitespaceLineReturnsTrue1()
{
var value = IsEmptyOrWhitespace(" ");
Assert.True(value);
}
[Fact]
public void IsEmptyOrWhitespace_WhitespaceLineReturnsTrue2()
{
var value = IsEmptyOrWhitespace("\t\t");
Assert.True(value);
}
[Fact]
public void IsEmptyOrWhitespace_WhitespaceLineReturnsTrue3()
{
var value = IsEmptyOrWhitespace(" \t ");
Assert.True(value);
}
[Fact]
public void IsEmptyOrWhitespace_TextLineReturnsFalse()
{
var value = IsEmptyOrWhitespace("Foo");
Assert.False(value);
}
[Fact]
public void IsEmptyOrWhitespace_TextLineStartingWithWhitespaceReturnsFalse1()
{
var value = IsEmptyOrWhitespace(" Foo");
Assert.False(value);
}
[Fact]
public void IsEmptyOrWhitespace_TextLineStartingWithWhitespaceReturnsFalse2()
{
var value = IsEmptyOrWhitespace(" \t Foo");
Assert.False(value);
}
[Fact]
public void IsEmptyOrWhitespace_TextLineStartingWithWhitespaceReturnsFalse3()
{
var value = IsEmptyOrWhitespace("\t\tFoo");
Assert.False(value);
}
private ITextSnapshotLine GetLine(string codeLine)
{
var snapshot = EditorFactory.CreateBuffer(TestExportProvider.ExportProviderWithCSharpAndVisualBasic, codeLine).CurrentSnapshot;
return snapshot.GetLineFromLineNumber(0);
}
private bool IsEmptyOrWhitespace(string codeLine)
{
var line = GetLine(codeLine);
return line.IsEmptyOrWhitespace();
}
private int? GetFirstNonWhitespacePosition(string codeLine)
{
var line = GetLine(codeLine);
return line.GetFirstNonWhitespacePosition();
}
private int? GetLastNonWhitespacePosition(string codeLine)
{
var line = GetLine(codeLine);
return line.GetLastNonWhitespacePosition();
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using ActiproSoftware.Windows.Extensions;
using ArcGIS.Core.Geometry;
using ArcGIS.Core.Data;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using MessageBox = ArcGIS.Desktop.Framework.Dialogs.MessageBox;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Catalog;
using ArcGIS.Desktop.Core;
namespace DatastoresDefinitionsAndDatasets
{
internal class DockpaneViewModel : DockPane
{
#region Private members
private const string _dockPaneID = "DatastoresDefinitionsAndDatasets_Dockpane";
private Datastore _datastore;
private readonly object _lockCollection = new object();
private DatasetInfo _selectedDatasetInfo;
private string _dataPath;
private DatasetTypeCategory _datasetTypeCategory;
private DatastoreCategory _datastoreCategory;
private Visibility _cmdDataPathVisible;
private string _cmdDataPathContent;
private ICommand _cmdDataPath;
private ICommand _cmdLoadData;
private string _heading = "Datastore Datasets and Definitions";
#endregion Private members
private static bool IsOnUiThread => ArcGIS.Desktop.Framework.FrameworkApplication.TestMode || System.Windows.Application.Current.Dispatcher.CheckAccess();
protected DockpaneViewModel()
{
Datasets = new ObservableCollection<DatasetInfo>();
DatasetTypeCategories = new ObservableCollection<DatasetTypeCategory>();
DefinitionDetails = new ObservableCollection<string>();
RunOnUiThread(() =>
{
BindingOperations.EnableCollectionSynchronization(Datasets, _lockCollection);
BindingOperations.EnableCollectionSynchronization(DatasetTypeCategories, _lockCollection);
BindingOperations.EnableCollectionSynchronization(DefinitionDetails, _lockCollection);
});
}
public List<DatastoreCategory> DatastoreCategories => DatastoreCategory.AllDatastoreCategories;
public DatastoreCategory DatastoreCategory
{
get { return _datastoreCategory; }
set
{
SetProperty(ref _datastoreCategory, value, () => DatastoreCategory);
if (_datastoreCategory != null)
{
CmdDataPathVisible = string.IsNullOrEmpty(_datastoreCategory.PathCaption) ?
Visibility.Hidden : Visibility.Visible;
CmdDataPathContent = _datastoreCategory.PathCaption;
}
else CmdDataPathVisible = Visibility.Hidden;
}
}
public string DataPath
{
get { return _dataPath; }
set
{
SetProperty(ref _dataPath, value, () => DataPath);
}
}
public Visibility CmdDataPathVisible
{
get { return _cmdDataPathVisible; }
set
{
SetProperty(ref _cmdDataPathVisible, value, () => CmdDataPathVisible);
}
}
public string CmdDataPathContent
{
get { return _cmdDataPathContent; }
set
{
SetProperty(ref _cmdDataPathContent, value, () => CmdDataPathContent);
}
}
public ICommand CmdDataPath
{
get
{
return _cmdDataPath ?? (_cmdDataPath = new RelayCommand(() =>
{
OpenItemDialog openDialog = new OpenItemDialog()
{
Title = DatastoreCategory.OpenDlgTitle,
MultiSelect = false,
Filter = DatastoreCategory.OpenDlgFilter,
InitialLocation = string.IsNullOrEmpty(DataPath) ? @"c:\data" : DataPath
};
if (openDialog.ShowDialog() == true)
{
foreach (Item item in openDialog.Items)
{
var errValidation = DatastoreCategory.ValidateDataPath(item.Path);
if (!string.IsNullOrEmpty(errValidation)) MessageBox.Show(errValidation, "Error");
else DataPath = item.Path;
break;
}
}
}, () => !string.IsNullOrEmpty(CmdDataPathContent)));
}
}
public ICommand CmdLoadData
{
get
{
return _cmdLoadData ?? (_cmdLoadData = new RelayCommand(async () =>
{
try
{
Uri path = new Uri(DataPath);
// clear old information
Datasets.Clear();
DatasetTypeCategories.Clear();
DefinitionDetails.Clear();
if (_datastore != null)
_datastore.Dispose();
_datastore = await DatastoreCategory.OpenDatastore(path, DatasetTypeCategories);
}
catch (Exception exObj)
{
MessageBox.Show($@"Unable to create a Datastore for {DataPath}: {exObj.Message}",
"Error");
}
}, () => !string.IsNullOrEmpty(DataPath)));
}
}
public ObservableCollection<DatasetTypeCategory> DatasetTypeCategories { get; set; }
public DatasetTypeCategory DatasetTypeCategory
{
get
{ return _datasetTypeCategory; }
set
{
SetProperty(ref _datasetTypeCategory, value, () => DatasetTypeCategory);
if (_datasetTypeCategory == null) return;
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
SetupDefinitionAsync();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
}
}
public ObservableCollection<DatasetInfo> Datasets { get; set; }
public ObservableCollection<string> DefinitionDetails { get; set; }
public DatasetInfo Dataset
{
get { return _selectedDatasetInfo; }
set
{
SetProperty(ref _selectedDatasetInfo, value, () => Dataset);
if (_selectedDatasetInfo == null) return;
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
SetupDefinitionDetailsAsync();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
}
}
private async Task SetupDefinitionAsync()
{
try
{
var lstDefinitions = await QueuedTask.Run<List<DatasetInfo>>(() =>
{
List<DatasetInfo> definitions = new List<DatasetInfo>();
if (_datastore is Geodatabase)
{
var geodatabase = _datastore as Geodatabase;
switch (DatasetTypeCategory.DatasetType)
{
case DatasetType.Table:
definitions = geodatabase.GetDefinitions<TableDefinition>().Select(CreateDataSetInfo).ToList();
break;
case DatasetType.FeatureClass:
definitions = geodatabase.GetDefinitions<FeatureClassDefinition>().Select(CreateDataSetInfo).ToList();
break;
case DatasetType.FeatureDataset:
definitions = geodatabase.GetDefinitions<FeatureDatasetDefinition>().Select(CreateDataSetInfo).ToList();
break;
case DatasetType.RelationshipClass:
definitions = geodatabase.GetDefinitions<RelationshipClassDefinition>().Select(CreateDataSetInfo).ToList();
break;
case DatasetType.AttributedRelationshipClass:
definitions = geodatabase.GetDefinitions<AttributedRelationshipClassDefinition>().Select(CreateDataSetInfo).ToList();
break;
}
}
else if (_datastore is Database)
{
var database = _datastore as Database;
IReadOnlyList<string> tableNames = database.GetTableNames();
foreach (string tableName in tableNames)
{
QueryDescription queryDescription = database.GetQueryDescription(tableName);
TableDefinition tableDefinition = database.GetDefinition(queryDescription);
if (DatasetTypeCategory.DatasetType == DatasetType.Table || DatasetTypeCategory.DatasetType == DatasetType.FeatureClass)
{
definitions.Add(new DatasetInfo
{
Name = tableDefinition.GetName(),
DatasetDefinition = tableDefinition
});
}
}
}
else if (_datastore is FileSystemDatastore)
{
var shapefile = _datastore as FileSystemDatastore;
FileSystemConnectionPath shapefileConnectionPath = (FileSystemConnectionPath)shapefile.GetConnector();
DirectoryInfo directoryInfo = new DirectoryInfo(shapefileConnectionPath.Path.LocalPath);
if (DatasetTypeCategory.DatasetType == DatasetType.FeatureClass)
{
FileInfo[] filesWithShpExtension = directoryInfo.GetFiles("*.shp");
foreach (FileInfo file in filesWithShpExtension)
{
definitions.Add(CreateDataSetInfo(shapefile.GetDefinition<FeatureClassDefinition>(file.Name)));
}
}
if (DatasetTypeCategory.DatasetType == DatasetType.Table)
{
FileInfo[] filesWithDbfExtension = directoryInfo.GetFiles("*.dbf");
foreach (FileInfo file in filesWithDbfExtension)
{
definitions.Add(CreateDataSetInfo(shapefile.GetDefinition<TableDefinition>(file.Name)));
}
}
}
return definitions;
});
Datasets.Clear();
Datasets.AddRange(lstDefinitions);
DefinitionDetails.Clear();
}
catch (Exception exObj)
{
MessageBox.Show(exObj.Message, "Error");
}
}
private DatasetInfo CreateDataSetInfo(Definition definition)
{
return new DatasetInfo
{
Name = definition.GetName(),
DatasetDefinition = definition
};
}
private async Task SetupDefinitionDetailsAsync()
{
DefinitionDetails.Clear();
try
{
var lstDefs = await QueuedTask.Run<List<string>>(() =>
{
Definition datasetDefinition = Dataset.DatasetDefinition;
List<string> lstDefDetails = new List<string>();
if (datasetDefinition is TableDefinition)
{
TableDefinition tableDefinition = datasetDefinition as TableDefinition;
lstDefDetails.Add($"Object ID Field: {tableDefinition.GetObjectIDField()}");
StringBuilder stringBuilder = new StringBuilder();
if (!(_datastore is FileSystemDatastore))
{
lstDefDetails.Add($"Alias Name: {tableDefinition.GetAliasName()}");
lstDefDetails.Add($"CreatedAt Field: {tableDefinition.GetCreatedAtField()}");
lstDefDetails.Add($"Creator Field: {tableDefinition.GetCreatorField()}");
lstDefDetails.Add($"Subtype Field: {tableDefinition.GetSubtypeField()}");
lstDefDetails.Add($"Default Subtype Code: {tableDefinition.GetDefaultSubtypeCode()}");
lstDefDetails.Add($"EditedAt Field: {tableDefinition.GetEditedAtField()}");
lstDefDetails.Add($"Editor Field: {tableDefinition.GetEditorField()}");
lstDefDetails.Add($"Global ID Field: {tableDefinition.GetGlobalIDField()}");
lstDefDetails.Add($"Model Name: {tableDefinition.GetModelName()}");
foreach (var subtype in tableDefinition.GetSubtypes())
{
stringBuilder.Append(subtype.GetCode()).Append(": ").Append(subtype.GetName()).Append(Environment.NewLine);
}
lstDefDetails.Add($"Subtypes: {stringBuilder}");
}
stringBuilder = new StringBuilder();
foreach (Index index in tableDefinition.GetIndexes())
{
stringBuilder.Append(index.GetName()).Append(",");
string order = index.IsAscending() ? "Ascending" : "Descending";
stringBuilder.Append(order).Append(", ");
string unique = index.IsUnique() ? "Unique" : "Not Unique";
stringBuilder.Append(unique);
}
lstDefDetails.Add($"Indexes: {stringBuilder}");
}
if (datasetDefinition is FeatureClassDefinition)
{
FeatureClassDefinition featureClassDefinition = datasetDefinition as FeatureClassDefinition;
if (!(_datastore is FileSystemDatastore))
{
lstDefDetails.Add($"Area Field: {featureClassDefinition.GetAreaField()}");
lstDefDetails.Add($"Length Field: {featureClassDefinition.GetLengthField()}");
}
lstDefDetails.Add($"Shape Field: {featureClassDefinition.GetShapeField()}");
lstDefDetails.Add($"Shape Type: {featureClassDefinition.GetShapeType()}");
lstDefDetails.Add($"Spatial Reference Name: {featureClassDefinition.GetSpatialReference().Name}");
Envelope extent = featureClassDefinition.GetExtent();
lstDefDetails.Add($"Extent Details: XMin-{extent.XMin} XMax-{extent.XMax} YMin-{extent.YMin} YMax-{extent.YMax}");
}
if (datasetDefinition is FeatureDatasetDefinition)
{
FeatureDatasetDefinition featureDatasetDefinition = datasetDefinition as FeatureDatasetDefinition;
lstDefDetails.Add($"Spatial Reference Name: {featureDatasetDefinition.GetSpatialReference().Name}");
try
{
Envelope extent = featureDatasetDefinition.GetExtent();
lstDefDetails.Add($"Extent Details: XMin-{extent.XMin} XMax-{extent.XMax} YMin-{extent.YMin} YMax-{extent.YMax}");
}
catch (Exception)
{
lstDefDetails.Add("Could not get extent");
}
}
if (datasetDefinition is RelationshipClassDefinition)
{
RelationshipClassDefinition relationshipClassDefinition = datasetDefinition as RelationshipClassDefinition;
lstDefDetails.Add($"Alias Name: {relationshipClassDefinition.GetAliasName()}");
lstDefDetails.Add($"Cardinality: {relationshipClassDefinition.GetCardinality()}");
lstDefDetails.Add($"Origin Class: {relationshipClassDefinition.GetOriginClass()}");
lstDefDetails.Add($"Destination Class: {relationshipClassDefinition.GetDestinationClass()}");
lstDefDetails.Add($"Origin Primary Key: {relationshipClassDefinition.GetOriginKeyField()}");
lstDefDetails.Add($"Origin Foreign Key: {relationshipClassDefinition.GetOriginForeignKeyField()}");
lstDefDetails.Add($"Is Attachement?: {relationshipClassDefinition.IsAttachmentRelationship()}");
lstDefDetails.Add($"Is Composite Relationship?: {relationshipClassDefinition.IsComposite()}");
}
if (datasetDefinition is AttributedRelationshipClassDefinition)
{
AttributedRelationshipClassDefinition relationshipClassDefinition = datasetDefinition as AttributedRelationshipClassDefinition;
lstDefDetails.Add($"Destination Key: {relationshipClassDefinition.GetDestinationKeyField()}");
lstDefDetails.Add($"Destination Foreign Key: {relationshipClassDefinition.GetDestinationForeignKeyField()}");
lstDefDetails.Add($"Object ID Field: {relationshipClassDefinition.GetObjectIDField()}");
}
return lstDefDetails;
});
DefinitionDetails.AddRange(lstDefs);
}
catch (Exception exObj)
{
MessageBox.Show(exObj.Message, "Error");
}
}
/// <summary>
/// Show the DockPane.
/// </summary>
internal static void Show()
{
DockPane pane = FrameworkApplication.DockPaneManager.Find(_dockPaneID);
if (pane == null)
return;
pane.Activate();
}
/// <summary>
/// Text shown near the top of the DockPane.
/// </summary>
public string Heading
{
get { return _heading; }
set
{
SetProperty(ref _heading, value, () => Heading);
}
}
internal static void RunOnUiThread(Action action)
{
try
{
if (IsOnUiThread)
action();
else
Application.Current.Dispatcher.Invoke(action);
}
catch (Exception ex)
{
MessageBox.Show($@"Error in OpenAndActivateMap: {ex.Message}");
}
}
}
/// <summary>
/// Button implementation to show the DockPane.
/// </summary>
internal class Dockpane_ShowButton : Button
{
protected override void OnClick()
{
DockpaneViewModel.Show();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using Microsoft.Internal;
namespace System.ComponentModel.Composition.Hosting
{
public abstract partial class ExportProvider
{
/// <summary>
/// Returns the export with the contract name derived from the specified type parameter,
/// throwing an exception if there is not exactly one matching export.
/// </summary>
/// <typeparam name="T">
/// The type of the <see cref="Lazy{T}"/> object to return. The contract name is also
/// derived from this type parameter.
/// </typeparam>
/// <returns>
/// The <see cref="Lazy{T}"/> object with the contract name derived from
/// <typeparamref name="T"/>.
/// </returns>
/// <remarks>
/// <para>
/// The returned <see cref="Lazy{T}"/> object is an instance of
/// <see cref="Lazy{T, TMetadataView}"/> underneath, where
/// <c>TMetadataView</c>
/// is <see cref="IDictionary{TKey, TValue}"/> and where <c>TKey</c>
/// is <see cref="String"/> and <c>TValue</c> is <see cref="Object"/>.
/// </para>
/// <para>
/// The contract name is the result of calling
/// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
/// </para>
/// <para>
/// The contract name is compared using a case-sensitive, non-linguistic comparison
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
/// <exception cref="ImportCardinalityMismatchException">
/// <para>
/// There are zero <see cref="Lazy{T}"/> objects with the contract name derived
/// from <typeparamref name="T"/> in the <see cref="CompositionContainer"/>.
/// </para>
/// -or-
/// <para>
/// There are more than one <see cref="Lazy{T}"/> objects with the contract name
/// derived from <typeparamref name="T"/> in the <see cref="CompositionContainer"/>.
/// </para>
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
public Lazy<T> GetExport<T>()
{
return GetExport<T>((string)null);
}
/// <summary>
/// Returns the export with the specified contract name, throwing an exception if there
/// is not exactly one matching export.
/// </summary>
/// <typeparam name="T">
/// The type of the <see cref="Lazy{T}"/> object to return.
/// </typeparam>
/// <param name="contractName">
/// A <see cref="String"/> containing the contract name of the <see cref="Lazy{T}"/>
/// object to return; or <see langword="null"/> or an empty string ("") to use the
/// default contract name.
/// </param>
/// <returns>
/// The <see cref="Lazy{T}"/> object with the specified contract name.
/// </returns>
/// <remarks>
/// <para>
/// The returned <see cref="Lazy{T}"/> object is an instance of
/// <see cref="Lazy{T, TMetadataView}"/> underneath, where
/// <c>TMetadataView</c>
/// is <see cref="IDictionary{TKey, TValue}"/> and where <c>TKey</c>
/// is <see cref="String"/> and <c>TValue</c> is <see cref="Object"/>.
/// </para>
/// <para>
/// The contract name is the result of calling
/// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
/// </para>
/// <para>
/// The default contract name is compared using a case-sensitive, non-linguistic
/// comparison using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
/// <exception cref="ImportCardinalityMismatchException">
/// <para>
/// There are zero <see cref="Lazy{T}"/> objects with the specified contract name
/// in the <see cref="CompositionContainer"/>.
/// </para>
/// -or-
/// <para>
/// There are more than one <see cref="Lazy{T}"/> objects with the specified contract
/// name in the <see cref="CompositionContainer"/>.
/// </para>
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
public Lazy<T> GetExport<T>(string contractName)
{
return GetExportCore<T>(contractName);
}
/// <summary>
/// Returns the export with the contract name derived from the specified type parameter,
/// throwing an exception if there is not exactly one matching export.
/// </summary>
/// <typeparam name="T">
/// The type of the <see cref="Lazy{T, TMetadataView}"/> object to return. The
/// contract name is also derived from this type parameter.
/// </typeparam>
/// <typeparam name="TMetadataView">
/// The type of the metadata view of the <see cref="Lazy{T, TMetadataView}"/> object
/// to return.
/// </typeparam>
/// <returns>
/// The <see cref="Lazy{T, TMetadataView}"/> object with the contract name derived
/// from <typeparamref name="T"/>.
/// </returns>
/// <remarks>
/// <para>
/// The contract name is the result of calling
/// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
/// </para>
/// <para>
/// The contract name is compared using a case-sensitive, non-linguistic comparison
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
/// <exception cref="ImportCardinalityMismatchException">
/// <para>
/// There are zero <see cref="Lazy{T, TMetadataView}"/> objects with the contract
/// name derived from <typeparamref name="T"/> in the
/// <see cref="CompositionContainer"/>.
/// </para>
/// -or-
/// <para>
/// There are more than one <see cref="Lazy{T, TMetadataView}"/> objects with the
/// contract name derived from <typeparamref name="T"/> in the
/// <see cref="CompositionContainer"/>.
/// </para>
/// </exception>
/// <exception cref="InvalidOperationException">
/// <typeparamref name="TMetadataView"/> is not a valid metadata view type.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
public Lazy<T, TMetadataView> GetExport<T, TMetadataView>()
{
return GetExport<T, TMetadataView>((string)null);
}
/// <summary>
/// Returns the export with the specified contract name, throwing an exception if there
/// is not exactly one matching export.
/// </summary>
/// <typeparam name="T">
/// The type of the <see cref="Lazy{T, TMetadataView}"/> object to return.
/// </typeparam>
/// <typeparam name="TMetadataView">
/// The type of the metadata view of the <see cref="Lazy{T, TMetadataView}"/> object
/// to return.
/// </typeparam>
/// <param name="contractName">
/// A <see cref="String"/> containing the contract name of the
/// <see cref="Lazy{T, TMetadataView}"/> object to return; or <see langword="null"/>
/// or an empty string ("") to use the default contract name.
/// </param>
/// <returns>
/// The <see cref="Lazy{T, TMetadataView}"/> object with the specified contract name.
/// </returns>
/// <remarks>
/// <para>
/// The default contract name is the result of calling
/// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
/// </para>
/// <para>
/// The contract name is compared using a case-sensitive, non-linguistic comparison
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
/// <exception cref="ImportCardinalityMismatchException">
/// <para>
/// There are zero <see cref="Lazy{T, TMetadataView}"/> objects with the
/// specified contract name in the <see cref="CompositionContainer"/>.
/// </para>
/// -or-
/// <para>
/// There are more than one <see cref="Lazy{T, TMetadataView}"/> objects with the
/// specified contract name in the <see cref="CompositionContainer"/>.
/// </para>
/// </exception>
/// <exception cref="InvalidOperationException">
/// <typeparamref name="TMetadataView"/> is not a valid metadata view type.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
public Lazy<T, TMetadataView> GetExport<T, TMetadataView>(string contractName)
{
return GetExportCore<T, TMetadataView>(contractName);
}
/// <summary>
/// Returns the exports with the specified contract name.
/// </summary>
/// <param name="type">
/// The <see cref="Type"/> of the <see cref="Export"/> objects to return.
/// </param>
/// <param name="metadataViewType">
/// The <see cref="Type"/> of the metadata view of the <see cref="Export"/> objects to
/// return.
/// </param>
/// <param name="contractName">
/// A <see cref="String"/> containing the contract name of the
/// <see cref="Export"/> object to return; or <see langword="null"/>
/// or an empty string ("") to use the default contract name.
/// </param>
/// <returns>
/// An <see cref="IEnumerable{T}"/> containing the <see cref="Lazy{Object, Object}"/> objects
/// with the specified contract name, if found; otherwise, an empty
/// <see cref="IEnumerable{T}"/>.
/// </returns>
/// <remarks>
/// <para>
/// The returned <see cref="Export"/> objects are instances of
/// <see cref="Lazy{T, TMetadataView}"/> underneath, where <c>T</c>
/// is <paramref name="type"/> and <c>TMetadataView</c> is
/// <paramref name="metadataViewType"/>.
/// </para>
/// <para>
/// The default contract name is the result of calling
/// <see cref="AttributedModelServices.GetContractName(Type)"/> on <paramref name="type"/>.
/// </para>
/// <para>
/// The contract name is compared using a case-sensitive, non-linguistic comparison
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="type"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// <paramref name="metadataViewType"/> is not a valid metadata view type.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1006")]
public IEnumerable<Lazy<object, object>> GetExports(Type type, Type metadataViewType, string contractName)
{
IEnumerable<Export> exports = GetExportsCore(type, metadataViewType, contractName, ImportCardinality.ZeroOrMore);
Collection<Lazy<object, object>> result = new Collection<Lazy<object, object>>();
Func<Export, Lazy<object, object>> typedExportFactory = ExportServices.CreateSemiStronglyTypedLazyFactory(type, metadataViewType);
foreach (Export export in exports)
{
result.Add(typedExportFactory.Invoke(export));
}
return result;
}
/// <summary>
/// Returns the exports with the contract name derived from the specified type parameter.
/// </summary>
/// <typeparam name="T">
/// The type of the <see cref="Lazy{T}"/> objects to return. The contract name is also
/// derived from this type parameter.
/// </typeparam>
/// <returns>
/// An <see cref="IEnumerable{T}"/> containing the <see cref="Lazy{T}"/> objects
/// with the contract name derived from <typeparamref name="T"/>, if found; otherwise,
/// an empty <see cref="IEnumerable{T}"/>.
/// </returns>
/// <remarks>
/// <para>
/// The returned <see cref="Lazy{T}"/> objects are instances of
/// <see cref="Lazy{T, TMetadataView}"/> underneath, where
/// <c>TMetadataView</c>
/// is <see cref="IDictionary{TKey, TValue}"/> and where <c>TKey</c>
/// is <see cref="String"/> and <c>TValue</c> is <see cref="Object"/>.
/// </para>
/// <para>
/// The contract name is the result of calling
/// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
/// </para>
/// <para>
/// The contract name is compared using a case-sensitive, non-linguistic comparison
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1006")]
public IEnumerable<Lazy<T>> GetExports<T>()
{
return GetExports<T>((string)null);
}
/// <summary>
/// Returns the exports with the specified contract name.
/// </summary>
/// <typeparam name="T">
/// The type of the <see cref="Lazy{T}"/> objects to return.
/// </typeparam>
/// <param name="contractName">
/// A <see cref="String"/> containing the contract name of the <see cref="Lazy{T}"/>
/// objects to return; or <see langword="null"/> or an empty string ("") to use the
/// default contract name.
/// </param>
/// <returns>
/// An <see cref="IEnumerable{T}"/> containing the <see cref="Lazy{T}"/> objects
/// with the specified contract name, if found; otherwise, an empty
/// <see cref="IEnumerable{T}"/>.
/// </returns>
/// <remarks>
/// <para>
/// The returned <see cref="Lazy{T}"/> objects are instances of
/// <see cref="Lazy{T, TMetadataView}"/> underneath, where
/// <c>TMetadataView</c>
/// is <see cref="IDictionary{TKey, TValue}"/> and where <c>TKey</c>
/// is <see cref="String"/> and <c>TValue</c> is <see cref="Object"/>.
/// </para>
/// <para>
/// The default contract name is the result of calling
/// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
/// </para>
/// <para>
/// The contract name is compared using a case-sensitive, non-linguistic comparison
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1006")]
public IEnumerable<Lazy<T>> GetExports<T>(string contractName)
{
return GetExportsCore<T>(contractName);
}
/// <summary>
/// Returns the exports with the contract name derived from the specified type parameter.
/// </summary>
/// <typeparam name="T">
/// The type of the <see cref="Lazy{T, TMetadataView}"/> objects to return. The
/// contract name is also derived from this type parameter.
/// </typeparam>
/// <typeparam name="TMetadataView">
/// The type of the metadata view of the <see cref="Lazy{T, TMetadataView}"/> objects
/// to return.
/// </typeparam>
/// <returns>
/// An <see cref="IEnumerable{T}"/> containing the
/// <see cref="Lazy{T, TMetadataView}"/> objects with the contract name derived from
/// <typeparamref name="T"/>, if found; otherwise, an empty
/// <see cref="IEnumerable{T}"/>.
/// </returns>
/// <remarks>
/// <para>
/// The contract name is the result of calling
/// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
/// </para>
/// <para>
/// The contract name is compared using a case-sensitive, non-linguistic comparison
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
/// <exception cref="InvalidOperationException">
/// <typeparamref name="TMetadataView"/> is not a valid metadata view type.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1006")]
public IEnumerable<Lazy<T, TMetadataView>> GetExports<T, TMetadataView>()
{
return GetExports<T, TMetadataView>((string)null);
}
/// <summary>
/// Returns the exports with the specified contract name.
/// </summary>
/// <typeparam name="T">
/// The type of the <see cref="Lazy{T, TMetadataView}"/> objects to return. The
/// contract name is also derived from this type parameter.
/// </typeparam>
/// <typeparam name="TMetadataView">
/// The type of the metadata view of the <see cref="Lazy{T, TMetadataView}"/> objects
/// to return.
/// </typeparam>
/// <param name="contractName">
/// A <see cref="String"/> containing the contract name of the
/// <see cref="Lazy{T, TMetadataView}"/> objects to return; or <see langword="null"/>
/// or an empty string ("") to use the default contract name.
/// </param>
/// <returns>
/// An <see cref="IEnumerable{T}"/> containing the
/// <see cref="Lazy{T, TMetadataView}"/> objects with the specified contract name if
/// found; otherwise, an empty <see cref="IEnumerable{T}"/>.
/// </returns>
/// <remarks>
/// <para>
/// The default contract name is the result of calling
/// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
/// </para>
/// <para>
/// The contract name is compared using a case-sensitive, non-linguistic comparison
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
/// <exception cref="InvalidOperationException">
/// <typeparamref name="TMetadataView"/> is not a valid metadata view type.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1006")]
public IEnumerable<Lazy<T, TMetadataView>> GetExports<T, TMetadataView>(string contractName)
{
return GetExportsCore<T, TMetadataView>(contractName);
}
/// <summary>
/// Returns the exported value with the contract name derived from the specified type
/// parameter, throwing an exception if there is not exactly one matching exported value.
/// </summary>
/// <typeparam name="T">
/// The type of the exported value to return. The contract name is also
/// derived from this type parameter.
/// </typeparam>
/// <returns>
/// The exported <see cref="Object"/> with the contract name derived from
/// <typeparamref name="T"/>.
/// </returns>
/// <remarks>
/// <para>
/// The contract name is the result of calling
/// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
/// </para>
/// <para>
/// The contract name is compared using a case-sensitive, non-linguistic comparison
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
/// <exception cref="CompositionContractMismatchException">
/// The underlying exported value cannot be cast to <typeparamref name="T"/>.
/// </exception>
/// <exception cref="ImportCardinalityMismatchException">
/// <para>
/// There are zero exported values with the contract name derived from
/// <typeparamref name="T"/> in the <see cref="CompositionContainer"/>.
/// </para>
/// -or-
/// <para>
/// There are more than one exported values with the contract name derived from
/// <typeparamref name="T"/> in the <see cref="CompositionContainer"/>.
/// </para>
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
/// <exception cref="CompositionException">
/// An error occurred during composition. <see cref="CompositionException.Errors"/> will
/// contain a collection of errors that occurred.
/// </exception>
public T GetExportedValue<T>()
{
return GetExportedValue<T>((string)null);
}
/// <summary>
/// Returns the exported value with the specified contract name, throwing an exception
/// if there is not exactly one matching exported value.
/// </summary>
/// <typeparam name="T">
/// The type of the exported value to return.
/// </typeparam>
/// <param name="contractName">
/// A <see cref="String"/> containing the contract name of the exported value to return,
/// or <see langword="null"/> or an empty string ("") to use the default contract name.
/// </param>
/// <returns>
/// The exported <see cref="Object"/> with the specified contract name.
/// </returns>
/// <remarks>
/// <para>
/// The default contract name is the result of calling
/// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
/// </para>
/// <para>
/// The contract name is compared using a case-sensitive, non-linguistic comparison
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
/// <exception cref="CompositionContractMismatchException">
/// The underlying exported value cannot be cast to <typeparamref name="T"/>.
/// </exception>
/// <exception cref="ImportCardinalityMismatchException">
/// <para>
/// There are zero exported values with the specified contract name in the
/// <see cref="CompositionContainer"/>.
/// </para>
/// -or-
/// <para>
/// There are more than one exported values with the specified contract name in the
/// <see cref="CompositionContainer"/>.
/// </para>
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
/// <exception cref="CompositionException">
/// An error occurred during composition. <see cref="CompositionException.Errors"/> will
/// contain a collection of errors that occurred.
/// </exception>
public T GetExportedValue<T>(string contractName)
{
return GetExportedValueCore<T>(contractName, ImportCardinality.ExactlyOne);
}
/// <summary>
/// Returns the exported value with the contract name derived from the specified type
/// parameter, throwing an exception if there is more than one matching exported value.
/// </summary>
/// <typeparam name="T">
/// The type of the exported value to return. The contract name is also
/// derived from this type parameter.
/// </typeparam>
/// <returns>
/// The exported <see cref="Object"/> with the contract name derived from
/// <typeparamref name="T"/>, if found; otherwise, the default value for
/// <typeparamref name="T"/>.
/// </returns>
/// <remarks>
/// <para>
/// If the exported value is not found, then this method returns the appropriate
/// default value for <typeparamref name="T"/>; for example, 0 (zero) for integer
/// types, <see langword="false"/> for Boolean types, and <see langword="null"/>
/// for reference types.
/// </para>
/// <para>
/// The contract name is the result of calling
/// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
/// </para>
/// <para>
/// The contract name is compared using a case-sensitive, non-linguistic comparison
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
/// <exception cref="CompositionContractMismatchException">
/// The underlying exported value cannot be cast to <typeparamref name="T"/>.
/// </exception>
/// <exception cref="ImportCardinalityMismatchException">
/// <para>
/// There are more than one exported values with the contract name derived from
/// <typeparamref name="T"/> in the <see cref="CompositionContainer"/>.
/// </para>
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
/// <exception cref="CompositionException">
/// An error occurred during composition. <see cref="CompositionException.Errors"/> will
/// contain a collection of errors that occurred.
/// </exception>
public T GetExportedValueOrDefault<T>()
{
return GetExportedValueOrDefault<T>((string)null);
}
/// <summary>
/// Returns the exported value with the specified contract name, throwing an exception
/// if there is more than one matching exported value.
/// </summary>
/// <typeparam name="T">
/// The type of the exported value to return.
/// </typeparam>
/// <param name="contractName">
/// A <see cref="String"/> containing the contract name of the exported value to return,
/// or <see langword="null"/> or an empty string ("") to use the default contract name.
/// </param>
/// <returns>
/// The exported <see cref="Object"/> with the specified contract name, if found;
/// otherwise, the default value for <typeparamref name="T"/>.
/// </returns>
/// <remarks>
/// <para>
/// If the exported value is not found, then this method returns the appropriate
/// default value for <typeparamref name="T"/>; for example, 0 (zero) for integer
/// types, <see langword="false"/> for Boolean types, and <see langword="null"/>
/// for reference types.
/// </para>
/// <para>
/// The default contract name is the result of calling
/// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
/// </para>
/// <para>
/// The contract name is compared using a case-sensitive, non-linguistic comparison
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
/// <exception cref="CompositionContractMismatchException">
/// The underlying exported value cannot be cast to <typeparamref name="T"/>.
/// </exception>
/// <exception cref="ImportCardinalityMismatchException">
/// There are more than one exported values with the specified contract name in the
/// <see cref="CompositionContainer"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
/// <exception cref="CompositionException">
/// An error occurred during composition. <see cref="CompositionException.Errors"/> will
/// contain a collection of errors that occurred.
/// </exception>
public T GetExportedValueOrDefault<T>(string contractName)
{
return GetExportedValueCore<T>(contractName, ImportCardinality.ZeroOrOne);
}
/// <summary>
/// Returns the exported values with the contract name derived from the specified type
/// parameter.
/// </summary>
/// <typeparam name="T">
/// The type of the exported value to return. The contract name is also
/// derived from this type parameter.
/// </typeparam>
/// <returns>
/// An <see cref="Collection{T}"/> containing the exported values with the contract name
/// derived from the specified type parameter, if found; otherwise, an empty
/// <see cref="Collection{T}"/>.
/// </returns>
/// <remarks>
/// <para>
/// The contract name is the result of calling
/// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
/// </para>
/// <para>
/// The contract name is compared using a case-sensitive, non-linguistic comparison
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
/// <exception cref="CompositionContractMismatchException">
/// One or more of the underlying exported values cannot be cast to
/// <typeparamref name="T"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
/// <exception cref="CompositionException">
/// An error occurred during composition. <see cref="CompositionException.Errors"/> will
/// contain a collection of errors that occurred.
/// </exception>
public IEnumerable<T> GetExportedValues<T>()
{
return GetExportedValues<T>((string)null);
}
/// <summary>
/// Returns the exported values with the specified contract name.
/// </summary>
/// <typeparam name="T">
/// The type of the exported value to return.
/// </typeparam>
/// <param name="contractName">
/// A <see cref="String"/> containing the contract name of the exported values to
/// return; or <see langword="null"/> or an empty string ("") to use the default
/// contract name.
/// </param>
/// <returns>
/// An <see cref="Collection{T}"/> containing the exported values with the specified
/// contract name, if found; otherwise, an empty <see cref="Collection{T}"/>.
/// </returns>
/// <remarks>
/// <para>
/// The default contract name is the result of calling
/// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
/// </para>
/// <para>
/// The contract name is compared using a case-sensitive, non-linguistic comparison
/// using <see cref="StringComparer.Ordinal"/>.
/// </para>
/// </remarks>
/// <exception cref="CompositionContractMismatchException">
/// One or more of the underlying exported values cannot be cast to
/// <typeparamref name="T"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
/// <exception cref="CompositionException">
/// An error occurred during composition. <see cref="CompositionException.Errors"/> will
/// contain a collection of errors that occurred.
/// </exception>
public IEnumerable<T> GetExportedValues<T>(string contractName)
{
return GetExportedValuesCore<T>(contractName);
}
private IEnumerable<T> GetExportedValuesCore<T>(string contractName)
{
IEnumerable<Export> exports = GetExportsCore(typeof(T), (Type)null, contractName, ImportCardinality.ZeroOrMore);
Collection<T> result = new Collection<T>();
foreach (Export export in exports)
{
result.Add(ExportServices.GetCastedExportedValue<T>(export));
}
return result;
}
private T GetExportedValueCore<T>(string contractName, ImportCardinality cardinality)
{
if (!cardinality.IsAtMostOne())
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
Export export = GetExportsCore(typeof(T), (Type)null, contractName, cardinality).SingleOrDefault();
return (export != null) ? ExportServices.GetCastedExportedValue<T>(export) : default(T);
}
private IEnumerable<Lazy<T>> GetExportsCore<T>(string contractName)
{
IEnumerable<Export> exports = GetExportsCore(typeof(T), (Type)null, contractName, ImportCardinality.ZeroOrMore);
Collection<Lazy<T>> result = new Collection<Lazy<T>>();
foreach (Export export in exports)
{
result.Add(ExportServices.CreateStronglyTypedLazyOfT<T>(export));
}
return result;
}
private IEnumerable<Lazy<T, TMetadataView>> GetExportsCore<T, TMetadataView>(string contractName)
{
IEnumerable<Export> exports = GetExportsCore(typeof(T), typeof(TMetadataView), contractName, ImportCardinality.ZeroOrMore);
Collection<Lazy<T, TMetadataView>> result = new Collection<Lazy<T, TMetadataView>>();
foreach (Export export in exports)
{
result.Add(ExportServices.CreateStronglyTypedLazyOfTM<T, TMetadataView>(export));
}
return result;
}
private Lazy<T, TMetadataView> GetExportCore<T, TMetadataView>(string contractName)
{
Export export = GetExportsCore(typeof(T), typeof(TMetadataView), contractName, ImportCardinality.ExactlyOne).SingleOrDefault();
return (export != null) ? ExportServices.CreateStronglyTypedLazyOfTM<T, TMetadataView>(export) : null;
}
private Lazy<T> GetExportCore<T>(string contractName)
{
Export export = GetExportsCore(typeof(T), null, contractName, ImportCardinality.ExactlyOne).SingleOrDefault();
return (export != null) ? ExportServices.CreateStronglyTypedLazyOfT<T>(export) : null;
}
private IEnumerable<Export> GetExportsCore(Type type, Type metadataViewType, string contractName, ImportCardinality cardinality)
{
// Only 'type' cannot be null - the other parameters have sensible defaults.
Requires.NotNull(type, nameof(type));
if (string.IsNullOrEmpty(contractName))
{
contractName = AttributedModelServices.GetContractName(type);
}
if (metadataViewType == null)
{
metadataViewType = ExportServices.DefaultMetadataViewType;
}
if (!MetadataViewProvider.IsViewTypeValid(metadataViewType))
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.InvalidMetadataView, metadataViewType.Name));
}
ImportDefinition importDefinition = BuildImportDefinition(type, metadataViewType, contractName, cardinality);
return GetExports(importDefinition, null);
}
private static ImportDefinition BuildImportDefinition(Type type, Type metadataViewType, string contractName, ImportCardinality cardinality)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (metadataViewType == null)
{
throw new ArgumentNullException(nameof(metadataViewType));
}
if (contractName == null)
{
throw new ArgumentNullException(nameof(contractName));
}
IEnumerable<KeyValuePair<string, Type>> requiredMetadata = CompositionServices.GetRequiredMetadata(metadataViewType);
IDictionary<string, object> metadata = CompositionServices.GetImportMetadata(type, null);
string requiredTypeIdentity = null;
if (type != typeof(object))
{
requiredTypeIdentity = AttributedModelServices.GetTypeIdentity(type);
}
return new ContractBasedImportDefinition(contractName, requiredTypeIdentity, requiredMetadata, cardinality, false, true, CreationPolicy.Any, metadata);
}
}
}
| |
namespace zenQuery
{
partial class frmAbout
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmAbout));
this.tableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.labelProductName = new System.Windows.Forms.Label();
this.labelVersion = new System.Windows.Forms.Label();
this.labelCopyright = new System.Windows.Forms.Label();
this.textBoxDescription = new System.Windows.Forms.TextBox();
this.okButton = new System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.panel2 = new System.Windows.Forms.Panel();
this.panel3 = new System.Windows.Forms.Panel();
this.panel4 = new System.Windows.Forms.Panel();
this.panel5 = new System.Windows.Forms.Panel();
this.linkLabel1 = new System.Windows.Forms.LinkLabel();
this.tableLayoutPanel.SuspendLayout();
this.SuspendLayout();
//
// tableLayoutPanel
//
this.tableLayoutPanel.ColumnCount = 2;
this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 6.581353F));
this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 93.41865F));
this.tableLayoutPanel.Controls.Add(this.labelProductName, 1, 0);
this.tableLayoutPanel.Controls.Add(this.labelVersion, 1, 1);
this.tableLayoutPanel.Controls.Add(this.labelCopyright, 1, 2);
this.tableLayoutPanel.Controls.Add(this.textBoxDescription, 1, 4);
this.tableLayoutPanel.Controls.Add(this.okButton, 1, 5);
this.tableLayoutPanel.Controls.Add(this.panel1, 0, 0);
this.tableLayoutPanel.Controls.Add(this.panel2, 0, 1);
this.tableLayoutPanel.Controls.Add(this.panel3, 0, 2);
this.tableLayoutPanel.Controls.Add(this.panel4, 0, 3);
this.tableLayoutPanel.Controls.Add(this.panel5, 0, 4);
this.tableLayoutPanel.Controls.Add(this.linkLabel1, 1, 3);
this.tableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel.Location = new System.Drawing.Point(9, 9);
this.tableLayoutPanel.Name = "tableLayoutPanel";
this.tableLayoutPanel.RowCount = 6;
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.Size = new System.Drawing.Size(547, 373);
this.tableLayoutPanel.TabIndex = 0;
//
// labelProductName
//
this.labelProductName.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelProductName.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelProductName.Location = new System.Drawing.Point(42, 0);
this.labelProductName.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0);
this.labelProductName.MaximumSize = new System.Drawing.Size(0, 17);
this.labelProductName.Name = "labelProductName";
this.labelProductName.Size = new System.Drawing.Size(502, 17);
this.labelProductName.TabIndex = 19;
this.labelProductName.Text = "Product Name";
this.labelProductName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// labelVersion
//
this.labelVersion.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelVersion.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
this.labelVersion.Location = new System.Drawing.Point(42, 37);
this.labelVersion.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0);
this.labelVersion.MaximumSize = new System.Drawing.Size(0, 17);
this.labelVersion.Name = "labelVersion";
this.labelVersion.Size = new System.Drawing.Size(502, 17);
this.labelVersion.TabIndex = 0;
this.labelVersion.Text = "Version";
this.labelVersion.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// labelCopyright
//
this.labelCopyright.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelCopyright.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
this.labelCopyright.Location = new System.Drawing.Point(42, 74);
this.labelCopyright.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0);
this.labelCopyright.MaximumSize = new System.Drawing.Size(0, 17);
this.labelCopyright.Name = "labelCopyright";
this.labelCopyright.Size = new System.Drawing.Size(502, 17);
this.labelCopyright.TabIndex = 21;
this.labelCopyright.Text = "Copyright";
this.labelCopyright.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// textBoxDescription
//
this.textBoxDescription.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBoxDescription.Location = new System.Drawing.Point(42, 151);
this.textBoxDescription.Margin = new System.Windows.Forms.Padding(6, 3, 3, 3);
this.textBoxDescription.Multiline = true;
this.textBoxDescription.Name = "textBoxDescription";
this.textBoxDescription.ReadOnly = true;
this.textBoxDescription.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.textBoxDescription.Size = new System.Drawing.Size(502, 180);
this.textBoxDescription.TabIndex = 23;
this.textBoxDescription.TabStop = false;
this.textBoxDescription.Text = resources.GetString("textBoxDescription.Text");
//
// okButton
//
this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.okButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.okButton.Location = new System.Drawing.Point(469, 347);
this.okButton.Name = "okButton";
this.okButton.Size = new System.Drawing.Size(75, 23);
this.okButton.TabIndex = 24;
this.okButton.Text = "&OK";
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.panel1.Location = new System.Drawing.Point(3, 3);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(29, 31);
this.panel1.TabIndex = 25;
//
// panel2
//
this.panel2.BackColor = System.Drawing.Color.Silver;
this.panel2.Location = new System.Drawing.Point(3, 40);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(29, 31);
this.panel2.TabIndex = 26;
//
// panel3
//
this.panel3.BackColor = System.Drawing.Color.Gray;
this.panel3.Location = new System.Drawing.Point(3, 77);
this.panel3.Name = "panel3";
this.panel3.Size = new System.Drawing.Size(29, 31);
this.panel3.TabIndex = 27;
//
// panel4
//
this.panel4.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.panel4.Location = new System.Drawing.Point(3, 114);
this.panel4.Name = "panel4";
this.panel4.Size = new System.Drawing.Size(29, 31);
this.panel4.TabIndex = 28;
//
// panel5
//
this.panel5.BackColor = System.Drawing.Color.Black;
this.panel5.Location = new System.Drawing.Point(3, 151);
this.panel5.Name = "panel5";
this.panel5.Size = new System.Drawing.Size(29, 180);
this.panel5.TabIndex = 29;
//
// linkLabel1
//
this.linkLabel1.AutoSize = true;
this.linkLabel1.Location = new System.Drawing.Point(39, 111);
this.linkLabel1.Name = "linkLabel1";
this.linkLabel1.Size = new System.Drawing.Size(173, 13);
this.linkLabel1.TabIndex = 30;
this.linkLabel1.TabStop = true;
this.linkLabel1.Text = "http://sqlhere.com/zenquery.aspx";
//
// frmAbout
//
this.AcceptButton = this.okButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(565, 391);
this.Controls.Add(this.tableLayoutPanel);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "frmAbout";
this.Padding = new System.Windows.Forms.Padding(9);
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "About SCide";
this.Load += new System.EventHandler(this.frmAbout_Load);
this.tableLayoutPanel.ResumeLayout(false);
this.tableLayoutPanel.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel;
private System.Windows.Forms.Label labelProductName;
private System.Windows.Forms.Label labelVersion;
private System.Windows.Forms.Label labelCopyright;
private System.Windows.Forms.TextBox textBoxDescription;
private System.Windows.Forms.Button okButton;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.Panel panel4;
private System.Windows.Forms.Panel panel5;
private System.Windows.Forms.LinkLabel linkLabel1;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
namespace Umbraco.Core.PropertyEditors
{
/// <summary>
/// Defines a pre-value editor
/// </summary>
/// <remarks>
/// A pre-value editor is made up of multiple pre-value fields, each field defines a key that the value is stored against.
/// Each field can have any editor and the value from each field can store any data such as a simple string or a json structure.
///
/// The Json serialization attributes are required for manifest property editors to work.
/// </remarks>
public class PreValueEditor
{
public PreValueEditor()
{
var fields = new List<PreValueField>();
//the ctor checks if we have PreValueFieldAttributes applied and if so we construct our fields from them
var props = TypeHelper.CachedDiscoverableProperties(GetType())
.Where(x => x.Name != "Fields");
foreach (var p in props)
{
var att = p.GetCustomAttributes(typeof (PreValueFieldAttribute), false).OfType<PreValueFieldAttribute>().SingleOrDefault();
if (att != null)
{
if (att.PreValueFieldType != null)
{
//try to create it
try
{
var instance = (PreValueField) Activator.CreateInstance(att.PreValueFieldType);
//overwrite values if they are assigned
if (!att.Key.IsNullOrWhiteSpace())
{
instance.Key = att.Key;
}
//if the key is still empty then assign it to be the property name
if (instance.Key.IsNullOrWhiteSpace())
{
instance.Key = p.Name;
}
if (!att.Name.IsNullOrWhiteSpace())
instance.Name = att.Name;
if (!att.View.IsNullOrWhiteSpace())
instance.View = att.View;
if (!att.Description.IsNullOrWhiteSpace())
instance.Description = att.Description;
if (att.HideLabel)
instance.HideLabel = att.HideLabel;
//add the custom field
fields.Add(instance);
}
catch (Exception ex)
{
LogHelper.WarnWithException<PreValueEditor>("Could not create an instance of " + att.PreValueFieldType, ex);
}
}
else
{
fields.Add(MapAttributeToField(att, p));
}
}
}
Fields = fields;
}
private static PreValueField MapAttributeToField(PreValueFieldAttribute att, PropertyInfo prop)
{
return new PreValueField
{
//set the key to the property name if it is empty
Key = att.Key.IsNullOrWhiteSpace() ? prop.Name : att.Key,
Name = att.Name,
Description = att.Description,
HideLabel = att.HideLabel,
View = att.View
};
}
/// <summary>
/// A collection of pre-value fields to be edited
/// </summary>
/// <remarks>
/// If fields are specified then the master View and Validators will be ignored
/// </remarks>
[JsonProperty("fields")]
public List<PreValueField> Fields { get; private set; }
/// <summary>
/// A method to format the posted values from the editor to the values to be persisted
/// </summary>
/// <param name="editorValue"></param>
/// <param name="currentValue">
/// The current value that has been persisted to the database for this pre-value editor. This value may be usesful for
/// how the value then get's deserialized again to be re-persisted. In most cases it will probably not be used.
/// </param>
/// <returns></returns>
/// <remarks>
/// By default this will just return the Posted editorValue.
///
/// This can be overridden if perhaps you have a comma delimited string posted value but want to convert those to individual rows, or to convert
/// a json structure to multiple rows.
/// </remarks>
public virtual IDictionary<string, PreValue> ConvertEditorToDb(IDictionary<string, object> editorValue, PreValueCollection currentValue)
{
//convert to a string based value to be saved in the db
return editorValue.ToDictionary(x => x.Key, x => new PreValue(x.Value == null ? null : x.Value.ToString()));
}
/// <summary>
/// This can be used to re-format the currently saved pre-values that will be passed to the editor,
/// by default this returns the merged default and persisted pre-values.
/// </summary>
/// <param name="defaultPreVals">
/// The default/static pre-vals for the property editor
/// </param>
/// <param name="persistedPreVals">
/// The persisted pre-vals for the property editor
/// </param>
/// <returns></returns>
/// <remarks>
/// This is generally not going to be used by anything unless a property editor wants to change the merging
/// functionality or needs to convert some legacy persisted data, or convert the string values to strongly typed values in json (i.e. booleans)
///
/// IMPORTANT! When using this method the default pre values dictionary should not be modified which would change the property editor's global
/// singleton pre-values!
/// </remarks>
public virtual IDictionary<string, object> ConvertDbToEditor(IDictionary<string, object> defaultPreVals, PreValueCollection persistedPreVals)
{
//we'll make a copy since we'll merge into the defaults - but we don't want to overwrite the global singleton ones passed in!
var defaultPreValCopy = new Dictionary<string, object>();
if (defaultPreVals != null)
{
defaultPreValCopy = new Dictionary<string, object>(defaultPreVals);
}
if (persistedPreVals.IsDictionaryBased)
{
//we just need to merge the dictionaries now, the persisted will replace default.
foreach (var item in persistedPreVals.PreValuesAsDictionary)
{
//The persisted dictionary contains values of type PreValue which contain the ID and the Value, we don't care
// about the Id, just the value so ignore the id.
defaultPreValCopy[item.Key] = item.Value.Value;
}
//now we're going to try to see if any of the values are JSON, if they are we'll convert them to real JSON objects
// so they can be consumed as real json in angular!
ConvertItemsToJsonIfDetected(defaultPreValCopy);
return defaultPreValCopy;
}
//it's an array so need to format it
var result = new Dictionary<string, object>();
var asArray = persistedPreVals.PreValuesAsArray.ToArray();
for (var i = 0; i < asArray.Length; i++)
{
//each item is of type PreValue but we don't want the ID, just the value so ignore the ID
result.Add(i.ToInvariantString(), asArray[i].Value);
}
//now we're going to try to see if any of the values are JSON, if they are we'll convert them to real JSON objects
// so they can be consumed as real json in angular!
ConvertItemsToJsonIfDetected(result);
return result;
}
private void ConvertItemsToJsonIfDetected(IDictionary<string, object> result)
{
//now we're going to try to see if any of the values are JSON, if they are we'll convert them to real JSON objects
// so they can be consumed as real json in angular!
var keys = result.Keys.ToArray();
for (var i = 0; i < keys.Length; i++)
{
if (result[keys[i]] is string)
{
var asString = result[keys[i]].ToString();
if (asString.DetectIsJson())
{
try
{
var json = JsonConvert.DeserializeObject(asString);
result[keys[i]] = json;
}
catch
{
//swallow this exception, we thought it was json but it really isn't so continue returning a string
}
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
namespace System.Collections.Immutable
{
/// <summary>
/// A set of initialization methods for instances of <see cref="ImmutableArray{T}"/>.
/// </summary>
public static class ImmutableArray
{
/// <summary>
/// A two element array useful for throwing exceptions the way LINQ does.
/// </summary>
internal static readonly byte[] TwoElementArray = new byte[2];
/// <summary>
/// Creates an empty <see cref="ImmutableArray{T}"/>.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <returns>An empty array.</returns>
[Pure]
public static ImmutableArray<T> Create<T>()
{
return ImmutableArray<T>.Empty;
}
/// <summary>
/// Creates an <see cref="ImmutableArray{T}"/> with the specified element as its only member.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <param name="item">The element to store in the array.</param>
/// <returns>A 1-element array.</returns>
[Pure]
public static ImmutableArray<T> Create<T>(T item)
{
T[] array = new[] { item };
return new ImmutableArray<T>(array);
}
/// <summary>
/// Creates an <see cref="ImmutableArray{T}"/> with the specified elements.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <param name="item1">The first element to store in the array.</param>
/// <param name="item2">The second element to store in the array.</param>
/// <returns>A 2-element array.</returns>
[Pure]
public static ImmutableArray<T> Create<T>(T item1, T item2)
{
T[] array = new[] { item1, item2 };
return new ImmutableArray<T>(array);
}
/// <summary>
/// Creates an <see cref="ImmutableArray{T}"/> with the specified elements.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <param name="item1">The first element to store in the array.</param>
/// <param name="item2">The second element to store in the array.</param>
/// <param name="item3">The third element to store in the array.</param>
/// <returns>A 3-element array.</returns>
[Pure]
public static ImmutableArray<T> Create<T>(T item1, T item2, T item3)
{
T[] array = new[] { item1, item2, item3 };
return new ImmutableArray<T>(array);
}
/// <summary>
/// Creates an <see cref="ImmutableArray{T}"/> with the specified elements.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <param name="item1">The first element to store in the array.</param>
/// <param name="item2">The second element to store in the array.</param>
/// <param name="item3">The third element to store in the array.</param>
/// <param name="item4">The fourth element to store in the array.</param>
/// <returns>A 4-element array.</returns>
[Pure]
public static ImmutableArray<T> Create<T>(T item1, T item2, T item3, T item4)
{
T[] array = new[] { item1, item2, item3, item4 };
return new ImmutableArray<T>(array);
}
/// <summary>
/// Creates an <see cref="ImmutableArray{T}"/> populated with the contents of the specified sequence.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <param name="items">The elements to store in the array.</param>
/// <returns>An immutable array.</returns>
[Pure]
public static ImmutableArray<T> CreateRange<T>(IEnumerable<T> items)
{
Requires.NotNull(items, nameof(items));
// As an optimization, if the provided enumerable is actually a
// boxed ImmutableArray<T> instance, reuse the underlying array if possible.
// Note that this allows for automatic upcasting and downcasting of arrays
// where the CLR allows it.
var immutableArray = items as IImmutableArray;
if (immutableArray != null)
{
immutableArray.ThrowInvalidOperationIfNotInitialized();
// immutableArray.Array must not be null at this point, and we know it's an
// ImmutableArray<T> or ImmutableArray<SomethingDerivedFromT> as they are
// the only types that could be both IEnumerable<T> and IImmutableArray.
// As such, we know that items is either an ImmutableArray<T> or
// ImmutableArray<TypeDerivedFromT>, and we can cast the array to T[].
return new ImmutableArray<T>((T[])immutableArray.Array);
}
// We don't recognize the source as an array that is safe to use.
// So clone the sequence into an array and return an immutable wrapper.
int count;
if (items.TryGetCount(out count))
{
if (count == 0)
{
// Return a wrapper around the singleton empty array.
return Create<T>();
}
else
{
// We know how long the sequence is. Linq's built-in ToArray extension method
// isn't as comprehensive in finding the length as we are, so call our own method
// to avoid reallocating arrays as the sequence is enumerated.
return new ImmutableArray<T>(items.ToArray(count));
}
}
else
{
return new ImmutableArray<T>(items.ToArray());
}
}
/// <summary>
/// Creates an empty <see cref="ImmutableArray{T}"/>.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <param name="items">The elements to store in the array.</param>
/// <returns>An immutable array.</returns>
[Pure]
public static ImmutableArray<T> Create<T>(params T[] items)
{
if (items == null)
{
return Create<T>();
}
// We can't trust that the array passed in will never be mutated by the caller.
// The caller may have passed in an array explicitly (not relying on compiler params keyword)
// and could then change the array after the call, thereby violating the immutable
// guarantee provided by this struct. So we always copy the array to ensure it won't ever change.
return CreateDefensiveCopy(items);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct.
/// </summary>
/// <param name="items">The array to initialize the array with. A defensive copy is made.</param>
/// <param name="start">The index of the first element in the source array to include in the resulting array.</param>
/// <param name="length">The number of elements from the source array to include in the resulting array.</param>
/// <remarks>
/// This overload allows helper methods or custom builder classes to efficiently avoid paying a redundant
/// tax for copying an array when the new array is a segment of an existing array.
/// </remarks>
[Pure]
public static ImmutableArray<T> Create<T>(T[] items, int start, int length)
{
Requires.NotNull(items, nameof(items));
Requires.Range(start >= 0 && start <= items.Length, nameof(start));
Requires.Range(length >= 0 && start + length <= items.Length, nameof(length));
if (length == 0)
{
// Avoid allocating an array.
return Create<T>();
}
var array = new T[length];
for (int i = 0; i < length; i++)
{
array[i] = items[start + i];
}
return new ImmutableArray<T>(array);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct.
/// </summary>
/// <param name="items">The array to initialize the array with.
/// The selected array segment may be copied into a new array.</param>
/// <param name="start">The index of the first element in the source array to include in the resulting array.</param>
/// <param name="length">The number of elements from the source array to include in the resulting array.</param>
/// <remarks>
/// This overload allows helper methods or custom builder classes to efficiently avoid paying a redundant
/// tax for copying an array when the new array is a segment of an existing array.
/// </remarks>
[Pure]
public static ImmutableArray<T> Create<T>(ImmutableArray<T> items, int start, int length)
{
Requires.Range(start >= 0 && start <= items.Length, nameof(start));
Requires.Range(length >= 0 && start + length <= items.Length, nameof(length));
if (length == 0)
{
return Create<T>();
}
if (start == 0 && length == items.Length)
{
return items;
}
var array = new T[length];
Array.Copy(items.array, start, array, 0, length);
return new ImmutableArray<T>(array);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct.
/// </summary>
/// <param name="items">The source array to initialize the resulting array with.</param>
/// <param name="selector">The function to apply to each element from the source array.</param>
/// <remarks>
/// This overload allows efficient creation of an <see cref="ImmutableArray{T}"/> based on an existing
/// <see cref="ImmutableArray{T}"/>, where a mapping function needs to be applied to each element from
/// the source array.
/// </remarks>
[Pure]
public static ImmutableArray<TResult> CreateRange<TSource, TResult>(ImmutableArray<TSource> items, Func<TSource, TResult> selector)
{
Requires.NotNull(selector, nameof(selector));
int length = items.Length;
if (length == 0)
{
return Create<TResult>();
}
var array = new TResult[length];
for (int i = 0; i < length; i++)
{
array[i] = selector(items[i]);
}
return new ImmutableArray<TResult>(array);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct.
/// </summary>
/// <param name="items">The source array to initialize the resulting array with.</param>
/// <param name="start">The index of the first element in the source array to include in the resulting array.</param>
/// <param name="length">The number of elements from the source array to include in the resulting array.</param>
/// <param name="selector">The function to apply to each element from the source array included in the resulting array.</param>
/// <remarks>
/// This overload allows efficient creation of an <see cref="ImmutableArray{T}"/> based on a slice of an existing
/// <see cref="ImmutableArray{T}"/>, where a mapping function needs to be applied to each element from the source array
/// included in the resulting array.
/// </remarks>
[Pure]
public static ImmutableArray<TResult> CreateRange<TSource, TResult>(ImmutableArray<TSource> items, int start, int length, Func<TSource, TResult> selector)
{
int itemsLength = items.Length;
Requires.Range(start >= 0 && start <= itemsLength, nameof(start));
Requires.Range(length >= 0 && start + length <= itemsLength, nameof(length));
Requires.NotNull(selector, nameof(selector));
if (length == 0)
{
return Create<TResult>();
}
var array = new TResult[length];
for (int i = 0; i < length; i++)
{
array[i] = selector(items[i + start]);
}
return new ImmutableArray<TResult>(array);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct.
/// </summary>
/// <param name="items">The source array to initialize the resulting array with.</param>
/// <param name="selector">The function to apply to each element from the source array.</param>
/// <param name="arg">An argument to be passed to the selector mapping function.</param>
/// <remarks>
/// This overload allows efficient creation of an <see cref="ImmutableArray{T}"/> based on an existing
/// <see cref="ImmutableArray{T}"/>, where a mapping function needs to be applied to each element from
/// the source array.
/// </remarks>
[Pure]
public static ImmutableArray<TResult> CreateRange<TSource, TArg, TResult>(ImmutableArray<TSource> items, Func<TSource, TArg, TResult> selector, TArg arg)
{
Requires.NotNull(selector, nameof(selector));
int length = items.Length;
if (length == 0)
{
return Create<TResult>();
}
var array = new TResult[length];
for (int i = 0; i < length; i++)
{
array[i] = selector(items[i], arg);
}
return new ImmutableArray<TResult>(array);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct.
/// </summary>
/// <param name="items">The source array to initialize the resulting array with.</param>
/// <param name="start">The index of the first element in the source array to include in the resulting array.</param>
/// <param name="length">The number of elements from the source array to include in the resulting array.</param>
/// <param name="selector">The function to apply to each element from the source array included in the resulting array.</param>
/// <param name="arg">An argument to be passed to the selector mapping function.</param>
/// <remarks>
/// This overload allows efficient creation of an <see cref="ImmutableArray{T}"/> based on a slice of an existing
/// <see cref="ImmutableArray{T}"/>, where a mapping function needs to be applied to each element from the source array
/// included in the resulting array.
/// </remarks>
[Pure]
public static ImmutableArray<TResult> CreateRange<TSource, TArg, TResult>(ImmutableArray<TSource> items, int start, int length, Func<TSource, TArg, TResult> selector, TArg arg)
{
int itemsLength = items.Length;
Requires.Range(start >= 0 && start <= itemsLength, nameof(start));
Requires.Range(length >= 0 && start + length <= itemsLength, nameof(length));
Requires.NotNull(selector, nameof(selector));
if (length == 0)
{
return Create<TResult>();
}
var array = new TResult[length];
for (int i = 0; i < length; i++)
{
array[i] = selector(items[i + start], arg);
}
return new ImmutableArray<TResult>(array);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}.Builder"/> class.
/// </summary>
/// <typeparam name="T">The type of elements stored in the array.</typeparam>
/// <returns>A new builder.</returns>
[Pure]
public static ImmutableArray<T>.Builder CreateBuilder<T>()
{
return Create<T>().ToBuilder();
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}.Builder"/> class.
/// </summary>
/// <typeparam name="T">The type of elements stored in the array.</typeparam>
/// <param name="initialCapacity">The size of the initial array backing the builder.</param>
/// <returns>A new builder.</returns>
[Pure]
public static ImmutableArray<T>.Builder CreateBuilder<T>(int initialCapacity)
{
return new ImmutableArray<T>.Builder(initialCapacity);
}
/// <summary>
/// Enumerates a sequence exactly once and produces an immutable array of its contents.
/// </summary>
/// <typeparam name="TSource">The type of element in the sequence.</typeparam>
/// <param name="items">The sequence to enumerate.</param>
/// <returns>An immutable array.</returns>
[Pure]
public static ImmutableArray<TSource> ToImmutableArray<TSource>(this IEnumerable<TSource> items)
{
if (items is ImmutableArray<TSource>)
{
return (ImmutableArray<TSource>)items;
}
return CreateRange(items);
}
/// <summary>
/// Searches an entire one-dimensional sorted <see cref="ImmutableArray{T}"/> for a specific element,
/// using the <see cref="IComparable{T}"/> generic interface implemented by each element
/// of the <see cref="ImmutableArray{T}"/> and by the specified object.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <param name="array">The sorted, one-dimensional array to search.</param>
/// <param name="value">The object to search for.</param>
/// <returns>
/// The index of the specified <paramref name="value"/> in the specified array, if <paramref name="value"/> is found.
/// If <paramref name="value"/> is not found and <paramref name="value"/> is less than one or more elements in array,
/// a negative number which is the bitwise complement of the index of the first
/// element that is larger than <paramref name="value"/>. If <paramref name="value"/> is not found and <paramref name="value"/> is greater
/// than any of the elements in array, a negative number which is the bitwise
/// complement of (the index of the last element plus 1).
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// <paramref name="value"/> does not implement the <see cref="IComparable{T}"/> generic interface, and
/// the search encounters an element that does not implement the <see cref="IComparable{T}"/>
/// generic interface.
/// </exception>
[Pure]
public static int BinarySearch<T>(this ImmutableArray<T> array, T value)
{
return Array.BinarySearch<T>(array.array, value);
}
/// <summary>
/// Searches an entire one-dimensional sorted <see cref="ImmutableArray{T}"/> for a value using
/// the specified <see cref="IComparer{T}"/> generic interface.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <param name="array">The sorted, one-dimensional array to search.</param>
/// <param name="value">The object to search for.</param>
/// <param name="comparer">
/// The <see cref="IComparer{T}"/> implementation to use when comparing
/// elements; or null to use the <see cref="IComparable{T}"/> implementation of each
/// element.
/// </param>
/// <returns>
/// The index of the specified <paramref name="value"/> in the specified array, if <paramref name="value"/> is found.
/// If <paramref name="value"/> is not found and <paramref name="value"/> is less than one or more elements in array,
/// a negative number which is the bitwise complement of the index of the first
/// element that is larger than <paramref name="value"/>. If <paramref name="value"/> is not found and <paramref name="value"/> is greater
/// than any of the elements in array, a negative number which is the bitwise
/// complement of (the index of the last element plus 1).
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// <paramref name="comparer"/> is null, <paramref name="value"/> does not implement the <see cref="IComparable{T}"/> generic interface, and
/// the search encounters an element that does not implement the <see cref="IComparable{T}"/>
/// generic interface.
/// </exception>
[Pure]
public static int BinarySearch<T>(this ImmutableArray<T> array, T value, IComparer<T> comparer)
{
return Array.BinarySearch<T>(array.array, value, comparer);
}
/// <summary>
/// Searches a range of elements in a one-dimensional sorted <see cref="ImmutableArray{T}"/> for
/// a value, using the <see cref="IComparable{T}"/> generic interface implemented by
/// each element of the <see cref="ImmutableArray{T}"/> and by the specified value.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <param name="array">The sorted, one-dimensional array to search.</param>
/// <param name="index">The starting index of the range to search.</param>
/// <param name="length">The length of the range to search.</param>
/// <param name="value">The object to search for.</param>
/// <returns>
/// The index of the specified <paramref name="value"/> in the specified <paramref name="array"/>, if <paramref name="value"/> is found.
/// If <paramref name="value"/> is not found and <paramref name="value"/> is less than one or more elements in <paramref name="array"/>,
/// a negative number which is the bitwise complement of the index of the first
/// element that is larger than <paramref name="value"/>. If <paramref name="value"/> is not found and <paramref name="value"/> is greater
/// than any of the elements in <paramref name="array"/>, a negative number which is the bitwise
/// complement of (the index of the last element plus 1).
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// <paramref name="value"/> does not implement the <see cref="IComparable{T}"/> generic interface, and
/// the search encounters an element that does not implement the <see cref="IComparable{T}"/>
/// generic interface.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="index"/> and <paramref name="length"/> do not specify a valid range in <paramref name="array"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is less than the lower bound of <paramref name="array"/>. -or- <paramref name="length"/> is less than zero.
/// </exception>
[Pure]
public static int BinarySearch<T>(this ImmutableArray<T> array, int index, int length, T value)
{
return Array.BinarySearch<T>(array.array, index, length, value);
}
/// <summary>
/// Searches a range of elements in a one-dimensional sorted <see cref="ImmutableArray{T}"/> for
/// a value, using the specified <see cref="IComparer{T}"/> generic
/// interface.
/// </summary>
/// <typeparam name="T">The type of element stored in the array.</typeparam>
/// <param name="array">The sorted, one-dimensional array to search.</param>
/// <param name="index">The starting index of the range to search.</param>
/// <param name="length">The length of the range to search.</param>
/// <param name="value">The object to search for.</param>
/// <param name="comparer">
/// The <see cref="IComparer{T}"/> implementation to use when comparing
/// elements; or null to use the <see cref="IComparable{T}"/> implementation of each
/// element.
/// </param>
/// <returns>
/// The index of the specified <paramref name="value"/> in the specified <paramref name="array"/>, if <paramref name="value"/> is found.
/// If <paramref name="value"/> is not found and <paramref name="value"/> is less than one or more elements in <paramref name="array"/>,
/// a negative number which is the bitwise complement of the index of the first
/// element that is larger than <paramref name="value"/>. If <paramref name="value"/> is not found and <paramref name="value"/> is greater
/// than any of the elements in <paramref name="array"/>, a negative number which is the bitwise
/// complement of (the index of the last element plus 1).
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// <paramref name="comparer"/> is null, <paramref name="value"/> does not implement the <see cref="IComparable{T}"/> generic
/// interface, and the search encounters an element that does not implement the
/// <see cref="IComparable{T}"/> generic interface.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="index"/> and <paramref name="length"/> do not specify a valid range in <paramref name="array"/>.-or-<paramref name="comparer"/> is null,
/// and <paramref name="value"/> is of a type that is not compatible with the elements of <paramref name="array"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is less than the lower bound of <paramref name="array"/>. -or- <paramref name="length"/> is less than zero.
/// </exception>
[Pure]
public static int BinarySearch<T>(this ImmutableArray<T> array, int index, int length, T value, IComparer<T> comparer)
{
return Array.BinarySearch<T>(array.array, index, length, value, comparer);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct.
/// </summary>
/// <param name="items">The array from which to copy.</param>
internal static ImmutableArray<T> CreateDefensiveCopy<T>(T[] items)
{
Debug.Assert(items != null);
if (items.Length == 0)
{
return ImmutableArray<T>.Empty; // use just a shared empty array, allowing the input array to be potentially GC'd
}
// defensive copy
var tmp = new T[items.Length];
Array.Copy(items, 0, tmp, 0, items.Length);
return new ImmutableArray<T>(tmp);
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace UltimateFracturing
{
static public class Parameters
{
static public float EPSILONDISTANCEPLANE = 0.00001f;
static public float EPSILONDISTANCEVERTEX = 0.00001f;
static public float EPSILONCAPPRECISIONMIN = 0.0001f;
static public float EPSILONCROSSPRODUCT = 0.00001f;
static public float EPSILONINSIDETRIANGLE = 0.01f;
static public int VERTICESSPACESUBDIVISION = 10;
}
public class VertexData
{
public int nVertexHash;
public Vector3 v3Vertex;
public Vector3 v3Normal;
public Vector4 v4Tangent;
public Color32 color32;
public Vector2 v2Mapping1;
public Vector2 v2Mapping2;
public bool bHasNormal;
public bool bHasTangent;
public bool bHasColor32;
public bool bHasMapping1;
public bool bHasMapping2;
public VertexData(int nVertexHash)
{
this.nVertexHash = nVertexHash;
v3Vertex = Vector3.zero;
v3Normal = Vector3.zero;
v4Tangent = Vector4.zero;
color32.r = color32.g = color32.b = color32.a = 255;
v2Mapping1 = Vector2.zero;
v2Mapping2 = Vector2.zero;
bHasNormal = false;
bHasTangent = false;
bHasColor32 = false;
bHasMapping1 = false;
bHasMapping2 = false;
}
public VertexData(int nVertexHash, Vector3 v3Vertex, Vector3 v3Normal, Vector3 v4Tangent, Color32 color32, Vector2 v2Mapping1, Vector2 v2Mapping2, bool bHasNormal, bool bHasTangent, bool bHasColor32, bool bHasMapping1, bool bHasMapping2)
{
this.nVertexHash = nVertexHash;
this.v3Vertex = v3Vertex;
this.v3Normal = v3Normal;
this.v4Tangent = v4Tangent;
this.color32 = color32;
this.v2Mapping1 = v2Mapping1;
this.v2Mapping2 = v2Mapping2;
this.bHasNormal = bHasNormal;
this.bHasTangent = bHasTangent;
this.bHasColor32 = bHasColor32;
this.bHasMapping1 = bHasMapping1;
this.bHasMapping2 = bHasMapping2;
}
public VertexData Copy()
{
VertexData vdCopy = new VertexData(nVertexHash);
vdCopy.v3Vertex = v3Vertex;
vdCopy.v3Normal = v3Normal;
vdCopy.v4Tangent = v4Tangent;
vdCopy.color32 = color32;
vdCopy.v2Mapping1 = v2Mapping1;
vdCopy.v2Mapping2 = v2Mapping2;
vdCopy.bHasNormal = bHasNormal;
vdCopy.bHasTangent = bHasTangent;
vdCopy.bHasColor32 = bHasColor32;
vdCopy.bHasMapping1 = bHasMapping1;
vdCopy.bHasMapping2 = bHasMapping2;
return vdCopy;
}
public static VertexData Lerp(int nVertexHash, VertexData vd1, VertexData vd2, float fT)
{
VertexData vdResult = new VertexData(nVertexHash);
// We assume vd1 and vd2 come from the same mesh and have the same data
vdResult.bHasNormal = vd1.bHasNormal;
vdResult.bHasTangent = vd1.bHasTangent;
vdResult.bHasColor32 = vd1.bHasColor32;
vdResult.bHasMapping1 = vd1.bHasMapping1;
vdResult.bHasMapping2 = vd1.bHasMapping2;
// Interpolate values
Vector3 v3Tangent = Vector3.Lerp(vd1.v4Tangent, vd2.v4Tangent, fT);//.normalized;
vdResult.v3Vertex = Vector3.Lerp(vd1.v3Vertex, vd2.v3Vertex, fT);
if(vd1.bHasNormal) vdResult.v3Normal = Vector3.Lerp(vd1.v3Normal, vd2.v3Normal, fT);//.normalized;
if(vd1.bHasColor32) vdResult.color32 = Color32.Lerp(vd1.color32, vd2.color32, fT);
if(vd1.bHasMapping1) vdResult.v2Mapping1 = Vector2.Lerp(vd1.v2Mapping1, vd2.v2Mapping1, fT);
if(vd1.bHasMapping2) vdResult.v2Mapping2 = Vector2.Lerp(vd1.v2Mapping2, vd2.v2Mapping2, fT);
if(vd1.bHasTangent) vdResult.v4Tangent = new Vector4(v3Tangent.x, v3Tangent.y, v3Tangent.z, vd1.v4Tangent.w);
return vdResult;
}
public static bool ClipAgainstPlane(VertexData[] aVertexDataInput, int nIndexA, int nIndexB, Vector3 v3A, Vector3 v3B, Plane planeSplit, ref VertexData clippedVertexDataOut)
{
Vector3 vecAB = (v3B - v3A).normalized;
Ray rayAB = new Ray(v3A, vecAB);
float fRayCast;
if(planeSplit.Raycast(rayAB, out fRayCast) == false)
{
Debug.LogWarning("Raycast returned false");
clippedVertexDataOut = new VertexData(clippedVertexDataOut.nVertexHash);
return false;
};
float fT = fRayCast / (v3B - v3A).magnitude;
clippedVertexDataOut = VertexData.Lerp(clippedVertexDataOut.nVertexHash, aVertexDataInput[nIndexA], aVertexDataInput[nIndexB], fT);
return true;
}
public static VertexData[] BuildVertexDataArray(Mesh mesh, Matrix4x4 mtxLocalToWorld, bool bTransformVerticesToWorld)
{
VertexData[] resultArray = new VertexData[mesh.vertexCount];
Vector3[] av3Vertices = mesh.vertices;
Vector3[] av3Normals = mesh.normals;
Vector4[] av4Tangents = mesh.tangents;
Vector2[] av2Mapping1 = mesh.uv;
Vector2[] av2Mapping2 = mesh.uv2;
Color[] acolColors = mesh.colors;
Color32[] aColors32 = mesh.colors32;
for(int i = 0; i < mesh.vertexCount; i++)
{
resultArray[i] = new VertexData(-1);
if(bTransformVerticesToWorld)
{
resultArray[i].v3Vertex = mtxLocalToWorld.MultiplyPoint3x4(av3Vertices[i]);
if(av3Normals != null)
{
if(av3Normals.Length > i)
{
resultArray[i].v3Normal = mtxLocalToWorld.MultiplyVector(av3Normals[i]);
resultArray[i].bHasNormal = true;
}
}
else resultArray[i].bHasNormal = false;
if(av4Tangents != null)
{
if(av4Tangents.Length > i)
{
float w = av4Tangents[i].w;
resultArray[i].v4Tangent = mtxLocalToWorld.MultiplyVector(av4Tangents[i]);
resultArray[i].v4Tangent.w = w;
resultArray[i].bHasTangent = true;
}
}
else resultArray[i].bHasTangent = false;
}
else
{
resultArray[i].v3Vertex = av3Vertices[i];
if(av3Normals != null)
{
if(av3Normals.Length > i)
{
resultArray[i].v3Normal = av3Normals[i];
resultArray[i].bHasNormal = true;
}
}
else resultArray[i].bHasNormal = false;
if(av4Tangents != null)
{
if(av4Tangents.Length > i)
{
resultArray[i].v4Tangent = av4Tangents[i];
resultArray[i].bHasTangent = true;
}
}
else resultArray[i].bHasTangent = false;
}
if(aColors32 != null)
{
if(aColors32.Length > i)
{
resultArray[i].color32 = aColors32[i];
resultArray[i].bHasColor32 = true;
}
}
else if(acolColors != null)
{
if(acolColors.Length > i)
{
resultArray[i].color32 = acolColors[i];
resultArray[i].bHasColor32 = true;
}
}
resultArray[i].bHasColor32 = false;
if(av2Mapping1 != null)
{
if(av2Mapping1.Length > i)
{
resultArray[i].v2Mapping1 = av2Mapping1[i];
resultArray[i].bHasMapping1 = true;
}
}
else resultArray[i].bHasMapping1 = false;
if(av2Mapping2 != null)
{
if(av2Mapping2.Length > i)
{
resultArray[i].v2Mapping2 = av2Mapping2[i];
resultArray[i].bHasMapping2 = true;
}
}
else resultArray[i].bHasMapping2 = false;
}
return resultArray;
}
public static void SetMeshDataFromVertexDataArray(MeshFilter meshFilter, MeshData meshData, bool bTransformVertexToLocal)
{
VertexData[] aVertexData = meshData.aVertexData;
Vector3[] aVertices = new Vector3[aVertexData.Length];
Vector3[] aNormals = aVertexData[0].bHasNormal ? new Vector3[aVertexData.Length] : null;
Vector4[] aTangents = aVertexData[0].bHasTangent ? new Vector4[aVertexData.Length] : null;
Color32[] aColors32 = aVertexData[0].bHasColor32 ? new Color32[aVertexData.Length] : null;
Vector2[] aMapping1 = aVertexData[0].bHasMapping1 ? new Vector2[aVertexData.Length] : null;
Vector2[] aMapping2 = aVertexData[0].bHasMapping2 ? new Vector2[aVertexData.Length] : null;
Matrix4x4 mtxWorldToLocal = meshFilter.transform.worldToLocalMatrix;
for(int i = 0; i < aVertexData.Length; i++)
{
if(bTransformVertexToLocal)
{
aVertices[i] = mtxWorldToLocal.MultiplyPoint(aVertexData[i].v3Vertex);
if(aNormals != null) aNormals[i] = mtxWorldToLocal.MultiplyVector(aVertexData[i].v3Normal);
if(aTangents != null)
{
float w = aVertexData[i].v4Tangent.w;
aTangents[i] = mtxWorldToLocal.MultiplyVector(aVertexData[i].v4Tangent);
aTangents[i].w = w;
}
}
else
{
aVertices[i] = aVertexData[i].v3Vertex;
if(aNormals != null) aNormals[i] = aVertexData[i].v3Normal;
if(aTangents != null) aTangents[i] = aVertexData[i].v4Tangent;
}
if(aColors32 != null) aColors32[i] = aVertexData[i].color32;
if(aMapping1 != null) aMapping1[i] = aVertexData[i].v2Mapping1;
if(aMapping2 != null) aMapping2[i] = aVertexData[i].v2Mapping2;
}
meshFilter.sharedMesh.vertices = aVertices;
meshFilter.sharedMesh.normals = aNormals;
meshFilter.sharedMesh.tangents = aTangents;
meshFilter.sharedMesh.colors32 = aColors32;
meshFilter.sharedMesh.uv = aMapping1;
meshFilter.sharedMesh.uv2 = aMapping2;
}
}
public struct EdgeKeyByIndex
{
public int nIndexA;
public int nIndexB;
public EdgeKeyByIndex(int nIndexA, int nIndexB)
{
this.nIndexA = nIndexA;
this.nIndexB = nIndexB;
}
public void Set(int nIndexA, int nIndexB)
{
this.nIndexA = nIndexA;
this.nIndexB = nIndexB;
}
public class EqualityComparer : IEqualityComparer<EdgeKeyByIndex>
{
public bool Equals(EdgeKeyByIndex x, EdgeKeyByIndex y)
{
return x.CompareTo(y.nIndexA, y.nIndexB);
}
public int GetHashCode(EdgeKeyByIndex x)
{
return x.nIndexA.GetHashCode() + x.nIndexB.GetHashCode();
}
}
public bool CompareTo(int nIndexA, int nIndexB)
{
if(this.nIndexA == nIndexA && this.nIndexB == nIndexB) return true;
if(this.nIndexA == nIndexB && this.nIndexB == nIndexA) return true;
return false;
}
}
public struct EdgeKeyByHash
{
public int nHashA;
public int nHashB;
public EdgeKeyByHash(int nHashA, int nHashB)
{
this.nHashA = nHashA;
this.nHashB = nHashB;
}
public void Set(int nHashA, int nHashB)
{
this.nHashA = nHashA;
this.nHashB = nHashB;
}
public class EqualityComparer : IEqualityComparer<EdgeKeyByHash>
{
public bool Equals(EdgeKeyByHash x, EdgeKeyByHash y)
{
return x.CompareTo(y.nHashA, y.nHashB);
}
public int GetHashCode(EdgeKeyByHash x)
{
return x.nHashA.GetHashCode() + x.nHashB.GetHashCode();
}
}
public bool CompareTo(int nHashA, int nHashB)
{
if(this.nHashA == nHashA && this.nHashB == nHashB) return true;
if(this.nHashA == nHashB && this.nHashB == nHashA) return true;
return false;
}
}
public struct ClippedEdge
{
public int nOldIndexA;
public int nOldIndexB;
public int nNewIndexA;
public int nNewIndexB;
public int nClippedIndex;
public ClippedEdge(int nOldIndexA, int nOldIndexB, int nNewIndexA, int nNewIndexB, int nClippedIndex)
{
this.nOldIndexA = nOldIndexA;
this.nOldIndexB = nOldIndexB;
this.nNewIndexA = nNewIndexA;
this.nNewIndexB = nNewIndexB;
this.nClippedIndex = nClippedIndex;
}
public int GetFirstIndex(int nOldIndexA)
{
if(this.nOldIndexA == nOldIndexA) return nNewIndexA;
return nNewIndexB;
}
public int GetSecondIndex(int nOldIndexB)
{
if(this.nOldIndexB == nOldIndexB) return nNewIndexB;
return nNewIndexA;
}
}
public struct CapEdge
{
public Vector3 v1, v2;
public int nHash1, nHash2;
public float fLength;
public CapEdge(int nHash1, int nHash2, Vector3 v1, Vector3 v2, float fLength)
{
this.nHash1 = nHash1;
this.nHash2 = nHash2;
this.v1 = v1;
this.v2 = v2;
this.fLength = fLength;
}
public int SharesVertex1Of(CapEdge edge)
{
if(nHash1 == edge.nHash1) return 1;
if(nHash2 == edge.nHash1) return 2;
return 0;
}
public int SharesVertex2Of(CapEdge edge)
{
if(nHash1 == edge.nHash2) return 1;
if(nHash2 == edge.nHash2) return 2;
return 0;
}
}
// Face connectivity through shared edges
public class MeshFaceConnectivity
{
public struct EdgeData
{
public struct SideData
{
public SideData(int nFace, int nSubMesh, int nSubMeshFace, int nEdgePos, int nVertexDataV1, int nVertexDataV2)
{
this.nFace = nFace; // Global face index
this.nSubMesh = nSubMesh; // Submesh index
this.nSubMeshFace = nSubMeshFace; // Face index (inside submesh)
this.nEdgePos = nEdgePos; // Edge position (0, 1 or 2)
this.nVertexDataV1 = nVertexDataV1; // Index in vertex data array for vertex 1
this.nVertexDataV2 = nVertexDataV2; // Index in vertex data array for vertex 2
}
public int nFace;
public int nSubMesh;
public int nSubMeshFace;
public int nEdgePos;
public int nVertexDataV1;
public int nVertexDataV2;
}
public EdgeData(int nEdgeIndex, int nFace, int nSubMesh, int nSubMeshFace, int nEdgePos, Vector3 v1, Vector3 v2, int nVertex1Hash, int nVertex2Hash, int nVertexDataV1, int nVertexDataV2)
{
this.nEdgeIndex = nEdgeIndex;
this.v1 = v1;
this.v2 = v2;
this.nVertex1Hash = nVertex1Hash;
this.nVertex2Hash = nVertex2Hash;
listSides = new List<SideData>();
listSides.Add(new SideData(nFace, nSubMesh, nSubMeshFace, nEdgePos, nVertexDataV1, nVertexDataV2));
}
public int nEdgeIndex; // Edge index for the edge list
int nVertex1Hash; // Vertex 1 hash (unique ID for vertices with same vertex coordinates)
int nVertex2Hash; // Vertex 2 hash (unique ID for vertices with same vertex coordinates)
public Vector3 v1; // Vertex 1
public Vector3 v2; // Vertex 2
public List<SideData> listSides; // Adjacent sides (more than 2 can be due to degenerate faces, just in case)
public bool Compare(int nVertex1Hash, int nVertex2Hash)
{
if(this.nVertex1Hash == nVertex1Hash && this.nVertex2Hash == nVertex2Hash) return true;
if(this.nVertex1Hash == nVertex2Hash && this.nVertex2Hash == nVertex1Hash) return true;
return false;
}
public void AddSideData(int nFace, int nSubMesh, int nSubMeshFace, int nEdgePos, int nVertexDataV1, int nVertexDataV2)
{
if(listSides == null)
{
listSides = new List<SideData>();
}
listSides.Add(new SideData(nFace, nSubMesh, nSubMeshFace, nEdgePos, nVertexDataV1, nVertexDataV2));
}
public bool HasMoreThanOneSide()
{
if(listSides == null)
{
return false;
}
return listSides.Count > 1;
}
}
public class TriangleData
{
public TriangleData(int nSubMesh, int nTriangle)
{
this.nSubMesh = nSubMesh;
this.nTriangle = nTriangle;
anEdges = new int[3];
alistNeighborSubMeshes = new List<int>[3];
alistNeighborTriangles = new List<int>[3];
for(int i = 0; i < 3; i++)
{
anEdges[i] = -1;
alistNeighborSubMeshes[i] = new List<int>();
alistNeighborTriangles[i] = new List<int>();
}
bVisited = false;
}
public int nSubMesh; // Submesh this triangle belongs to
public int nTriangle; // Triangle index (relative to submesh)
public int[] anEdges; // The 3 edges that conform this triangle
public List<int>[] alistNeighborSubMeshes; // For each 3 edges, the list of adjacent submeshes
public List<int>[] alistNeighborTriangles; // For each 3 edges, the list adjacent triangles (indices relative to submesh triangles
public bool bVisited; // Has this triangle been visited when traversing?
}
public List<TriangleData> listTriangles; // The triangles
private List<EdgeData> listEdges; // Edges for linear traversal
private List<int> listEdgeIndices; // Indices into the edge list
private Dictionary<EdgeKeyByHash, EdgeData> dicEdges; // Edge dictionary (key -> data)
private int nEdgeCount; // Internal edge counter
private Dictionary<int, int> dicSubMeshTriangleCount; // For each submesh, the internal triangle counter
public MeshFaceConnectivity()
{
listTriangles = new List<TriangleData>();
listEdges = new List<EdgeData>();
listEdgeIndices = new List<int>();
dicEdges = new Dictionary<EdgeKeyByHash, EdgeData>(new EdgeKeyByHash.EqualityComparer());
dicSubMeshTriangleCount = new Dictionary<int, int>();
nEdgeCount = 0;
}
public void Clear()
{
listTriangles.Clear();
listEdges.Clear();
listEdgeIndices.Clear();
dicEdges.Clear();
dicSubMeshTriangleCount.Clear();
nEdgeCount = 0;
}
public void ResetVisited()
{
for(int i = 0; i < listTriangles.Count; i++)
{
listTriangles[i].bVisited = false;
}
}
public void AddEdge(int nSubMesh, Vector3 v1, Vector3 v2, int nVertex1Hash, int nVertex2Hash, int nVertexDataIndex1, int nVertexDataIndex2)
{
int nEdgePos = nEdgeCount % 3;
int nFace = nEdgeCount / 3;
if(dicSubMeshTriangleCount.ContainsKey(nSubMesh) == false)
{
dicSubMeshTriangleCount.Add(nSubMesh, 0);
}
int nSubMeshFace = dicSubMeshTriangleCount[nSubMesh];
// Look for edge
int nEdgeIndex = -1;
EdgeKeyByHash edgeKey = new EdgeKeyByHash(nVertex1Hash, nVertex2Hash);
// Try to find in dictionary, otherwise create new entry
if(dicEdges.ContainsKey(edgeKey))
{
EdgeData edge = dicEdges[edgeKey];
edge.AddSideData(nFace, nSubMesh, nSubMeshFace, nEdgePos, nVertexDataIndex1, nVertexDataIndex2);
nEdgeIndex = edge.nEdgeIndex;
}
else
{
nEdgeIndex = listEdges.Count;
EdgeData newEdge = new EdgeData(nEdgeIndex, nFace, nSubMesh, nSubMeshFace, nEdgePos, v1, v2, nVertex1Hash, nVertex2Hash, nVertexDataIndex1, nVertexDataIndex2);
listEdges.Add(newEdge);
dicEdges.Add(edgeKey, newEdge);
}
listEdgeIndices.Add(nEdgeIndex);
// Closed triangle? create new triangle entry
nEdgeCount++;
if(nEdgeCount % 3 == 0)
{
TriangleData newTriangle = new TriangleData(nSubMesh, nSubMeshFace);
EdgeData edge1 = listEdges[listEdgeIndices[listEdgeIndices.Count - 3]];
EdgeData edge2 = listEdges[listEdgeIndices[listEdgeIndices.Count - 2]];
EdgeData edge3 = listEdges[listEdgeIndices[listEdgeIndices.Count - 1]];
newTriangle.anEdges[0] = edge1.nEdgeIndex;
newTriangle.anEdges[1] = edge2.nEdgeIndex;
newTriangle.anEdges[2] = edge3.nEdgeIndex;
// Set connectivity data
foreach(EdgeData.SideData sideData in edge1.listSides)
{
if(sideData.nFace != nFace)
{
listTriangles[sideData.nFace].alistNeighborSubMeshes[sideData.nEdgePos].Add(nSubMesh);
listTriangles[sideData.nFace].alistNeighborTriangles[sideData.nEdgePos].Add(nSubMeshFace);
newTriangle.alistNeighborSubMeshes[0].Add(sideData.nSubMesh);
newTriangle.alistNeighborTriangles[0].Add(sideData.nSubMeshFace);
}
}
foreach(EdgeData.SideData sideData in edge2.listSides)
{
if(sideData.nFace != nFace)
{
listTriangles[sideData.nFace].alistNeighborSubMeshes[sideData.nEdgePos].Add(nSubMesh);
listTriangles[sideData.nFace].alistNeighborTriangles[sideData.nEdgePos].Add(nSubMeshFace);
newTriangle.alistNeighborSubMeshes[1].Add(sideData.nSubMesh);
newTriangle.alistNeighborTriangles[1].Add(sideData.nSubMeshFace);
}
}
foreach(EdgeData.SideData sideData in edge3.listSides)
{
if(sideData.nFace != nFace)
{
listTriangles[sideData.nFace].alistNeighborSubMeshes[sideData.nEdgePos].Add(nSubMesh);
listTriangles[sideData.nFace].alistNeighborTriangles[sideData.nEdgePos].Add(nSubMeshFace);
newTriangle.alistNeighborSubMeshes[2].Add(sideData.nSubMesh);
newTriangle.alistNeighborTriangles[2].Add(sideData.nSubMeshFace);
}
}
listTriangles.Add(newTriangle);
dicSubMeshTriangleCount[nSubMesh]++;
}
}
}
// MeshData->MeshData connectivity through shared faces
public class MeshDataConnectivity
{
public static int s_CurrentSharedFaceHash = 0;
public struct Face
{
public Face(int nSubMesh, int nFaceIndex)
{
this.nSubMesh = nSubMesh;
this.nFaceIndex = nFaceIndex;
}
public class EqualityComparer : IEqualityComparer<Face>
{
public bool Equals(Face x, Face y)
{
return (x.nSubMesh == y.nSubMesh && x.nFaceIndex == y.nFaceIndex);
}
public int GetHashCode(Face x)
{
return x.nSubMesh.GetHashCode() + x.nFaceIndex.GetHashCode();
}
}
public int nSubMesh;
public int nFaceIndex;
}
public Dictionary<int, List<Face>> dicHash2FaceList;
public Dictionary<Face, List<int>> dicFace2HashList;
public Dictionary<Face, bool> dicFace2IsClipped;
public MeshDataConnectivity()
{
dicHash2FaceList = new Dictionary<int, List<Face>>();
dicFace2HashList = new Dictionary<Face, List<int>> (new Face.EqualityComparer());
dicFace2IsClipped = new Dictionary<Face, bool>(new Face.EqualityComparer());
}
public MeshDataConnectivity GetDeepCopy()
{
MeshDataConnectivity meshDataCopy = new MeshDataConnectivity();
foreach(KeyValuePair<int, List<Face>> hash2FaceList in dicHash2FaceList)
{
meshDataCopy.dicHash2FaceList.Add(hash2FaceList.Key, new List<Face>());
foreach(Face face in hash2FaceList.Value)
{
meshDataCopy.dicHash2FaceList[hash2FaceList.Key].Add(face);
}
}
foreach(KeyValuePair<Face, List<int>> face2HashList in dicFace2HashList)
{
meshDataCopy.dicFace2HashList.Add(face2HashList.Key, new List<int>());
foreach(int nHash in face2HashList.Value)
{
meshDataCopy.dicFace2HashList[face2HashList.Key].Add(nHash);
}
}
foreach(KeyValuePair<Face, bool> face2IsClipped in dicFace2IsClipped)
{
meshDataCopy.dicFace2IsClipped.Add(face2IsClipped.Key, face2IsClipped.Value);
}
return meshDataCopy;
}
public void NotifyNewClippedFace(MeshData meshDataSource, int nSourceSubMesh, int nSourceFaceIndex, int nDestSubMesh, int nDestFaceIndex)
{
Face faceSrc = new Face(nSourceSubMesh, nSourceFaceIndex);
Face faceDst = new Face(nDestSubMesh, nDestFaceIndex);
if(meshDataSource.meshDataConnectivity.dicFace2HashList.ContainsKey(faceSrc))
{
// The source face is a shared face, we must register this information
foreach(int nHash in meshDataSource.meshDataConnectivity.dicFace2HashList[faceSrc])
{
if(dicHash2FaceList.ContainsKey(nHash) == false)
{
dicHash2FaceList.Add(nHash, new List<Face>());
}
if(dicFace2HashList.ContainsKey(faceDst) == false)
{
dicFace2HashList.Add(faceDst, new List<int>());
}
dicHash2FaceList[nHash].Add(faceDst);
dicFace2HashList[faceDst].Add(nHash);
if(dicFace2IsClipped.ContainsKey(faceDst) == false)
{
dicFace2IsClipped.Add(faceDst, true);
}
else
{
dicFace2IsClipped[faceDst] = true;
}
}
}
}
public static int GetNewHash()
{
int nNewHash = 0;
lock(typeof(MeshDataConnectivity))
{
nNewHash = s_CurrentSharedFaceHash;
s_CurrentSharedFaceHash++;
}
return nNewHash;
}
public void NotifyNewCapFace(int nHash, int nSubMesh, int nFaceIndex)
{
Face face = new Face(nSubMesh, nFaceIndex);
if(dicHash2FaceList.ContainsKey(nHash) == false)
{
dicHash2FaceList.Add(nHash, new List<Face>());
}
dicHash2FaceList[nHash].Add(face);
if(dicFace2HashList.ContainsKey(face) == false)
{
dicFace2HashList.Add(face, new List<int>());
}
dicFace2HashList[face].Add(nHash);
}
public void NotifyRemappedFace(MeshDataConnectivity source, int nSourceSubMesh, int nSourceFaceIndex, int nDestSubMesh, int nDestFaceIndex)
{
Face faceSrc = new Face(nSourceSubMesh, nSourceFaceIndex);
Face faceDst = new Face(nDestSubMesh, nDestFaceIndex);
if(source.dicFace2HashList.ContainsKey(faceSrc))
{
// The source face is a shared face, we must register this information
foreach(int nHash in source.dicFace2HashList[faceSrc])
{
if(dicHash2FaceList.ContainsKey(nHash) == false)
{
dicHash2FaceList.Add(nHash, new List<Face>());
}
if(dicFace2HashList.ContainsKey(faceDst) == false)
{
dicFace2HashList.Add(faceDst, new List<int>());
}
dicHash2FaceList[nHash].Add(faceDst);
dicFace2HashList[faceDst].Add(nHash);
if(source.dicFace2IsClipped.ContainsKey(faceSrc))
{
if(dicFace2IsClipped.ContainsKey(faceDst) == false)
{
dicFace2IsClipped.Add(faceDst, true);
}
else
{
dicFace2IsClipped[faceDst] = true;
}
}
}
}
}
}
public class MeshData
{
public int nSubMeshCount; // The number of submeshes present
public int[][] aaIndices; // For each submesh, an array of indices
public int nSplitCloseSubMesh; // Index of the submesh that has the split faces
public VertexData[] aVertexData; // Vertex data
public Vector3 v3Position; // Transform's position
public Quaternion qRotation; // Transform's rotation
public Vector3 v3Scale; // Transform's scale
public Vector3 v3Min; // BBox min
public Vector3 v3Max; // BBox max
public int nCurrentVertexHash; // The last vertex hash value used. New values should be incremental values.
public Material[] aMaterials; // The array of materials
public MeshDataConnectivity meshDataConnectivity;
public class IncreasingSizeComparer : IComparer<MeshData>
{
private int nSplitAxis;
public IncreasingSizeComparer(int nSplitAxis)
{
this.nSplitAxis = nSplitAxis;
}
public int Compare(MeshData a, MeshData b)
{
Vector3 v3MinA = a.v3Min;
Vector3 v3MaxA = a.v3Max;
Vector3 v3MinB = b.v3Min;
Vector3 v3MaxB = b.v3Max;
if(nSplitAxis == 0)
{
return ((v3MaxA.x - v3MinA.x) - (v3MaxB.x - v3MinB.x)) < 0.0f ? -1 : 1;
}
else if(nSplitAxis == 1)
{
return ((v3MaxA.y - v3MinA.y) - (v3MaxB.y - v3MinB.y)) < 0.0f ? -1 : 1;
}
else if(nSplitAxis == 2)
{
return ((v3MaxA.z - v3MinA.z) - (v3MaxB.z - v3MinB.z)) < 0.0f ? -1 : 1;
}
return Mathf.Max(v3MaxA.x - v3MinA.x, v3MaxA.y - v3MinA.y, v3MaxA.z - v3MinA.z) -
Mathf.Max(v3MaxB.x - v3MinB.x, v3MaxB.y - v3MinB.y, v3MaxB.z - v3MinB.z) < 0.0f ? -1 : 1;
//return ((v3MaxA - v3MinA).sqrMagnitude - (v3MaxB - v3MinB).sqrMagnitude) < 0.0f ? -1 : 1;
}
}
public class DecreasingSizeComparer : IComparer<MeshData>
{
private int nSplitAxis;
public DecreasingSizeComparer(int nSplitAxis)
{
this.nSplitAxis = nSplitAxis;
}
public int Compare(MeshData a, MeshData b)
{
Vector3 v3MinA = a.v3Min;
Vector3 v3MaxA = a.v3Max;
Vector3 v3MinB = b.v3Min;
Vector3 v3MaxB = b.v3Max;
if(nSplitAxis == 0)
{
return ((v3MaxA.x - v3MinA.x) - (v3MaxB.x - v3MinB.x)) < 0.0f ? 1 : -1;
}
else if(nSplitAxis == 1)
{
return ((v3MaxA.y - v3MinA.y) - (v3MaxB.y - v3MinB.y)) < 0.0f ? 1 : -1;
}
else if(nSplitAxis == 2)
{
return ((v3MaxA.z - v3MinA.z) - (v3MaxB.z - v3MinB.z)) < 0.0f ? 1 : -1;
}
return Mathf.Max(v3MaxA.x - v3MinA.x, v3MaxA.y - v3MinA.y, v3MaxA.z - v3MinA.z) -
Mathf.Max(v3MaxB.x - v3MinB.x, v3MaxB.y - v3MinB.y, v3MaxB.z - v3MinB.z) < 0.0f ? 1 : -1;
//return ((v3MaxA - v3MinA).sqrMagnitude - (v3MaxB - v3MinB).sqrMagnitude) < 0.0f ? 1 : -1;
}
}
private MeshData()
{
meshDataConnectivity = new MeshDataConnectivity();
aMaterials = new Material[1];
aMaterials[0] = null;
}
public MeshData(Material[] aMaterials, List<int>[] alistIndices, List<VertexData> listVertexData, int nSplitCloseSubMesh, Vector3 v3Position, Quaternion qRotation, Vector3 v3Scale, Matrix4x4 mtxTransformVertices, bool bUseTransform, bool bBuildVertexHashData)
{
nSubMeshCount = alistIndices.Length;
aaIndices = new int[nSubMeshCount][];
for(int nSubMesh = 0; nSubMesh < nSubMeshCount; nSubMesh++)
{
aaIndices[nSubMesh] = alistIndices[nSubMesh].ToArray();
}
this.nSplitCloseSubMesh = nSplitCloseSubMesh;
aVertexData = listVertexData.ToArray();
if(bUseTransform)
{
for(int i = 0; i < aVertexData.Length; i++)
{
aVertexData[i].v3Vertex = mtxTransformVertices.MultiplyPoint3x4(aVertexData[i].v3Vertex);
}
}
ComputeMinMax(aVertexData, ref v3Min, ref v3Max);
this.v3Position = v3Position;
this.qRotation = qRotation;
this.v3Scale = v3Scale;
meshDataConnectivity = new MeshDataConnectivity();
if(bBuildVertexHashData)
{
BuildVertexHashData();
}
if(aMaterials != null)
{
this.aMaterials = new Material[aMaterials.Length];
aMaterials.CopyTo(this.aMaterials, 0);
}
else
{
this.aMaterials = new Material[1];
this.aMaterials[0] = null;
}
}
public MeshData(Transform transform, Mesh mesh, Material[] aMaterials, Matrix4x4 mtxLocalToWorld, bool bTransformVerticesToWorld, int nSplitCloseSubMesh, bool bBuildVertexHashData)
: this(transform.position, transform.rotation, transform.localScale, mesh, aMaterials, mtxLocalToWorld, bTransformVerticesToWorld, nSplitCloseSubMesh, bBuildVertexHashData)
{
}
public MeshData(Vector3 v3Position, Quaternion qRotation, Vector3 v3Scale, Mesh mesh, Material[] aMaterials, Matrix4x4 mtxLocalToWorld, bool bTransformVerticesToWorld, int nSplitCloseSubMesh, bool bBuildVertexHashData)
{
nSubMeshCount = mesh.subMeshCount;
aaIndices = new int[nSubMeshCount][];
for(int nSubMesh = 0; nSubMesh < nSubMeshCount; nSubMesh++)
{
aaIndices[nSubMesh] = mesh.GetTriangles(nSubMesh);
}
this.nSplitCloseSubMesh = nSplitCloseSubMesh;
aVertexData = VertexData.BuildVertexDataArray(mesh, mtxLocalToWorld, bTransformVerticesToWorld);
ComputeMinMax(aVertexData, ref v3Min, ref v3Max);
this.v3Position = v3Position;
this.qRotation = qRotation;
this.v3Scale = v3Scale;
if(bTransformVerticesToWorld)
{
v3Scale = Vector3.one;
}
meshDataConnectivity = new MeshDataConnectivity();
if(bBuildVertexHashData)
{
BuildVertexHashData();
}
if(aMaterials != null)
{
this.aMaterials = new Material[aMaterials.Length];
aMaterials.CopyTo(this.aMaterials, 0);
}
else
{
this.aMaterials = new Material[1];
this.aMaterials[0] = null;
}
}
static public MeshData CreateBoxMeshData(Vector3 v3Pos, Quaternion qRot, Vector3 v3Scale, Vector3 v3Min, Vector3 v3Max)
{
MeshData box = new MeshData();
box.nSubMeshCount = 1;
box.aaIndices = new int[1][];
box.aaIndices[0] = new int[36] { 1, 0, 3, 1, 3, 2, 4, 5, 7, 5, 6, 7, 0, 4, 3, 4, 7, 3, 7, 2, 3, 7, 6, 2, 5, 0, 1, 5, 4, 0, 6, 1, 2, 6, 5, 1 };
box.nSplitCloseSubMesh = 0;
Vector3[] aVertices = new Vector3[8] { new Vector3(v3Min.x, v3Min.y, v3Min.z), new Vector3(v3Min.x, v3Min.y, v3Max.z), new Vector3(v3Max.x, v3Min.y, v3Max.z), new Vector3(v3Max.x, v3Min.y, v3Min.z),
new Vector3(v3Min.x, v3Max.y, v3Min.z), new Vector3(v3Min.x, v3Max.y, v3Max.z), new Vector3(v3Max.x, v3Max.y, v3Max.z), new Vector3(v3Max.x, v3Max.y, v3Min.z) };
box.aVertexData = new VertexData[aVertices.Length];
for(int v = 0; v < aVertices.Length; v++)
{
box.aVertexData[v] = new VertexData(v);
box.aVertexData[v].v3Vertex = aVertices[v];
}
box.v3Position = v3Pos;
box.qRotation = qRot;
box.v3Scale = v3Scale;
box.v3Min = v3Min;
box.v3Max = v3Max;
box.nCurrentVertexHash = 8;
return box;
}
public MeshData GetDeepCopy()
{
MeshData meshDataCopy = new MeshData();
meshDataCopy.nSubMeshCount = nSubMeshCount;
meshDataCopy.aaIndices = new int[nSubMeshCount][];
for(int nSubMesh = 0; nSubMesh < nSubMeshCount; nSubMesh++)
{
meshDataCopy.aaIndices[nSubMesh] = new int[aaIndices[nSubMesh].Length];
aaIndices[nSubMesh].CopyTo(meshDataCopy.aaIndices[nSubMesh], 0);
}
meshDataCopy.nSplitCloseSubMesh = nSplitCloseSubMesh;
meshDataCopy.aVertexData = new VertexData[aVertexData.Length];
aVertexData.CopyTo(meshDataCopy.aVertexData, 0);
meshDataCopy.v3Position = v3Position;
meshDataCopy.qRotation = qRotation;
meshDataCopy.v3Scale = v3Scale;
meshDataCopy.v3Min = v3Min;
meshDataCopy.v3Max = v3Max;
meshDataCopy.nCurrentVertexHash = nCurrentVertexHash;
meshDataCopy.meshDataConnectivity = meshDataConnectivity.GetDeepCopy();
meshDataCopy.aMaterials = new Material[aMaterials.Length];
aMaterials.CopyTo(meshDataCopy.aMaterials, 0);
return meshDataCopy;
}
public bool FillMeshFilter(MeshFilter meshFilter, bool bTransformVerticesToLocal)
{
meshFilter.transform.position = v3Position;
meshFilter.transform.rotation = qRotation;
meshFilter.transform.localScale = v3Scale;
meshFilter.sharedMesh = new Mesh();
Mesh mesh = meshFilter.sharedMesh;
VertexData.SetMeshDataFromVertexDataArray(meshFilter, this, bTransformVerticesToLocal);
mesh.subMeshCount = nSubMeshCount;
for(int nSubMesh = 0; nSubMesh < nSubMeshCount; nSubMesh++)
{
mesh.SetTriangles(aaIndices[nSubMesh], nSubMesh);
}
mesh.RecalculateBounds();
mesh.Optimize();
return true;
}
public static void ComputeMinMax(IEnumerable<VertexData> VertexData, ref Vector3 v3Min, ref Vector3 v3Max)
{
v3Min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
v3Max = new Vector3(float.MinValue, float.MinValue, float.MinValue);
foreach(VertexData vdata in VertexData)
{
if(vdata.v3Vertex.x < v3Min.x) v3Min.x = vdata.v3Vertex.x;
if(vdata.v3Vertex.y < v3Min.y) v3Min.y = vdata.v3Vertex.y;
if(vdata.v3Vertex.z < v3Min.z) v3Min.z = vdata.v3Vertex.z;
if(vdata.v3Vertex.x > v3Max.x) v3Max.x = vdata.v3Vertex.x;
if(vdata.v3Vertex.y > v3Max.y) v3Max.y = vdata.v3Vertex.y;
if(vdata.v3Vertex.z > v3Max.z) v3Max.z = vdata.v3Vertex.z;
}
}
private void BuildVertexHashData()
{
// We are going to build the vertex hash data. This will allow us to know which vertices actually share the same coordinates, but have different vertex data.
List<Dictionary<int, Vector3>> listdicVertexHash2Vertex; // For each spacial subdivision, a dictionary from hash->vertex
List<float> listYTops; // This will contain entries where the different space subdivisions (Y level) are made.
listdicVertexHash2Vertex = new List<Dictionary<int, Vector3>>();
listYTops = new List<float>();
// Subdivide space
int nSubdivisions = (aVertexData.Length / Parameters.VERTICESSPACESUBDIVISION) + 1;
for(int nSubDiv = 0; nSubDiv < nSubdivisions; nSubDiv++)
{
float fTop = v3Min.y + (((float)(nSubDiv + 1) / (float)nSubdivisions) * (v3Max.y - v3Min.y));
listdicVertexHash2Vertex.Add(new Dictionary<int, Vector3>());
listYTops.Add(fTop);
}
// Look for replicated vertices
int[] aSpacesToLookIn = new int[3];
nCurrentVertexHash = 0;
int nUniqueVertices = 0;
for(int nVertexIndex = 0; nVertexIndex < aVertexData.Length; nVertexIndex++)
{
Vector3 v3Vertex = aVertexData[nVertexIndex].v3Vertex;
int nSpaceYIndex = Mathf.FloorToInt(((v3Vertex.y - v3Min.y) / (v3Max.y - v3Min.y)) * listYTops.Count);
if(nSpaceYIndex < 0) nSpaceYIndex = 0;
if(nSpaceYIndex >= listYTops.Count) nSpaceYIndex = listYTops.Count - 1;
aSpacesToLookIn[0] = nSpaceYIndex;
aSpacesToLookIn[1] = -1;
aSpacesToLookIn[2] = -1;
int nSpacesToLookIn = 1;
// We'll test the nearest one as well in case it's very close to the border and we may have floating point errors
if(Mathf.Abs(listYTops[nSpaceYIndex] - v3Vertex.y) < Parameters.EPSILONDISTANCEPLANE)
{
// Almost at the top?
if(nSpaceYIndex < listYTops.Count - 1)
{
aSpacesToLookIn[nSpacesToLookIn++] = nSpaceYIndex + 1;
}
}
if(nSpaceYIndex > 0)
{
if(Mathf.Abs(listYTops[nSpaceYIndex - 1] - v3Vertex.y) < Parameters.EPSILONDISTANCEPLANE)
{
// Almost at the bottom?
aSpacesToLookIn[nSpacesToLookIn++] = nSpaceYIndex - 1;
}
}
int nVertexHash = -1;
for(int nSpace = 0; nSpace < aSpacesToLookIn.Length; nSpace++)
{
int nSpaceY = aSpacesToLookIn[nSpace];
if(nSpaceY == -1) continue;
foreach(KeyValuePair<int, Vector3> hash2VertexPair in listdicVertexHash2Vertex[nSpaceY])
{
if(Vector3.Distance(hash2VertexPair.Value, v3Vertex) < Parameters.EPSILONDISTANCEVERTEX)
{
nVertexHash = hash2VertexPair.Key;
break;
}
}
}
if(nVertexHash == -1)
{
int nNewHash = nCurrentVertexHash++;
listdicVertexHash2Vertex[nSpaceYIndex].Add(nNewHash, v3Vertex);
aVertexData[nVertexIndex].nVertexHash = nNewHash;
nUniqueVertices++;
}
else
{
aVertexData[nVertexIndex].nVertexHash = nVertexHash;
}
}
}
public bool GetSharedFacesArea(FracturedObject fracturedComponent, MeshData meshData2, out float fSharedArea)
{
fSharedArea = 0.0f;
bool bHasSharedFaces = false;
foreach(int nHash in meshDataConnectivity.dicHash2FaceList.Keys)
{
if(meshData2.meshDataConnectivity.dicHash2FaceList.ContainsKey(nHash))
{
// Both faces come from the same split, but the area may be different (due to clipping)
foreach(MeshDataConnectivity.Face face1 in meshDataConnectivity.dicHash2FaceList[nHash])
{
Vector3 v1 = aVertexData[aaIndices[face1.nSubMesh][face1.nFaceIndex * 3 + 0]].v3Vertex;
Vector3 v2 = aVertexData[aaIndices[face1.nSubMesh][face1.nFaceIndex * 3 + 1]].v3Vertex;
Vector3 v3 = aVertexData[aaIndices[face1.nSubMesh][face1.nFaceIndex * 3 + 2]].v3Vertex;
float fArea1 = Vector3.Cross(v3 - v1, v2 - v1).magnitude;
foreach(MeshDataConnectivity.Face face2 in meshData2.meshDataConnectivity.dicHash2FaceList[nHash])
{
Vector3 v3Other1 = meshData2.aVertexData[meshData2.aaIndices[face2.nSubMesh][face2.nFaceIndex * 3 + 0]].v3Vertex;
Vector3 v3Other2 = meshData2.aVertexData[meshData2.aaIndices[face2.nSubMesh][face2.nFaceIndex * 3 + 1]].v3Vertex;
Vector3 v3Other3 = meshData2.aVertexData[meshData2.aaIndices[face2.nSubMesh][face2.nFaceIndex * 3 + 2]].v3Vertex;
float fArea2 = Vector3.Cross(v3Other3 - v3Other1, v3Other2 - v3Other1).magnitude;
bool bConnected = false;
if(Face2InsideFace1(fracturedComponent, this, meshData2, face1, face2))
{
bConnected = true;
}
else if(Face2InsideFace1(fracturedComponent, meshData2, this, face2, face1))
{
bConnected = true;
}
if(bConnected)
{
fSharedArea += Mathf.Min(fArea1, fArea2);
bHasSharedFaces = true;
}
}
}
}
}
return bHasSharedFaces;
}
private static bool Face2InsideFace1(FracturedObject fracturedComponent, MeshData meshData1, MeshData meshData2, MeshDataConnectivity.Face face1, MeshDataConnectivity.Face face2)
{
if(fracturedComponent.FracturePattern == FracturedObject.EFracturePattern.BSP)
{
if(meshData1.meshDataConnectivity.dicFace2IsClipped.ContainsKey(face1) == false && meshData2.meshDataConnectivity.dicFace2IsClipped.ContainsKey(face2) == false)
{
// Same face, because both haven't been clipped further
return true;
}
}
Vector3 v1 = meshData1.aVertexData[meshData1.aaIndices[face1.nSubMesh][face1.nFaceIndex * 3 + 0]].v3Vertex;
Vector3 v2 = meshData1.aVertexData[meshData1.aaIndices[face1.nSubMesh][face1.nFaceIndex * 3 + 1]].v3Vertex;
Vector3 v3 = meshData1.aVertexData[meshData1.aaIndices[face1.nSubMesh][face1.nFaceIndex * 3 + 2]].v3Vertex;
Vector3 v3Forward = -Vector3.Cross(v2 - v1, v3 - v1);
float fArea1 = v3Forward.magnitude;
if(fArea1 < Parameters.EPSILONCROSSPRODUCT)
{
return false;
}
Quaternion qFace = Quaternion.LookRotation(v3Forward.normalized, (v2 - v1).normalized);
Matrix4x4 mtxToFace = Matrix4x4.TRS(v1, qFace, Vector3.one).inverse;
Vector3 v3Other1 = meshData2.aVertexData[meshData2.aaIndices[face2.nSubMesh][face2.nFaceIndex * 3 + 0]].v3Vertex;
Vector3 v3Other2 = meshData2.aVertexData[meshData2.aaIndices[face2.nSubMesh][face2.nFaceIndex * 3 + 1]].v3Vertex;
Vector3 v3Other3 = meshData2.aVertexData[meshData2.aaIndices[face2.nSubMesh][face2.nFaceIndex * 3 + 2]].v3Vertex;
// We are going to check if the center is inside the face, doing it in face1 local coordinates
Vector3 v3OtherCenterLocal = (v3Other1 + v3Other2 + v3Other3) / 3.0f;
v3OtherCenterLocal = mtxToFace.MultiplyPoint3x4(v3OtherCenterLocal);
Vector3 v3Local1 = mtxToFace.MultiplyPoint3x4(v1);
Vector3 v3Local2 = mtxToFace.MultiplyPoint3x4(v2);
Vector3 v3Local3 = mtxToFace.MultiplyPoint3x4(v3);
Vector3 v3Edge2 = v3Local3 - v3Local2;
Vector3 v3Edge3 = v3Local1 - v3Local3;
bool bFaceConnected = false;
// Test the center
if(v3OtherCenterLocal.x >= 0.0f)
{
if(Vector3.Cross(v3Edge2, v3OtherCenterLocal - v3Local2).z <= 0.0f)
{
if(Vector3.Cross(v3Edge3, v3OtherCenterLocal - v3Local3).z <= 0.0f)
{
bFaceConnected = true;
}
}
}
// Test if the two triangles intersect in 2D
if(bFaceConnected == false)
{
// Try intersecting lines
Vector3 v3OtherLocal1 = mtxToFace.MultiplyPoint3x4(v3Other1);
Vector3 v3OtherLocal2 = mtxToFace.MultiplyPoint3x4(v3Other2);
Vector3 v3OtherLocal3 = mtxToFace.MultiplyPoint3x4(v3Other3);
if(bFaceConnected == false) if(Fracturer.IntersectEdges2D(v3OtherLocal1.x, v3OtherLocal1.y, v3OtherLocal2.x, v3OtherLocal2.y, v3Local1.x, v3Local1.y, v3Local2.x, v3Local2.y)) bFaceConnected = true;
if(bFaceConnected == false) if(Fracturer.IntersectEdges2D(v3OtherLocal1.x, v3OtherLocal1.y, v3OtherLocal2.x, v3OtherLocal2.y, v3Local2.x, v3Local2.y, v3Local3.x, v3Local3.y)) bFaceConnected = true;
if(bFaceConnected == false) if(Fracturer.IntersectEdges2D(v3OtherLocal1.x, v3OtherLocal1.y, v3OtherLocal2.x, v3OtherLocal2.y, v3Local3.x, v3Local3.y, v3Local1.x, v3Local1.y)) bFaceConnected = true;
if(bFaceConnected == false) if(Fracturer.IntersectEdges2D(v3OtherLocal2.x, v3OtherLocal2.y, v3OtherLocal3.x, v3OtherLocal3.y, v3Local1.x, v3Local1.y, v3Local2.x, v3Local2.y)) bFaceConnected = true;
if(bFaceConnected == false) if(Fracturer.IntersectEdges2D(v3OtherLocal2.x, v3OtherLocal2.y, v3OtherLocal3.x, v3OtherLocal3.y, v3Local2.x, v3Local2.y, v3Local3.x, v3Local3.y)) bFaceConnected = true;
if(bFaceConnected == false) if(Fracturer.IntersectEdges2D(v3OtherLocal2.x, v3OtherLocal2.y, v3OtherLocal3.x, v3OtherLocal3.y, v3Local3.x, v3Local3.y, v3Local1.x, v3Local1.y)) bFaceConnected = true;
if(bFaceConnected == false) if(Fracturer.IntersectEdges2D(v3OtherLocal3.x, v3OtherLocal3.y, v3OtherLocal1.x, v3OtherLocal1.y, v3Local1.x, v3Local1.y, v3Local2.x, v3Local2.y)) bFaceConnected = true;
if(bFaceConnected == false) if(Fracturer.IntersectEdges2D(v3OtherLocal3.x, v3OtherLocal3.y, v3OtherLocal1.x, v3OtherLocal1.y, v3Local2.x, v3Local2.y, v3Local3.x, v3Local3.y)) bFaceConnected = true;
if(bFaceConnected == false) if(Fracturer.IntersectEdges2D(v3OtherLocal3.x, v3OtherLocal3.y, v3OtherLocal1.x, v3OtherLocal1.y, v3Local3.x, v3Local3.y, v3Local1.x, v3Local1.y)) bFaceConnected = true;
}
return bFaceConnected;
}
static public List<MeshData> PostProcessConnectivity(MeshData meshDataSource, MeshFaceConnectivity connectivity, MeshDataConnectivity meshConnectivity, List<int>[] alistIndices, List<VertexData> listVertexData, int nSplitCloseSubMesh, int nCurrentVertexHash, bool bTransformToLocal)
{
List<MeshData> listMeshData = new List<MeshData>();
// Build some lists
List<int>[] alistFacesRemainingInOut = new List<int>[alistIndices.Length];
int[] aLinearFaceIndexStart = new int[alistIndices.Length];
int nLinearFaceIndexStart = 0;
List<int>[] alistIndicesOut = new List<int>[alistIndices.Length];
List<VertexData> listVertexDataOut = new List<VertexData>();
Dictionary<int, int> dicVertexRemap = new Dictionary<int, int>();
for(int nSubMesh = 0; nSubMesh < alistIndices.Length; nSubMesh++)
{
// Remaining faces to process
alistFacesRemainingInOut[nSubMesh] = new List<int>();
for(int nFace = 0; nFace < alistIndices[nSubMesh].Count / 3; nFace++)
{
alistFacesRemainingInOut[nSubMesh].Add(nFace);
}
// Face index start list
aLinearFaceIndexStart[nSubMesh] = nLinearFaceIndexStart;
nLinearFaceIndexStart += alistIndices[nSubMesh].Count / 3;
// Mesh indices out
alistIndicesOut[nSubMesh] = new List<int>();
}
// Process
while(StillHasFacesToProcess(alistFacesRemainingInOut))
{
// Isolete objects
for(int nSubMesh = 0; nSubMesh < alistFacesRemainingInOut.Length; nSubMesh++)
{
if(alistFacesRemainingInOut[nSubMesh].Count > 0)
{
dicVertexRemap.Clear();
listVertexDataOut.Clear();
MeshDataConnectivity meshConnectivityOut = new MeshDataConnectivity();
for(int i = 0; i < alistIndices.Length; i++)
{
alistIndicesOut[i].Clear();
}
// Start process
LookForClosedObjectRecursive(connectivity, meshConnectivity, nSubMesh, alistFacesRemainingInOut[nSubMesh][0], alistIndices, listVertexData, alistFacesRemainingInOut, aLinearFaceIndexStart, alistIndicesOut, listVertexDataOut, dicVertexRemap, meshConnectivityOut);
// Build transform
Vector3 v3Min = Vector3.zero, v3Max = Vector3.zero;
MeshData.ComputeMinMax(listVertexDataOut, ref v3Min, ref v3Max);
Vector3 v3Center = (v3Min + v3Max) * 0.5f;
Matrix4x4 mtxTransformVertices = Matrix4x4.TRS(v3Center, meshDataSource.qRotation, meshDataSource.v3Scale);
// Add new meshData
MeshData newMeshData = new MeshData(meshDataSource.aMaterials, alistIndicesOut, listVertexDataOut, nSplitCloseSubMesh, v3Center, meshDataSource.qRotation, meshDataSource.v3Scale, mtxTransformVertices, bTransformToLocal, false);
newMeshData.meshDataConnectivity = meshConnectivityOut;
newMeshData.nCurrentVertexHash = nCurrentVertexHash;
listMeshData.Add(newMeshData);
}
}
}
return listMeshData;
}
static private bool StillHasFacesToProcess(List<int>[] alistFacesRemaining)
{
foreach(List<int> listFaces in alistFacesRemaining)
{
if(listFaces.Count > 0)
{
return true;
}
}
return false;
}
static private void LookForClosedObjectRecursive(MeshFaceConnectivity connectivity, MeshDataConnectivity meshConnectivity, int nSubMeshStart, int nFaceSubMeshStart, List<int>[] alistIndicesIn, List<VertexData> listVertexDataIn, List<int>[] alistFacesRemainingInOut, int[] aLinearFaceIndexStart, List<int>[] alistIndicesOut, List<VertexData> listVertexDataOut, Dictionary<int, int> dicVertexRemap, MeshDataConnectivity meshConnectivityOut)
{
MeshFaceConnectivity.TriangleData triangle = connectivity.listTriangles[aLinearFaceIndexStart[nSubMeshStart] + nFaceSubMeshStart];
// Check if we already visited this triangle
if(triangle.bVisited)
{
return;
}
// Add vertex data of this face. Add new indices in new list and remove processed face from remaining face list.
meshConnectivityOut.NotifyRemappedFace(meshConnectivity, nSubMeshStart, nFaceSubMeshStart, nSubMeshStart, alistIndicesOut[nSubMeshStart].Count / 3);
for(int i = 0; i < 3; i++)
{
int nIndexIn = alistIndicesIn[nSubMeshStart][nFaceSubMeshStart * 3 + i];
if(dicVertexRemap.ContainsKey(nIndexIn))
{
alistIndicesOut[nSubMeshStart].Add(dicVertexRemap[nIndexIn]);
}
else
{
int nNewIndexOut = listVertexDataOut.Count;
alistIndicesOut[nSubMeshStart].Add(nNewIndexOut);
listVertexDataOut.Add(listVertexDataIn[nIndexIn].Copy());
dicVertexRemap.Add(nIndexIn, nNewIndexOut);
}
}
alistFacesRemainingInOut[nSubMeshStart].Remove(nFaceSubMeshStart);
triangle.bVisited = true;
// Recurse into adjacent triangles
for(int i = 0; i < 3; i++)
{
MeshFaceConnectivity.TriangleData triangleAdjacent = null;
for(int nSide = 0; nSide < triangle.alistNeighborSubMeshes[i].Count; nSide++)
{
if(triangle.alistNeighborSubMeshes[i][nSide] != -1 && triangle.alistNeighborTriangles[i][nSide] != -1)
{
triangleAdjacent = connectivity.listTriangles[aLinearFaceIndexStart[triangle.alistNeighborSubMeshes[i][nSide]] + triangle.alistNeighborTriangles[i][nSide]];
}
if(triangleAdjacent != null)
{
if(triangleAdjacent.bVisited != true)
{
LookForClosedObjectRecursive(connectivity, meshConnectivity, triangleAdjacent.nSubMesh, triangleAdjacent.nTriangle, alistIndicesIn, listVertexDataIn, alistFacesRemainingInOut, aLinearFaceIndexStart, alistIndicesOut, listVertexDataOut, dicVertexRemap, meshConnectivityOut);
}
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using BudgetAnalyser.Engine;
using BudgetAnalyser.Annotations;
using BudgetAnalyser.Engine.BankAccount;
using BudgetAnalyser.Engine.Ledger;
using BudgetAnalyser.Filtering;
using BudgetAnalyser.ShellDialog;
using GalaSoft.MvvmLight.CommandWpf;
using Rees.UserInteraction.Contracts;
using Rees.Wpf;
namespace BudgetAnalyser.LedgerBook
{
[AutoRegisterWithIoC(SingleInstance = true)]
public class AddLedgerReconciliationController : ControllerBase, IShellDialogToolTips, IShellDialogInteractivity
{
private readonly IAccountTypeRepository accountTypeRepository;
private readonly IUserMessageBox messageBox;
private Guid dialogCorrelationId;
private bool doNotUseAddBalanceVisibility;
private IEnumerable<Account> doNotUseBankAccounts;
private decimal doNotUseBankBalance;
private DateTime doNotUseDate;
private bool doNotUseEditable;
private Account doNotUseSelectedBankAccount;
private Engine.Ledger.LedgerBook parentBook;
public AddLedgerReconciliationController(
[NotNull] UiContext uiContext,
[NotNull] IAccountTypeRepository accountTypeRepository)
{
this.accountTypeRepository = accountTypeRepository;
if (uiContext == null)
{
throw new ArgumentNullException(nameof(uiContext));
}
if (accountTypeRepository == null)
{
throw new ArgumentNullException(nameof(accountTypeRepository));
}
MessengerInstance = uiContext.Messenger;
MessengerInstance.Register<ShellDialogResponseMessage>(this, OnShellDialogResponseReceived);
this.messageBox = uiContext.UserPrompts.MessageBox;
}
public event EventHandler<EditBankBalancesEventArgs> Complete;
public string ActionButtonToolTip => "Add new ledger entry line.";
public bool AddBalanceVisibility
{
get { return this.doNotUseAddBalanceVisibility; }
private set
{
this.doNotUseAddBalanceVisibility = value;
RaisePropertyChanged();
}
}
[UsedImplicitly]
public ICommand AddBankBalanceCommand => new RelayCommand(OnAddBankBalanceCommandExecuted, CanExecuteAddBankBalanceCommand);
public decimal? AdjustedBankBalanceTotal
{
get { return AddBalanceVisibility ? default(decimal?) : BankBalances.Sum(b => b.AdjustedBalance); }
}
public IEnumerable<Account> BankAccounts
{
[UsedImplicitly] get { return this.doNotUseBankAccounts; }
private set
{
this.doNotUseBankAccounts = value;
RaisePropertyChanged();
}
}
public decimal BankBalance
{
get { return this.doNotUseBankBalance; }
set
{
this.doNotUseBankBalance = value;
RaisePropertyChanged();
RaisePropertyChanged(() => BankBalanceTotal);
RaisePropertyChanged(() => AdjustedBankBalanceTotal);
}
}
public ObservableCollection<BankBalanceViewModel> BankBalances { get; private set; }
public decimal BankBalanceTotal => BankBalances.Sum(b => b.Balance);
public bool Canceled { get; private set; }
public bool CanExecuteCancelButton => true;
public bool CanExecuteOkButton
{
get
{
if (CreateMode)
{
return Date != DateTime.MinValue && HasRequiredBalances;
}
return Editable && Date != DateTime.MinValue && HasRequiredBalances;
}
}
public bool CanExecuteSaveButton => false;
public string CloseButtonToolTip => "Cancel";
public bool CreateMode { get; private set; }
public DateTime Date
{
get { return this.doNotUseDate; }
set
{
this.doNotUseDate = value;
RaisePropertyChanged();
}
}
public bool Editable
{
get { return this.doNotUseEditable; }
private set
{
this.doNotUseEditable = value;
RaisePropertyChanged();
}
}
/// <summary>
/// Checks to make sure the <see cref="BankBalances" /> collection contains a balance for every ledger that will be
/// included in the reconciliation.
/// </summary>
public bool HasRequiredBalances => this.parentBook.Ledgers.All(l => BankBalances.Any(b => b.Account == l.StoredInAccount));
[UsedImplicitly]
public ICommand RemoveBankBalanceCommand => new RelayCommand<BankBalanceViewModel>(OnRemoveBankBalanceCommandExecuted, x => Editable);
public Account SelectedBankAccount
{
get { return this.doNotUseSelectedBankAccount; }
set
{
this.doNotUseSelectedBankAccount = value;
RaisePropertyChanged();
}
}
/// <summary>
/// Used to start a new Ledger Book reconciliation. This will ultimately add a new <see cref="LedgerEntryLine" /> to
/// the <see cref="LedgerBook" />.
/// </summary>
public void ShowCreateDialog([NotNull] Engine.Ledger.LedgerBook ledgerBook)
{
if (ledgerBook == null)
{
throw new ArgumentNullException(nameof(ledgerBook));
}
this.parentBook = ledgerBook;
BankBalances = new ObservableCollection<BankBalanceViewModel>();
CreateMode = true;
AddBalanceVisibility = true;
Editable = true;
var requestFilterMessage = new RequestFilterMessage(this);
MessengerInstance.Send(requestFilterMessage);
Date = requestFilterMessage.Criteria.EndDate?.AddDays(1) ?? DateTime.Today;
ShowDialogCommon("New Monthly Reconciliation");
}
/// <summary>
/// Used to show the bank balances involved in this <see cref="LedgerEntryLine" />.
/// Only shows balances at this stage, no editing allowed.
/// </summary>
public void ShowViewDialog([NotNull] Engine.Ledger.LedgerBook ledgerBook, [NotNull] LedgerEntryLine line)
{
if (ledgerBook == null)
{
throw new ArgumentNullException(nameof(ledgerBook));
}
if (line == null)
{
throw new ArgumentNullException(nameof(line));
}
this.parentBook = ledgerBook;
Date = line.Date;
BankBalances = new ObservableCollection<BankBalanceViewModel>(line.BankBalances.Select(b => new BankBalanceViewModel(line, b)));
CreateMode = false;
AddBalanceVisibility = false;
Editable = false; // Bank balances are not editable after creating a new Ledger Line at this stage.
ShowDialogCommon(Editable ? "Edit Bank Balances" : "Bank Balances");
}
private void AddNewBankBalance()
{
BankBalances.Add(new BankBalanceViewModel(null, SelectedBankAccount, BankBalance));
SelectedBankAccount = null;
BankBalance = 0;
RaisePropertyChanged(() => HasRequiredBalances);
}
private bool CanExecuteAddBankBalanceCommand()
{
if (CreateMode)
{
return SelectedBankAccount != null;
}
if (!Editable)
{
return false;
}
if (!AddBalanceVisibility)
{
return true;
}
return SelectedBankAccount != null;
}
private void OnAddBankBalanceCommandExecuted()
{
if (CreateMode)
{
AddNewBankBalance();
return;
}
if (!AddBalanceVisibility)
{
AddBalanceVisibility = true;
return;
}
AddBalanceVisibility = false;
AddNewBankBalance();
}
private void OnRemoveBankBalanceCommandExecuted(BankBalanceViewModel bankBalance)
{
if (bankBalance == null)
{
return;
}
BankBalances.Remove(bankBalance);
RaisePropertyChanged(() => BankBalanceTotal);
RaisePropertyChanged(() => AdjustedBankBalanceTotal);
RaisePropertyChanged(() => HasRequiredBalances);
}
private void OnShellDialogResponseReceived(ShellDialogResponseMessage message)
{
if (!message.IsItForMe(this.dialogCorrelationId))
{
return;
}
try
{
if (message.Response == ShellDialogButton.Help)
{
this.messageBox.Show(
"Use your actual pay day as the date, this signifies the closing of the previous month, and opening a new month on your pay day showing available funds in each ledger for the new month. The date used will also be used to select transactions from the statement to calculate the ledger balance. The date is set from the current date range filter (on the dashboard page), using the day after the end date. Transactions will be found by searching one month prior to the given date, excluding the given date. The transactions are used to show how the current ledger balance is calculated. The bank balance is the balance as at the date given, after your pay has been credited.");
return;
}
if (message.Response == ShellDialogButton.Cancel)
{
Canceled = true;
}
else
{
if (BankBalances.None())
{
if (CanExecuteAddBankBalanceCommand())
{
// User may have entered some data to add a new bank balance to the collection, but not clicked the add button, instead they just clicked save.
OnAddBankBalanceCommandExecuted();
}
else
{
throw new InvalidOperationException("Failed to add any bank balances to Ledger Book reconciliation.");
}
}
}
EventHandler<EditBankBalancesEventArgs> handler = Complete;
handler?.Invoke(this, new EditBankBalancesEventArgs { Canceled = Canceled });
}
finally
{
Reset();
}
}
private void Reset()
{
this.parentBook = null;
Date = DateTime.MinValue;
BankBalances = null;
BankAccounts = null;
SelectedBankAccount = null;
}
private void ShowDialogCommon(string title)
{
Canceled = false;
List<Account> accountsToShow = this.accountTypeRepository.ListCurrentlyUsedAccountTypes().ToList();
BankAccounts = accountsToShow.OrderBy(a => a.Name);
SelectedBankAccount = null;
this.dialogCorrelationId = Guid.NewGuid();
var dialogRequest = new ShellDialogRequestMessage(BudgetAnalyserFeature.LedgerBook, this, ShellDialogType.OkCancel)
{
CorrelationId = this.dialogCorrelationId,
Title = title,
HelpAvailable = CreateMode
};
MessengerInstance.Send(dialogRequest);
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// James Driscoll, mailto:jamesdriscoll@btinternet.com
// with contributions from Hath1
//
// 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
// All code in this file requires .NET Framework 1.1 or later.
#if !NET_1_0
[assembly: Elmah.Scc("$Id$")]
namespace Elmah
{
#region Imports
using System;
using System.Data;
using System.Data.OracleClient;
using System.IO;
using System.Text;
using IDictionary = System.Collections.IDictionary;
using IList = System.Collections.IList;
#endregion
/// <summary>
/// An <see cref="ErrorLog"/> implementation that uses Oracle as its backing store.
/// </summary>
public class OracleErrorLog : ErrorLog
{
private readonly string _connectionString;
private string _schemaOwner;
private bool _schemaOwnerInitialized;
private const int _maxAppNameLength = 60;
private const int _maxSchemaNameLength = 30;
/// <summary>
/// Initializes a new instance of the <see cref="OracleErrorLog"/> class
/// using a dictionary of configured settings.
/// </summary>
public OracleErrorLog(IDictionary config)
{
if (config == null)
throw new ArgumentNullException("config");
string connectionString = ConnectionStringHelper.GetConnectionString(config);
//
// If there is no connection string to use then throw an
// exception to abort construction.
//
if (connectionString.Length == 0)
throw new ApplicationException("Connection string is missing for the Oracle error log.");
_connectionString = connectionString;
//
// Set the application name as this implementation provides
// per-application isolation over a single store.
//
string appName = Mask.NullString((string)config["applicationName"]);
if (appName.Length > _maxAppNameLength)
{
throw new ApplicationException(string.Format(
"Application name is too long. Maximum length allowed is {0} characters.",
_maxAppNameLength.ToString("N0")));
}
ApplicationName = appName;
SchemaOwner = (string)config["schemaOwner"];
}
/// <summary>
/// Initializes a new instance of the <see cref="OracleErrorLog"/> class
/// to use a specific connection string for connecting to the database.
/// </summary>
public OracleErrorLog(string connectionString)
{
if (connectionString == null)
throw new ArgumentNullException("connectionString");
if (connectionString.Length == 0)
throw new ArgumentException(null, "connectionString");
_connectionString = connectionString;
}
/// <summary>
/// Initializes a new instance of the <see cref="OracleErrorLog"/> class
/// to use a specific connection string for connecting to the database and
/// a specific schema owner.
/// </summary>
public OracleErrorLog(string connectionString, string schemaOwner)
: this(connectionString)
{
SchemaOwner = schemaOwner;
}
/// <summary>
/// Gets the name of the schema owner where the errors are being stored.
/// </summary>
public string SchemaOwner
{
get { return Mask.NullString(_schemaOwner); }
set
{
if (_schemaOwnerInitialized)
throw new InvalidOperationException("The schema owner cannot be reset once initialized.");
_schemaOwner = Mask.NullString(value);
if (_schemaOwner.Length == 0)
return;
if (_schemaOwner.Length > _maxSchemaNameLength)
throw new ApplicationException(string.Format(
"Oracle schema owner is too long. Maximum length allowed is {0} characters.",
_maxSchemaNameLength.ToString("N0")));
_schemaOwner = _schemaOwner + ".";
_schemaOwnerInitialized = true;
}
}
/// <summary>
/// Gets the name of this error log implementation.
/// </summary>
public override string Name
{
get { return "Oracle Error Log"; }
}
/// <summary>
/// Gets the connection string used by the log to connect to the database.
/// </summary>
public virtual string ConnectionString
{
get { return _connectionString; }
}
/// <summary>
/// Logs an error to the database.
/// </summary>
/// <remarks>
/// Use the stored procedure called by this implementation to set a
/// policy on how long errors are kept in the log. The default
/// implementation stores all errors for an indefinite time.
/// </remarks>
public override string Log(Error error)
{
if (error == null)
throw new ArgumentNullException("error");
string errorXml = ErrorXml.EncodeString(error);
Guid id = Guid.NewGuid();
using (OracleConnection connection = new OracleConnection(this.ConnectionString))
using (OracleCommand command = connection.CreateCommand())
{
connection.Open();
using (OracleTransaction transaction = connection.BeginTransaction())
{
// because we are storing the XML data in a NClob, we need to jump through a few hoops!!
// so first we've got to operate within a transaction
command.Transaction = transaction;
// then we need to create a temporary lob on the database server
command.CommandText = "declare xx nclob; begin dbms_lob.createtemporary(xx, false, 0); :tempblob := xx; end;";
command.CommandType = CommandType.Text;
OracleParameterCollection parameters = command.Parameters;
parameters.Add("tempblob", OracleType.NClob).Direction = ParameterDirection.Output;
command.ExecuteNonQuery();
// now we can get a handle to the NClob
OracleLob xmlLob = (OracleLob)parameters[0].Value;
// create a temporary buffer in which to store the XML
byte[] tempbuff = Encoding.Unicode.GetBytes(errorXml);
// and finally we can write to it!
xmlLob.BeginBatch(OracleLobOpenMode.ReadWrite);
xmlLob.Write(tempbuff,0,tempbuff.Length);
xmlLob.EndBatch();
command.CommandText = SchemaOwner + "pkg_elmah$log_error.LogError";
command.CommandType = CommandType.StoredProcedure;
parameters.Clear();
parameters.Add("v_ErrorId", OracleType.NVarChar, 32).Value = id.ToString("N");
parameters.Add("v_Application", OracleType.NVarChar, _maxAppNameLength).Value = ApplicationName;
parameters.Add("v_Host", OracleType.NVarChar, 30).Value = error.HostName;
parameters.Add("v_Type", OracleType.NVarChar, 100).Value = error.Type;
parameters.Add("v_Source", OracleType.NVarChar, 60).Value = error.Source;
parameters.Add("v_Message", OracleType.NVarChar, 500).Value = error.Message;
parameters.Add("v_User", OracleType.NVarChar, 50).Value = error.User;
parameters.Add("v_AllXml", OracleType.NClob).Value = xmlLob;
parameters.Add("v_StatusCode", OracleType.Int32).Value = error.StatusCode;
parameters.Add("v_TimeUtc", OracleType.DateTime).Value = error.Time.ToUniversalTime();
command.ExecuteNonQuery();
transaction.Commit();
}
return id.ToString();
}
}
/// <summary>
/// Returns a page of errors from the databse in descending order
/// of logged time.
/// </summary>
public override int GetErrors(int pageIndex, int pageSize, IList errorEntryList)
{
if (pageIndex < 0)
throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null);
if (pageSize < 0)
throw new ArgumentOutOfRangeException("pageSize", pageSize, null);
using (OracleConnection connection = new OracleConnection(this.ConnectionString))
using (OracleCommand command = connection.CreateCommand())
{
command.CommandText = SchemaOwner + "pkg_elmah$get_error.GetErrorsXml";
command.CommandType = CommandType.StoredProcedure;
OracleParameterCollection parameters = command.Parameters;
parameters.Add("v_Application", OracleType.NVarChar, _maxAppNameLength).Value = ApplicationName;
parameters.Add("v_PageIndex", OracleType.Int32).Value = pageIndex;
parameters.Add("v_PageSize", OracleType.Int32).Value = pageSize;
parameters.Add("v_TotalCount", OracleType.Int32).Direction = ParameterDirection.Output;
parameters.Add("v_Results", OracleType.Cursor).Direction = ParameterDirection.Output;
connection.Open();
using (OracleDataReader reader = command.ExecuteReader())
{
Debug.Assert(reader != null);
if (errorEntryList != null)
{
while (reader.Read())
{
string id = reader["ErrorId"].ToString();
Guid guid = new Guid(id);
Error error = new Error();
error.ApplicationName = reader["Application"].ToString();
error.HostName = reader["Host"].ToString();
error.Type = reader["Type"].ToString();
error.Source = reader["Source"].ToString();
error.Message = reader["Message"].ToString();
error.User = reader["UserName"].ToString();
error.StatusCode = Convert.ToInt32(reader["StatusCode"]);
error.Time = Convert.ToDateTime(reader["TimeUtc"]).ToLocalTime();
errorEntryList.Add(new ErrorLogEntry(this, guid.ToString(), error));
}
}
reader.Close();
}
return (int)command.Parameters["v_TotalCount"].Value;
}
}
/// <summary>
/// Returns the specified error from the database, or null
/// if it does not exist.
/// </summary>
public override ErrorLogEntry GetError(string id)
{
if (id == null)
throw new ArgumentNullException("id");
if (id.Length == 0)
throw new ArgumentException(null, "id");
Guid errorGuid;
try
{
errorGuid = new Guid(id);
}
catch (FormatException e)
{
throw new ArgumentException(e.Message, "id", e);
}
string errorXml;
using (OracleConnection connection = new OracleConnection(this.ConnectionString))
using (OracleCommand command = connection.CreateCommand())
{
command.CommandText = SchemaOwner + "pkg_elmah$get_error.GetErrorXml";
command.CommandType = CommandType.StoredProcedure;
OracleParameterCollection parameters = command.Parameters;
parameters.Add("v_Application", OracleType.NVarChar, _maxAppNameLength).Value = ApplicationName;
parameters.Add("v_ErrorId", OracleType.NVarChar, 32).Value = errorGuid.ToString("N");
parameters.Add("v_AllXml", OracleType.NClob).Direction = ParameterDirection.Output;
connection.Open();
command.ExecuteNonQuery();
OracleLob xmlLob = (OracleLob)command.Parameters["v_AllXml"].Value;
StreamReader streamreader = new StreamReader(xmlLob, Encoding.Unicode);
char[] cbuffer = new char[1000];
int actual;
StringBuilder sb = new StringBuilder();
while((actual = streamreader.Read(cbuffer, 0, cbuffer.Length)) >0)
sb.Append(cbuffer, 0, actual);
errorXml = sb.ToString();
}
if (errorXml == null)
return null;
Error error = ErrorXml.DecodeString(errorXml);
return new ErrorLogEntry(this, id, error);
}
}
}
#endif //!NET_1_0
| |
// 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.Runtime.Serialization;
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace System.Xml
{
internal enum ValueHandleConstStringType
{
String = 0,
Number = 1,
Array = 2,
Object = 3,
Boolean = 4,
Null = 5,
}
internal static class ValueHandleLength
{
public const int Int8 = 1;
public const int Int16 = 2;
public const int Int32 = 4;
public const int Int64 = 8;
public const int UInt64 = 8;
public const int Single = 4;
public const int Double = 8;
public const int Decimal = 16;
public const int DateTime = 8;
public const int TimeSpan = 8;
public const int Guid = 16;
public const int UniqueId = 16;
}
internal enum ValueHandleType
{
Empty,
True,
False,
Zero,
One,
Int8,
Int16,
Int32,
Int64,
UInt64,
Single,
Double,
Decimal,
DateTime,
TimeSpan,
Guid,
UniqueId,
UTF8,
EscapedUTF8,
Base64,
Dictionary,
List,
Char,
Unicode,
QName,
ConstString
}
internal class ValueHandle
{
private XmlBufferReader _bufferReader;
private ValueHandleType _type;
private int _offset;
private int _length;
private static Base64Encoding s_base64Encoding;
private static string[] s_constStrings = {
"string",
"number",
"array",
"object",
"boolean",
"null",
};
public ValueHandle(XmlBufferReader bufferReader)
{
_bufferReader = bufferReader;
_type = ValueHandleType.Empty;
}
private static Base64Encoding Base64Encoding
{
get
{
if (s_base64Encoding == null)
s_base64Encoding = new Base64Encoding();
return s_base64Encoding;
}
}
public void SetConstantValue(ValueHandleConstStringType constStringType)
{
_type = ValueHandleType.ConstString;
_offset = (int)constStringType;
}
public void SetValue(ValueHandleType type)
{
_type = type;
}
public void SetDictionaryValue(int key)
{
SetValue(ValueHandleType.Dictionary, key, 0);
}
public void SetCharValue(int ch)
{
SetValue(ValueHandleType.Char, ch, 0);
}
public void SetQNameValue(int prefix, int key)
{
SetValue(ValueHandleType.QName, key, prefix);
}
public void SetValue(ValueHandleType type, int offset, int length)
{
_type = type;
_offset = offset;
_length = length;
}
public bool IsWhitespace()
{
switch (_type)
{
case ValueHandleType.UTF8:
return _bufferReader.IsWhitespaceUTF8(_offset, _length);
case ValueHandleType.Dictionary:
return _bufferReader.IsWhitespaceKey(_offset);
case ValueHandleType.Char:
int ch = GetChar();
if (ch > char.MaxValue)
return false;
return XmlConverter.IsWhitespace((char)ch);
case ValueHandleType.EscapedUTF8:
return _bufferReader.IsWhitespaceUTF8(_offset, _length);
case ValueHandleType.Unicode:
return _bufferReader.IsWhitespaceUnicode(_offset, _length);
case ValueHandleType.True:
case ValueHandleType.False:
case ValueHandleType.Zero:
case ValueHandleType.One:
return false;
case ValueHandleType.ConstString:
return s_constStrings[_offset].Length == 0;
default:
return _length == 0;
}
}
public Type ToType()
{
switch (_type)
{
case ValueHandleType.False:
case ValueHandleType.True:
return typeof(bool);
case ValueHandleType.Zero:
case ValueHandleType.One:
case ValueHandleType.Int8:
case ValueHandleType.Int16:
case ValueHandleType.Int32:
return typeof(int);
case ValueHandleType.Int64:
return typeof(long);
case ValueHandleType.UInt64:
return typeof(ulong);
case ValueHandleType.Single:
return typeof(float);
case ValueHandleType.Double:
return typeof(double);
case ValueHandleType.Decimal:
return typeof(decimal);
case ValueHandleType.DateTime:
return typeof(DateTime);
case ValueHandleType.Empty:
case ValueHandleType.UTF8:
case ValueHandleType.Unicode:
case ValueHandleType.EscapedUTF8:
case ValueHandleType.Dictionary:
case ValueHandleType.Char:
case ValueHandleType.QName:
case ValueHandleType.ConstString:
return typeof(string);
case ValueHandleType.Base64:
return typeof(byte[]);
case ValueHandleType.List:
return typeof(object[]);
case ValueHandleType.UniqueId:
return typeof(UniqueId);
case ValueHandleType.Guid:
return typeof(Guid);
case ValueHandleType.TimeSpan:
return typeof(TimeSpan);
default:
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());
}
}
public Boolean ToBoolean()
{
ValueHandleType type = _type;
if (type == ValueHandleType.False)
return false;
if (type == ValueHandleType.True)
return true;
if (type == ValueHandleType.UTF8)
return XmlConverter.ToBoolean(_bufferReader.Buffer, _offset, _length);
if (type == ValueHandleType.Int8)
{
int value = GetInt8();
if (value == 0)
return false;
if (value == 1)
return true;
}
return XmlConverter.ToBoolean(GetString());
}
public int ToInt()
{
ValueHandleType type = _type;
if (type == ValueHandleType.Zero)
return 0;
if (type == ValueHandleType.One)
return 1;
if (type == ValueHandleType.Int8)
return GetInt8();
if (type == ValueHandleType.Int16)
return GetInt16();
if (type == ValueHandleType.Int32)
return GetInt32();
if (type == ValueHandleType.Int64)
{
long value = GetInt64();
if (value >= int.MinValue && value <= int.MaxValue)
{
return (int)value;
}
}
if (type == ValueHandleType.UInt64)
{
ulong value = GetUInt64();
if (value <= int.MaxValue)
{
return (int)value;
}
}
if (type == ValueHandleType.UTF8)
return XmlConverter.ToInt32(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToInt32(GetString());
}
public long ToLong()
{
ValueHandleType type = _type;
if (type == ValueHandleType.Zero)
return 0;
if (type == ValueHandleType.One)
return 1;
if (type == ValueHandleType.Int8)
return GetInt8();
if (type == ValueHandleType.Int16)
return GetInt16();
if (type == ValueHandleType.Int32)
return GetInt32();
if (type == ValueHandleType.Int64)
return GetInt64();
if (type == ValueHandleType.UInt64)
{
ulong value = GetUInt64();
if (value <= long.MaxValue)
{
return (long)value;
}
}
if (type == ValueHandleType.UTF8)
{
return XmlConverter.ToInt64(_bufferReader.Buffer, _offset, _length);
}
return XmlConverter.ToInt64(GetString());
}
public ulong ToULong()
{
ValueHandleType type = _type;
if (type == ValueHandleType.Zero)
return 0;
if (type == ValueHandleType.One)
return 1;
if (type >= ValueHandleType.Int8 && type <= ValueHandleType.Int64)
{
long value = ToLong();
if (value >= 0)
return (ulong)value;
}
if (type == ValueHandleType.UInt64)
return GetUInt64();
if (type == ValueHandleType.UTF8)
return XmlConverter.ToUInt64(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToUInt64(GetString());
}
public Single ToSingle()
{
ValueHandleType type = _type;
if (type == ValueHandleType.Single)
return GetSingle();
if (type == ValueHandleType.Double)
{
double value = GetDouble();
if ((value >= Single.MinValue && value <= Single.MaxValue) || !double.IsFinite(value))
{
return (Single)value;
}
}
if (type == ValueHandleType.Zero)
return 0;
if (type == ValueHandleType.One)
return 1;
if (type == ValueHandleType.Int8)
return GetInt8();
if (type == ValueHandleType.Int16)
return GetInt16();
if (type == ValueHandleType.UTF8)
return XmlConverter.ToSingle(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToSingle(GetString());
}
public Double ToDouble()
{
ValueHandleType type = _type;
if (type == ValueHandleType.Double)
return GetDouble();
if (type == ValueHandleType.Single)
return GetSingle();
if (type == ValueHandleType.Zero)
return 0;
if (type == ValueHandleType.One)
return 1;
if (type == ValueHandleType.Int8)
return GetInt8();
if (type == ValueHandleType.Int16)
return GetInt16();
if (type == ValueHandleType.Int32)
return GetInt32();
if (type == ValueHandleType.UTF8)
return XmlConverter.ToDouble(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToDouble(GetString());
}
public Decimal ToDecimal()
{
ValueHandleType type = _type;
if (type == ValueHandleType.Decimal)
return GetDecimal();
if (type == ValueHandleType.Zero)
return 0;
if (type == ValueHandleType.One)
return 1;
if (type >= ValueHandleType.Int8 && type <= ValueHandleType.Int64)
return ToLong();
if (type == ValueHandleType.UInt64)
return GetUInt64();
if (type == ValueHandleType.UTF8)
return XmlConverter.ToDecimal(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToDecimal(GetString());
}
public DateTime ToDateTime()
{
if (_type == ValueHandleType.DateTime)
{
return XmlConverter.ToDateTime(GetInt64());
}
if (_type == ValueHandleType.UTF8)
{
return XmlConverter.ToDateTime(_bufferReader.Buffer, _offset, _length);
}
return XmlConverter.ToDateTime(GetString());
}
public UniqueId ToUniqueId()
{
if (_type == ValueHandleType.UniqueId)
return GetUniqueId();
if (_type == ValueHandleType.UTF8)
return XmlConverter.ToUniqueId(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToUniqueId(GetString());
}
public TimeSpan ToTimeSpan()
{
if (_type == ValueHandleType.TimeSpan)
return new TimeSpan(GetInt64());
if (_type == ValueHandleType.UTF8)
return XmlConverter.ToTimeSpan(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToTimeSpan(GetString());
}
public Guid ToGuid()
{
if (_type == ValueHandleType.Guid)
return GetGuid();
if (_type == ValueHandleType.UTF8)
return XmlConverter.ToGuid(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToGuid(GetString());
}
public override string ToString()
{
return GetString();
}
public byte[] ToByteArray()
{
if (_type == ValueHandleType.Base64)
{
byte[] buffer = new byte[_length];
GetBase64(buffer, 0, _length);
return buffer;
}
if (_type == ValueHandleType.UTF8 && (_length % 4) == 0)
{
try
{
int expectedLength = _length / 4 * 3;
if (_length > 0)
{
if (_bufferReader.Buffer[_offset + _length - 1] == '=')
{
expectedLength--;
if (_bufferReader.Buffer[_offset + _length - 2] == '=')
expectedLength--;
}
}
byte[] buffer = new byte[expectedLength];
int actualLength = Base64Encoding.GetBytes(_bufferReader.Buffer, _offset, _length, buffer, 0);
if (actualLength != buffer.Length)
{
byte[] newBuffer = new byte[actualLength];
Buffer.BlockCopy(buffer, 0, newBuffer, 0, actualLength);
buffer = newBuffer;
}
return buffer;
}
catch (FormatException)
{
// Something unhappy with the characters, fall back to the hard way
}
}
try
{
return Base64Encoding.GetBytes(XmlConverter.StripWhitespace(GetString()));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(exception.Message, exception.InnerException));
}
}
public string GetString()
{
ValueHandleType type = _type;
if (type == ValueHandleType.UTF8)
return GetCharsText();
switch (type)
{
case ValueHandleType.False:
return "false";
case ValueHandleType.True:
return "true";
case ValueHandleType.Zero:
return "0";
case ValueHandleType.One:
return "1";
case ValueHandleType.Int8:
case ValueHandleType.Int16:
case ValueHandleType.Int32:
return XmlConverter.ToString(ToInt());
case ValueHandleType.Int64:
return XmlConverter.ToString(GetInt64());
case ValueHandleType.UInt64:
return XmlConverter.ToString(GetUInt64());
case ValueHandleType.Single:
return XmlConverter.ToString(GetSingle());
case ValueHandleType.Double:
return XmlConverter.ToString(GetDouble());
case ValueHandleType.Decimal:
return XmlConverter.ToString(GetDecimal());
case ValueHandleType.DateTime:
return XmlConverter.ToString(ToDateTime());
case ValueHandleType.Empty:
return string.Empty;
case ValueHandleType.Unicode:
return GetUnicodeCharsText();
case ValueHandleType.EscapedUTF8:
return GetEscapedCharsText();
case ValueHandleType.Char:
return GetCharText();
case ValueHandleType.Dictionary:
return GetDictionaryString().Value;
case ValueHandleType.Base64:
byte[] bytes = ToByteArray();
DiagnosticUtility.DebugAssert(bytes != null, "");
return Base64Encoding.GetString(bytes, 0, bytes.Length);
case ValueHandleType.List:
return XmlConverter.ToString(ToList());
case ValueHandleType.UniqueId:
return XmlConverter.ToString(ToUniqueId());
case ValueHandleType.Guid:
return XmlConverter.ToString(ToGuid());
case ValueHandleType.TimeSpan:
return XmlConverter.ToString(ToTimeSpan());
case ValueHandleType.QName:
return GetQNameDictionaryText();
case ValueHandleType.ConstString:
return s_constStrings[_offset];
default:
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());
}
}
// ASSUMPTION (Microsoft): all chars in str will be ASCII
public bool Equals2(string str, bool checkLower)
{
if (_type != ValueHandleType.UTF8)
return GetString() == str;
if (_length != str.Length)
return false;
byte[] buffer = _bufferReader.Buffer;
for (int i = 0; i < _length; ++i)
{
DiagnosticUtility.DebugAssert(str[i] < 128, "");
byte ch = buffer[i + _offset];
if (ch == str[i])
continue;
if (checkLower && char.ToLowerInvariant((char)ch) == str[i])
continue;
return false;
}
return true;
}
public void Sign(XmlSigningNodeWriter writer)
{
switch (_type)
{
case ValueHandleType.Int8:
case ValueHandleType.Int16:
case ValueHandleType.Int32:
writer.WriteInt32Text(ToInt());
break;
case ValueHandleType.Int64:
writer.WriteInt64Text(GetInt64());
break;
case ValueHandleType.UInt64:
writer.WriteUInt64Text(GetUInt64());
break;
case ValueHandleType.Single:
writer.WriteFloatText(GetSingle());
break;
case ValueHandleType.Double:
writer.WriteDoubleText(GetDouble());
break;
case ValueHandleType.Decimal:
writer.WriteDecimalText(GetDecimal());
break;
case ValueHandleType.DateTime:
writer.WriteDateTimeText(ToDateTime());
break;
case ValueHandleType.Empty:
break;
case ValueHandleType.UTF8:
writer.WriteEscapedText(_bufferReader.Buffer, _offset, _length);
break;
case ValueHandleType.Base64:
writer.WriteBase64Text(_bufferReader.Buffer, 0, _bufferReader.Buffer, _offset, _length);
break;
case ValueHandleType.UniqueId:
writer.WriteUniqueIdText(ToUniqueId());
break;
case ValueHandleType.Guid:
writer.WriteGuidText(ToGuid());
break;
case ValueHandleType.TimeSpan:
writer.WriteTimeSpanText(ToTimeSpan());
break;
default:
writer.WriteEscapedText(GetString());
break;
}
}
public object[] ToList()
{
return _bufferReader.GetList(_offset, _length);
}
public object ToObject()
{
switch (_type)
{
case ValueHandleType.False:
case ValueHandleType.True:
return ToBoolean();
case ValueHandleType.Zero:
case ValueHandleType.One:
case ValueHandleType.Int8:
case ValueHandleType.Int16:
case ValueHandleType.Int32:
return ToInt();
case ValueHandleType.Int64:
return ToLong();
case ValueHandleType.UInt64:
return GetUInt64();
case ValueHandleType.Single:
return ToSingle();
case ValueHandleType.Double:
return ToDouble();
case ValueHandleType.Decimal:
return ToDecimal();
case ValueHandleType.DateTime:
return ToDateTime();
case ValueHandleType.Empty:
case ValueHandleType.UTF8:
case ValueHandleType.Unicode:
case ValueHandleType.EscapedUTF8:
case ValueHandleType.Dictionary:
case ValueHandleType.Char:
case ValueHandleType.ConstString:
return ToString();
case ValueHandleType.Base64:
return ToByteArray();
case ValueHandleType.List:
return ToList();
case ValueHandleType.UniqueId:
return ToUniqueId();
case ValueHandleType.Guid:
return ToGuid();
case ValueHandleType.TimeSpan:
return ToTimeSpan();
default:
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());
}
}
public bool TryReadBase64(byte[] buffer, int offset, int count, out int actual)
{
if (_type == ValueHandleType.Base64)
{
actual = Math.Min(_length, count);
GetBase64(buffer, offset, actual);
_offset += actual;
_length -= actual;
return true;
}
if (_type == ValueHandleType.UTF8 && count >= 3 && (_length % 4) == 0)
{
try
{
int charCount = Math.Min(count / 3 * 4, _length);
actual = Base64Encoding.GetBytes(_bufferReader.Buffer, _offset, charCount, buffer, offset);
_offset += charCount;
_length -= charCount;
return true;
}
catch (FormatException)
{
// Something unhappy with the characters, fall back to the hard way
}
}
actual = 0;
return false;
}
public bool TryReadChars(char[] chars, int offset, int count, out int actual)
{
DiagnosticUtility.DebugAssert(offset + count <= chars.Length, string.Format("offset '{0}' + count '{1}' MUST BE <= chars.Length '{2}'", offset, count, chars.Length));
if (_type == ValueHandleType.Unicode)
return TryReadUnicodeChars(chars, offset, count, out actual);
if (_type != ValueHandleType.UTF8)
{
actual = 0;
return false;
}
int charOffset = offset;
int charCount = count;
byte[] bytes = _bufferReader.Buffer;
int byteOffset = _offset;
int byteCount = _length;
bool insufficientSpaceInCharsArray = false;
var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
while (true)
{
while (charCount > 0 && byteCount > 0)
{
// fast path for codepoints U+0000 - U+007F
byte b = bytes[byteOffset];
if (b >= 0x80)
break;
chars[charOffset] = (char)b;
byteOffset++;
byteCount--;
charOffset++;
charCount--;
}
if (charCount == 0 || byteCount == 0 || insufficientSpaceInCharsArray)
break;
int actualByteCount;
int actualCharCount;
try
{
// If we're asking for more than are possibly available, or more than are truly available then we can return the entire thing
if (charCount >= encoding.GetMaxCharCount(byteCount) || charCount >= encoding.GetCharCount(bytes, byteOffset, byteCount))
{
actualCharCount = encoding.GetChars(bytes, byteOffset, byteCount, chars, charOffset);
actualByteCount = byteCount;
}
else
{
Decoder decoder = encoding.GetDecoder();
// Since x bytes can never generate more than x characters this is a safe estimate as to what will fit
actualByteCount = Math.Min(charCount, byteCount);
// We use a decoder so we don't error if we fall across a character boundary
actualCharCount = decoder.GetChars(bytes, byteOffset, actualByteCount, chars, charOffset);
// We might have gotten zero characters though if < 4 bytes were requested because
// codepoints from U+0000 - U+FFFF can be up to 3 bytes in UTF-8, and represented as ONE char
// codepoints from U+10000 - U+10FFFF (last Unicode codepoint representable in UTF-8) are represented by up to 4 bytes in UTF-8
// and represented as TWO chars (high+low surrogate)
// (e.g. 1 char requested, 1 char in the buffer represented in 3 bytes)
while (actualCharCount == 0)
{
// Note the by the time we arrive here, if actualByteCount == 3, the next decoder.GetChars() call will read the 4th byte
// if we don't bail out since the while loop will advance actualByteCount only after reading the byte.
if (actualByteCount >= 3 && charCount < 2)
{
// If we reach here, it means that we're:
// - trying to decode more than 3 bytes and,
// - there is only one char left of charCount where we're stuffing decoded characters.
// In this case, we need to back off since decoding > 3 bytes in UTF-8 means that we will get 2 16-bit chars
// (a high surrogate and a low surrogate) - the Decoder will attempt to provide both at once
// and an ArgumentException will be thrown complaining that there's not enough space in the output char array.
// actualByteCount = 0 when the while loop is broken out of; decoder goes out of scope so its state no longer matters
insufficientSpaceInCharsArray = true;
break;
}
else
{
DiagnosticUtility.DebugAssert(byteOffset + actualByteCount < bytes.Length,
string.Format("byteOffset {0} + actualByteCount {1} MUST BE < bytes.Length {2}", byteOffset, actualByteCount, bytes.Length));
// Request a few more bytes to get at least one character
actualCharCount = decoder.GetChars(bytes, byteOffset + actualByteCount, 1, chars, charOffset);
actualByteCount++;
}
}
// Now that we actually retrieved some characters, figure out how many bytes it actually was
actualByteCount = encoding.GetByteCount(chars, charOffset, actualCharCount);
}
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(bytes, byteOffset, byteCount, exception));
}
// Advance
byteOffset += actualByteCount;
byteCount -= actualByteCount;
charOffset += actualCharCount;
charCount -= actualCharCount;
}
_offset = byteOffset;
_length = byteCount;
actual = (count - charCount);
return true;
}
private bool TryReadUnicodeChars(char[] chars, int offset, int count, out int actual)
{
int charCount = Math.Min(count, _length / sizeof(char));
for (int i = 0; i < charCount; i++)
{
chars[offset + i] = (char)_bufferReader.GetInt16(_offset + i * sizeof(char));
}
_offset += charCount * sizeof(char);
_length -= charCount * sizeof(char);
actual = charCount;
return true;
}
public bool TryGetDictionaryString(out XmlDictionaryString value)
{
if (_type == ValueHandleType.Dictionary)
{
value = GetDictionaryString();
return true;
}
else
{
value = null;
return false;
}
}
public bool TryGetByteArrayLength(out int length)
{
if (_type == ValueHandleType.Base64)
{
length = _length;
return true;
}
length = 0;
return false;
}
private string GetCharsText()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.UTF8, "");
if (_length == 1 && _bufferReader.GetByte(_offset) == '1')
return "1";
return _bufferReader.GetString(_offset, _length);
}
private string GetUnicodeCharsText()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Unicode, "");
return _bufferReader.GetUnicodeString(_offset, _length);
}
private string GetEscapedCharsText()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.EscapedUTF8, "");
return _bufferReader.GetEscapedString(_offset, _length);
}
private string GetCharText()
{
int ch = GetChar();
if (ch > char.MaxValue)
{
SurrogateChar surrogate = new SurrogateChar(ch);
char[] chars = new char[2];
chars[0] = surrogate.HighChar;
chars[1] = surrogate.LowChar;
return new string(chars, 0, 2);
}
else
{
return ((char)ch).ToString();
}
}
private int GetChar()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Char, "");
return _offset;
}
private int GetInt8()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int8, "");
return _bufferReader.GetInt8(_offset);
}
private int GetInt16()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int16, "");
return _bufferReader.GetInt16(_offset);
}
private int GetInt32()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int32, "");
return _bufferReader.GetInt32(_offset);
}
private long GetInt64()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int64 || _type == ValueHandleType.TimeSpan || _type == ValueHandleType.DateTime, "");
return _bufferReader.GetInt64(_offset);
}
private ulong GetUInt64()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.UInt64, "");
return _bufferReader.GetUInt64(_offset);
}
private float GetSingle()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Single, "");
return _bufferReader.GetSingle(_offset);
}
private double GetDouble()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Double, "");
return _bufferReader.GetDouble(_offset);
}
private decimal GetDecimal()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Decimal, "");
return _bufferReader.GetDecimal(_offset);
}
private UniqueId GetUniqueId()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.UniqueId, "");
return _bufferReader.GetUniqueId(_offset);
}
private Guid GetGuid()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Guid, "");
return _bufferReader.GetGuid(_offset);
}
private void GetBase64(byte[] buffer, int offset, int count)
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Base64, "");
_bufferReader.GetBase64(_offset, buffer, offset, count);
}
private XmlDictionaryString GetDictionaryString()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Dictionary, "");
return _bufferReader.GetDictionaryString(_offset);
}
private string GetQNameDictionaryText()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.QName, "");
return string.Concat(PrefixHandle.GetString(PrefixHandle.GetAlphaPrefix(_length)), ":", _bufferReader.GetDictionaryString(_offset));
}
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Firestore.Admin.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedFirestoreAdminClientTest
{
[xunit::FactAttribute]
public void GetIndexRequestObject()
{
moq::Mock<FirestoreAdmin.FirestoreAdminClient> mockGrpcClient = new moq::Mock<FirestoreAdmin.FirestoreAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIndexRequest request = new GetIndexRequest
{
IndexName = IndexName.FromProjectDatabaseCollectionIndex("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[INDEX]"),
};
Index expectedResponse = new Index
{
IndexName = IndexName.FromProjectDatabaseCollectionIndex("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[INDEX]"),
QueryScope = Index.Types.QueryScope.Unspecified,
Fields =
{
new Index.Types.IndexField(),
},
State = Index.Types.State.Ready,
};
mockGrpcClient.Setup(x => x.GetIndex(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirestoreAdminClient client = new FirestoreAdminClientImpl(mockGrpcClient.Object, null);
Index response = client.GetIndex(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIndexRequestObjectAsync()
{
moq::Mock<FirestoreAdmin.FirestoreAdminClient> mockGrpcClient = new moq::Mock<FirestoreAdmin.FirestoreAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIndexRequest request = new GetIndexRequest
{
IndexName = IndexName.FromProjectDatabaseCollectionIndex("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[INDEX]"),
};
Index expectedResponse = new Index
{
IndexName = IndexName.FromProjectDatabaseCollectionIndex("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[INDEX]"),
QueryScope = Index.Types.QueryScope.Unspecified,
Fields =
{
new Index.Types.IndexField(),
},
State = Index.Types.State.Ready,
};
mockGrpcClient.Setup(x => x.GetIndexAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Index>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirestoreAdminClient client = new FirestoreAdminClientImpl(mockGrpcClient.Object, null);
Index responseCallSettings = await client.GetIndexAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Index responseCancellationToken = await client.GetIndexAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIndex()
{
moq::Mock<FirestoreAdmin.FirestoreAdminClient> mockGrpcClient = new moq::Mock<FirestoreAdmin.FirestoreAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIndexRequest request = new GetIndexRequest
{
IndexName = IndexName.FromProjectDatabaseCollectionIndex("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[INDEX]"),
};
Index expectedResponse = new Index
{
IndexName = IndexName.FromProjectDatabaseCollectionIndex("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[INDEX]"),
QueryScope = Index.Types.QueryScope.Unspecified,
Fields =
{
new Index.Types.IndexField(),
},
State = Index.Types.State.Ready,
};
mockGrpcClient.Setup(x => x.GetIndex(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirestoreAdminClient client = new FirestoreAdminClientImpl(mockGrpcClient.Object, null);
Index response = client.GetIndex(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIndexAsync()
{
moq::Mock<FirestoreAdmin.FirestoreAdminClient> mockGrpcClient = new moq::Mock<FirestoreAdmin.FirestoreAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIndexRequest request = new GetIndexRequest
{
IndexName = IndexName.FromProjectDatabaseCollectionIndex("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[INDEX]"),
};
Index expectedResponse = new Index
{
IndexName = IndexName.FromProjectDatabaseCollectionIndex("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[INDEX]"),
QueryScope = Index.Types.QueryScope.Unspecified,
Fields =
{
new Index.Types.IndexField(),
},
State = Index.Types.State.Ready,
};
mockGrpcClient.Setup(x => x.GetIndexAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Index>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirestoreAdminClient client = new FirestoreAdminClientImpl(mockGrpcClient.Object, null);
Index responseCallSettings = await client.GetIndexAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Index responseCancellationToken = await client.GetIndexAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIndexResourceNames()
{
moq::Mock<FirestoreAdmin.FirestoreAdminClient> mockGrpcClient = new moq::Mock<FirestoreAdmin.FirestoreAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIndexRequest request = new GetIndexRequest
{
IndexName = IndexName.FromProjectDatabaseCollectionIndex("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[INDEX]"),
};
Index expectedResponse = new Index
{
IndexName = IndexName.FromProjectDatabaseCollectionIndex("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[INDEX]"),
QueryScope = Index.Types.QueryScope.Unspecified,
Fields =
{
new Index.Types.IndexField(),
},
State = Index.Types.State.Ready,
};
mockGrpcClient.Setup(x => x.GetIndex(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirestoreAdminClient client = new FirestoreAdminClientImpl(mockGrpcClient.Object, null);
Index response = client.GetIndex(request.IndexName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIndexResourceNamesAsync()
{
moq::Mock<FirestoreAdmin.FirestoreAdminClient> mockGrpcClient = new moq::Mock<FirestoreAdmin.FirestoreAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIndexRequest request = new GetIndexRequest
{
IndexName = IndexName.FromProjectDatabaseCollectionIndex("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[INDEX]"),
};
Index expectedResponse = new Index
{
IndexName = IndexName.FromProjectDatabaseCollectionIndex("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[INDEX]"),
QueryScope = Index.Types.QueryScope.Unspecified,
Fields =
{
new Index.Types.IndexField(),
},
State = Index.Types.State.Ready,
};
mockGrpcClient.Setup(x => x.GetIndexAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Index>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirestoreAdminClient client = new FirestoreAdminClientImpl(mockGrpcClient.Object, null);
Index responseCallSettings = await client.GetIndexAsync(request.IndexName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Index responseCancellationToken = await client.GetIndexAsync(request.IndexName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteIndexRequestObject()
{
moq::Mock<FirestoreAdmin.FirestoreAdminClient> mockGrpcClient = new moq::Mock<FirestoreAdmin.FirestoreAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteIndexRequest request = new DeleteIndexRequest
{
IndexName = IndexName.FromProjectDatabaseCollectionIndex("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[INDEX]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteIndex(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirestoreAdminClient client = new FirestoreAdminClientImpl(mockGrpcClient.Object, null);
client.DeleteIndex(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteIndexRequestObjectAsync()
{
moq::Mock<FirestoreAdmin.FirestoreAdminClient> mockGrpcClient = new moq::Mock<FirestoreAdmin.FirestoreAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteIndexRequest request = new DeleteIndexRequest
{
IndexName = IndexName.FromProjectDatabaseCollectionIndex("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[INDEX]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteIndexAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirestoreAdminClient client = new FirestoreAdminClientImpl(mockGrpcClient.Object, null);
await client.DeleteIndexAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteIndexAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteIndex()
{
moq::Mock<FirestoreAdmin.FirestoreAdminClient> mockGrpcClient = new moq::Mock<FirestoreAdmin.FirestoreAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteIndexRequest request = new DeleteIndexRequest
{
IndexName = IndexName.FromProjectDatabaseCollectionIndex("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[INDEX]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteIndex(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirestoreAdminClient client = new FirestoreAdminClientImpl(mockGrpcClient.Object, null);
client.DeleteIndex(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteIndexAsync()
{
moq::Mock<FirestoreAdmin.FirestoreAdminClient> mockGrpcClient = new moq::Mock<FirestoreAdmin.FirestoreAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteIndexRequest request = new DeleteIndexRequest
{
IndexName = IndexName.FromProjectDatabaseCollectionIndex("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[INDEX]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteIndexAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirestoreAdminClient client = new FirestoreAdminClientImpl(mockGrpcClient.Object, null);
await client.DeleteIndexAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteIndexAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteIndexResourceNames()
{
moq::Mock<FirestoreAdmin.FirestoreAdminClient> mockGrpcClient = new moq::Mock<FirestoreAdmin.FirestoreAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteIndexRequest request = new DeleteIndexRequest
{
IndexName = IndexName.FromProjectDatabaseCollectionIndex("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[INDEX]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteIndex(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirestoreAdminClient client = new FirestoreAdminClientImpl(mockGrpcClient.Object, null);
client.DeleteIndex(request.IndexName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteIndexResourceNamesAsync()
{
moq::Mock<FirestoreAdmin.FirestoreAdminClient> mockGrpcClient = new moq::Mock<FirestoreAdmin.FirestoreAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteIndexRequest request = new DeleteIndexRequest
{
IndexName = IndexName.FromProjectDatabaseCollectionIndex("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[INDEX]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteIndexAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirestoreAdminClient client = new FirestoreAdminClientImpl(mockGrpcClient.Object, null);
await client.DeleteIndexAsync(request.IndexName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteIndexAsync(request.IndexName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetFieldRequestObject()
{
moq::Mock<FirestoreAdmin.FirestoreAdminClient> mockGrpcClient = new moq::Mock<FirestoreAdmin.FirestoreAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFieldRequest request = new GetFieldRequest
{
FieldName = FieldName.FromProjectDatabaseCollectionField("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[FIELD]"),
};
Field expectedResponse = new Field
{
FieldName = FieldName.FromProjectDatabaseCollectionField("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[FIELD]"),
IndexConfig = new Field.Types.IndexConfig(),
};
mockGrpcClient.Setup(x => x.GetField(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirestoreAdminClient client = new FirestoreAdminClientImpl(mockGrpcClient.Object, null);
Field response = client.GetField(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetFieldRequestObjectAsync()
{
moq::Mock<FirestoreAdmin.FirestoreAdminClient> mockGrpcClient = new moq::Mock<FirestoreAdmin.FirestoreAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFieldRequest request = new GetFieldRequest
{
FieldName = FieldName.FromProjectDatabaseCollectionField("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[FIELD]"),
};
Field expectedResponse = new Field
{
FieldName = FieldName.FromProjectDatabaseCollectionField("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[FIELD]"),
IndexConfig = new Field.Types.IndexConfig(),
};
mockGrpcClient.Setup(x => x.GetFieldAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Field>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirestoreAdminClient client = new FirestoreAdminClientImpl(mockGrpcClient.Object, null);
Field responseCallSettings = await client.GetFieldAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Field responseCancellationToken = await client.GetFieldAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetField()
{
moq::Mock<FirestoreAdmin.FirestoreAdminClient> mockGrpcClient = new moq::Mock<FirestoreAdmin.FirestoreAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFieldRequest request = new GetFieldRequest
{
FieldName = FieldName.FromProjectDatabaseCollectionField("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[FIELD]"),
};
Field expectedResponse = new Field
{
FieldName = FieldName.FromProjectDatabaseCollectionField("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[FIELD]"),
IndexConfig = new Field.Types.IndexConfig(),
};
mockGrpcClient.Setup(x => x.GetField(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirestoreAdminClient client = new FirestoreAdminClientImpl(mockGrpcClient.Object, null);
Field response = client.GetField(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetFieldAsync()
{
moq::Mock<FirestoreAdmin.FirestoreAdminClient> mockGrpcClient = new moq::Mock<FirestoreAdmin.FirestoreAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFieldRequest request = new GetFieldRequest
{
FieldName = FieldName.FromProjectDatabaseCollectionField("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[FIELD]"),
};
Field expectedResponse = new Field
{
FieldName = FieldName.FromProjectDatabaseCollectionField("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[FIELD]"),
IndexConfig = new Field.Types.IndexConfig(),
};
mockGrpcClient.Setup(x => x.GetFieldAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Field>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirestoreAdminClient client = new FirestoreAdminClientImpl(mockGrpcClient.Object, null);
Field responseCallSettings = await client.GetFieldAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Field responseCancellationToken = await client.GetFieldAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetFieldResourceNames()
{
moq::Mock<FirestoreAdmin.FirestoreAdminClient> mockGrpcClient = new moq::Mock<FirestoreAdmin.FirestoreAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFieldRequest request = new GetFieldRequest
{
FieldName = FieldName.FromProjectDatabaseCollectionField("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[FIELD]"),
};
Field expectedResponse = new Field
{
FieldName = FieldName.FromProjectDatabaseCollectionField("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[FIELD]"),
IndexConfig = new Field.Types.IndexConfig(),
};
mockGrpcClient.Setup(x => x.GetField(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FirestoreAdminClient client = new FirestoreAdminClientImpl(mockGrpcClient.Object, null);
Field response = client.GetField(request.FieldName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetFieldResourceNamesAsync()
{
moq::Mock<FirestoreAdmin.FirestoreAdminClient> mockGrpcClient = new moq::Mock<FirestoreAdmin.FirestoreAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFieldRequest request = new GetFieldRequest
{
FieldName = FieldName.FromProjectDatabaseCollectionField("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[FIELD]"),
};
Field expectedResponse = new Field
{
FieldName = FieldName.FromProjectDatabaseCollectionField("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[FIELD]"),
IndexConfig = new Field.Types.IndexConfig(),
};
mockGrpcClient.Setup(x => x.GetFieldAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Field>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FirestoreAdminClient client = new FirestoreAdminClientImpl(mockGrpcClient.Object, null);
Field responseCallSettings = await client.GetFieldAsync(request.FieldName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Field responseCancellationToken = await client.GetFieldAsync(request.FieldName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
namespace System.Net.Sockets
{
public partial class SocketAsyncEventArgs : EventArgs, IDisposable
{
private int _acceptedFileDescriptor;
private int _socketAddressSize;
private SocketFlags _receivedFlags;
internal int? SendPacketsDescriptorCount { get { return null; } }
private void InitializeInternals()
{
// No-op for *nix.
}
private void FreeInternals(bool calledFromFinalizer)
{
// No-op for *nix.
}
private void SetupSingleBuffer()
{
// No-op for *nix.
}
private void SetupMultipleBuffers()
{
// No-op for *nix.
}
private void SetupSendPacketsElements()
{
// No-op for *nix.
}
private void InnerComplete()
{
// No-op for *nix.
}
private void InnerStartOperationAccept(bool userSuppliedBuffer)
{
_acceptedFileDescriptor = -1;
}
private void AcceptCompletionCallback(int acceptedFileDescriptor, byte[] socketAddress, int socketAddressSize, SocketError socketError)
{
// TODO: receive bytes on socket if requested
_acceptedFileDescriptor = acceptedFileDescriptor;
Debug.Assert(socketAddress == null || socketAddress == _acceptBuffer);
_acceptAddressBufferCount = socketAddressSize;
CompletionCallback(0, socketError);
}
internal unsafe SocketError DoOperationAccept(Socket socket, SafeCloseSocket handle, SafeCloseSocket acceptHandle, out int bytesTransferred)
{
Debug.Assert(acceptHandle == null);
bytesTransferred = 0;
return handle.AsyncContext.AcceptAsync(_buffer ?? _acceptBuffer, _acceptAddressBufferCount / 2, AcceptCompletionCallback);
}
private void InnerStartOperationConnect()
{
// No-op for *nix.
}
private void ConnectCompletionCallback(SocketError socketError)
{
CompletionCallback(0, socketError);
}
internal unsafe SocketError DoOperationConnect(Socket socket, SafeCloseSocket handle, out int bytesTransferred)
{
bytesTransferred = 0;
return handle.AsyncContext.ConnectAsync(_socketAddress.Buffer, _socketAddress.Size, ConnectCompletionCallback);
}
private void InnerStartOperationDisconnect()
{
throw new PlatformNotSupportedException();
}
internal unsafe SocketError DoOperationDisconnect(Socket socket, SafeCloseSocket handle)
{
throw new PlatformNotSupportedException();
}
private void TransferCompletionCallback(int bytesTransferred, byte[] socketAddress, int socketAddressSize, int receivedFlags, SocketError socketError)
{
Debug.Assert(socketAddress == null || socketAddress == _socketAddress.Buffer);
_socketAddressSize = socketAddressSize;
_receivedFlags = SocketPal.GetSocketFlags(receivedFlags);
CompletionCallback(bytesTransferred, socketError);
}
private void InnerStartOperationReceive()
{
_receivedFlags = System.Net.Sockets.SocketFlags.None;
_socketAddressSize = 0;
}
internal unsafe SocketError DoOperationReceive(SafeCloseSocket handle, out SocketFlags flags, out int bytesTransferred)
{
int platformFlags = SocketPal.GetPlatformSocketFlags(_socketFlags);
SocketError errorCode;
if (_buffer != null)
{
errorCode = handle.AsyncContext.ReceiveAsync(_buffer, _offset, _count, platformFlags, TransferCompletionCallback);
}
else
{
errorCode = handle.AsyncContext.ReceiveAsync(_bufferList, platformFlags, TransferCompletionCallback);
}
flags = _socketFlags;
bytesTransferred = 0;
return errorCode;
}
private void InnerStartOperationReceiveFrom()
{
_receivedFlags = System.Net.Sockets.SocketFlags.None;
_socketAddressSize = 0;
}
internal unsafe SocketError DoOperationReceiveFrom(SafeCloseSocket handle, out SocketFlags flags, out int bytesTransferred)
{
int platformFlags = SocketPal.GetPlatformSocketFlags(_socketFlags);
SocketError errorCode;
if (_buffer != null)
{
errorCode = handle.AsyncContext.ReceiveFromAsync(_buffer, _offset, _count, platformFlags, _socketAddress.Buffer, _socketAddress.Size, TransferCompletionCallback);
}
else
{
errorCode = handle.AsyncContext.ReceiveFromAsync(_bufferList, platformFlags, _socketAddress.Buffer, _socketAddress.Size, TransferCompletionCallback);
}
flags = _socketFlags;
bytesTransferred = 0;
return errorCode;
}
private void InnerStartOperationReceiveMessageFrom()
{
_receiveMessageFromPacketInfo = default(IPPacketInformation);
_receivedFlags = System.Net.Sockets.SocketFlags.None;
_socketAddressSize = 0;
}
private void ReceiveMessageFromCompletionCallback(int bytesTransferred, byte[] socketAddress, int socketAddressSize, int receivedFlags, IPPacketInformation ipPacketInformation, SocketError errorCode)
{
Debug.Assert(_socketAddress != null);
Debug.Assert(socketAddress == null || _socketAddress.Buffer == socketAddress);
_socketAddressSize = socketAddressSize;
_receivedFlags = SocketPal.GetSocketFlags(receivedFlags);
_receiveMessageFromPacketInfo = ipPacketInformation;
CompletionCallback(bytesTransferred, errorCode);
}
internal unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeCloseSocket handle, out int bytesTransferred)
{
int platformFlags = SocketPal.GetPlatformSocketFlags(_socketFlags);
bool isIPv4, isIPv6;
Socket.GetIPProtocolInformation(socket.AddressFamily, _socketAddress, out isIPv4, out isIPv6);
bytesTransferred = 0;
return handle.AsyncContext.ReceiveMessageFromAsync(_buffer, _offset, _count, platformFlags, _socketAddress.Buffer, _socketAddress.Size, isIPv4, isIPv6, ReceiveMessageFromCompletionCallback);
}
private void InnerStartOperationSend()
{
_receivedFlags = System.Net.Sockets.SocketFlags.None;
_socketAddressSize = 0;
}
internal unsafe SocketError DoOperationSend(SafeCloseSocket handle, out int bytesTransferred)
{
int platformFlags = SocketPal.GetPlatformSocketFlags(_socketFlags);
SocketError errorCode;
if (_buffer != null)
{
errorCode = handle.AsyncContext.SendAsync(_buffer, _offset, _count, platformFlags, TransferCompletionCallback);
}
else
{
errorCode = handle.AsyncContext.SendAsync(new BufferList(_bufferList), platformFlags, TransferCompletionCallback);
}
bytesTransferred = 0;
return errorCode;
}
private void InnerStartOperationSendPackets()
{
throw new PlatformNotSupportedException();
}
internal SocketError DoOperationSendPackets(Socket socket, SafeCloseSocket handle)
{
throw new PlatformNotSupportedException();
}
private void InnerStartOperationSendTo()
{
_receivedFlags = System.Net.Sockets.SocketFlags.None;
_socketAddressSize = 0;
}
internal SocketError DoOperationSendTo(SafeCloseSocket handle, out int bytesTransferred)
{
int platformFlags = SocketPal.GetPlatformSocketFlags(_socketFlags);
SocketError errorCode;
if (_buffer != null)
{
errorCode = handle.AsyncContext.SendToAsync(_buffer, _offset, _count, platformFlags, _socketAddress.Buffer, _socketAddress.Size, TransferCompletionCallback);
}
else
{
errorCode = handle.AsyncContext.SendToAsync(new BufferList(_bufferList), platformFlags, _socketAddress.Buffer, _socketAddress.Size, TransferCompletionCallback);
}
bytesTransferred = 0;
return errorCode;
}
internal void LogBuffer(int size)
{
// TODO: implement?
}
internal void LogSendPacketsBuffers(int size)
{
throw new PlatformNotSupportedException();
}
private SocketError FinishOperationAccept(Internals.SocketAddress remoteSocketAddress)
{
System.Buffer.BlockCopy(_acceptBuffer, 0, remoteSocketAddress.Buffer, 0, _acceptAddressBufferCount);
_acceptSocket = _currentSocket.CreateAcceptSocket(
SafeCloseSocket.CreateSocket(_acceptedFileDescriptor),
_currentSocket._rightEndPoint.Create(remoteSocketAddress));
return SocketError.Success;
}
private SocketError FinishOperationConnect()
{
// No-op for *nix.
return SocketError.Success;
}
private unsafe int GetSocketAddressSize()
{
return _socketAddressSize;
}
private unsafe void FinishOperationReceiveMessageFrom()
{
// No-op for *nix.
}
private void FinishOperationSendPackets()
{
throw new PlatformNotSupportedException();
}
private void CompletionCallback(int bytesTransferred, SocketError socketError)
{
// TODO: plumb SocketFlags through TransferOperation
if (socketError == SocketError.Success)
{
FinishOperationSuccess(socketError, bytesTransferred, _receivedFlags);
}
else
{
if (_currentSocket.CleanedUp)
{
socketError = SocketError.OperationAborted;
}
FinishOperationAsyncFailure(socketError, bytesTransferred, _receivedFlags);
}
}
}
}
| |
/*
* Copyright 2011 John Sample
*
* 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.IO;
using System.Net;
using System.Net.Sockets;
using log4net;
namespace BitCoinSharp.Discovery
{
/// <summary>
/// IrcDiscovery provides a way to find network peers by joining a pre-agreed rendevouz point on the LFnet IRC network.
/// </summary>
public class IrcDiscovery : IPeerDiscovery
{
private static readonly ILog _log = LogManager.GetLogger(typeof (IrcDiscovery));
private readonly string _channel;
private readonly int _port;
private readonly string _server;
/// <summary>
/// Finds a list of peers by connecting to an IRC network, joining a channel, decoding the nicks and then
/// disconnecting.
/// </summary>
/// <param name="channel">The IRC channel to join, either "#bitcoin" or "#bitcoinTEST" for the production and test networks respectively.</param>
/// <param name="server">Name or textual IP address of the IRC server to join.</param>
/// <param name="port">The port of the IRC server to join.</param>
public IrcDiscovery(string channel, string server = "irc.lfnet.org", int port = 6667)
{
_channel = channel;
_server = server;
_port = port;
}
protected virtual void OnIrcSend(string message)
{
if (Send != null)
{
Send(this, new IrcDiscoveryEventArgs(message));
}
}
protected virtual void OnIrcReceive(string message)
{
if (Receive != null)
{
Receive(this, new IrcDiscoveryEventArgs(message));
}
}
public event EventHandler<IrcDiscoveryEventArgs> Send;
public event EventHandler<IrcDiscoveryEventArgs> Receive;
/// <summary>
/// Returns a list of peers that were found in the IRC channel. Note that just because a peer appears in the list
/// does not mean it is accepting connections.
/// </summary>
/// <exception cref="PeerDiscoveryException"/>
public IEnumerable<EndPoint> GetPeers()
{
var addresses = new List<EndPoint>();
using (var connection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
try
{
connection.Connect(_server, _port);
using (var writer = new StreamWriter(new NetworkStream(connection, FileAccess.Write)))
using (var reader = new StreamReader(new NetworkStream(connection, FileAccess.Read)))
{
// Generate a random nick for the connection. This is chosen to be clearly identifiable as coming from
// BitCoinSharp but not match the standard nick format, so full peers don't try and connect to us.
var nickRnd = string.Format("bcs{0}", new Random().Next(int.MaxValue));
var command = "NICK " + nickRnd;
LogAndSend(writer, command);
// USER <user> <mode> <unused> <realname> (RFC 2812)
command = "USER " + nickRnd + " 8 *: " + nickRnd;
LogAndSend(writer, command);
writer.Flush();
// Wait to be logged in. Worst case we end up blocked until the server PING/PONGs us out.
string currLine;
while ((currLine = reader.ReadLine()) != null)
{
OnIrcReceive(currLine);
// 004 tells us we are connected
// TODO: add common exception conditions (nick already in use, etc..)
// these aren't bullet proof checks but they should do for our purposes.
if (CheckLineStatus("004", currLine))
{
break;
}
}
// Join the channel.
LogAndSend(writer, "JOIN " + _channel);
// List users in channel.
LogAndSend(writer, "NAMES " + _channel);
writer.Flush();
// A list of the users should be returned. Look for code 353 and parse until code 366.
while ((currLine = reader.ReadLine()) != null)
{
OnIrcReceive(currLine);
if (CheckLineStatus("353", currLine))
{
// Line contains users. List follows ":" (second ":" if line starts with ":")
var subIndex = 0;
if (currLine.StartsWith(":"))
{
subIndex = 1;
}
var spacedList = currLine.Substring(currLine.IndexOf(":", subIndex));
addresses.AddRange(ParseUserList(spacedList.Substring(1).Split(' ')));
}
else if (CheckLineStatus("366", currLine))
{
// End of user list.
break;
}
}
// Quit the server.
LogAndSend(writer, "PART " + _channel);
LogAndSend(writer, "QUIT");
writer.Flush();
}
}
catch (Exception e)
{
// Throw the original error wrapped in the discovery error.
throw new PeerDiscoveryException(e.Message, e);
}
}
return addresses.ToArray();
}
private void LogAndSend(TextWriter writer, string command)
{
OnIrcSend(command);
writer.WriteLine(command);
}
// Visible for testing.
internal static IList<EndPoint> ParseUserList(IEnumerable<string> userNames)
{
var addresses = new List<EndPoint>();
foreach (var user in userNames)
{
// All BitCoin peers start their nicknames with a 'u' character.
if (!user.StartsWith("u"))
{
continue;
}
// After "u" is stripped from the beginning array contains unsigned chars of:
// 4 byte IP address, 2 byte port, 4 byte hash check (ipv4)
byte[] addressBytes;
try
{
// Strip off the "u" before decoding. Note that it's possible for anyone to join these IRC channels and
// so simply beginning with "u" does not imply this is a valid BitCoin encoded address.
//
// decodeChecked removes the checksum from the returned bytes.
addressBytes = Base58.DecodeChecked(user.Substring(1));
}
catch (AddressFormatException)
{
_log.WarnFormat("IRC nick does not parse as base58: {0}", user);
continue;
}
// TODO: Handle IPv6 if one day the official client uses it. It may be that IRC discovery never does.
if (addressBytes.Length != 6)
{
continue;
}
var ipBytes = new[] {addressBytes[0], addressBytes[1], addressBytes[2], addressBytes[3]};
var port = Utils.ReadUint16Be(addressBytes, 4);
var ip = new IPAddress(ipBytes);
var address = new IPEndPoint(ip, port);
addresses.Add(address);
}
return addresses;
}
private static bool CheckLineStatus(string statusCode, string response)
{
// Lines can either start with the status code or an optional :<source>
//
// All the testing shows the servers for this purpose use :<source> but plan for either.
// TODO: Consider whether regex would be worth it here.
if (response.StartsWith(":"))
{
// Look for first space.
var startIndex = response.IndexOf(" ") + 1;
// Next part should be status code.
return response.IndexOf(statusCode + " ", startIndex) == startIndex;
}
return response.StartsWith(statusCode + " ");
}
}
public class IrcDiscoveryEventArgs : EventArgs
{
public string Message { get; private set; }
public IrcDiscoveryEventArgs(string message)
{
Message = message;
}
}
}
| |
using EPiServer.Commerce.Order;
using EPiServer.Commerce.Order.Internal;
using EPiServer.Security;
using EPiServer.ServiceLocation;
using Mediachase.Commerce.Catalog;
using Mediachase.Commerce.Catalog.Dto;
using Mediachase.Commerce.Catalog.Managers;
using Mediachase.Commerce.Catalog.Objects;
using Mediachase.Commerce.Customers;
using Mediachase.Commerce.Customers.Profile;
using Mediachase.Commerce.Inventory;
using Mediachase.Commerce.Marketing;
using Mediachase.Commerce.Marketing.Dto;
using Mediachase.Commerce.Marketing.Managers;
using Mediachase.Commerce.Marketing.Objects;
using Mediachase.Commerce.Orders;
using Mediachase.Commerce.Security;
using Mediachase.Commerce.WorkflowCompatibility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
namespace Mediachase.Commerce.Workflow
{
/// <summary>
/// This is an activity that calculates and applies discounts to a particular order group.
/// This can be used out of the box or as a basis for a different promotion engine.
/// </summary>
public class CalculateDiscountsActivity : OrderGroupActivityBase
{
private Currency _currency;
/// <summary>
/// Executes the specified execution context.
/// </summary>
/// <param name="executionContext">The execution context.</param>
/// <returns></returns>
protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
{
// Validate the properties at runtime
ValidateRuntime();
// Initialize Marketing Context
InitMarketingContext();
// Calculate order discounts
CalculateDiscounts();
// Return the closed status indicating that this activity is complete.
return ActivityExecutionStatus.Closed;
}
/// <summary>
/// Inits the marketing context.
/// </summary>
private void InitMarketingContext()
{
OrderGroup group = OrderGroup;
_currency = group.BillingCurrency;
SetContext(MarketingContext.ContextConstants.ShoppingCart, group);
// Set customer segment context
var principal = PrincipalInfo.CurrentPrincipal;
if (principal != null)
{
CustomerProfileWrapper profile = GetCurrentUserProfile();
if (profile != null)
{
SetContext(MarketingContext.ContextConstants.CustomerProfile, profile);
var contactId = principal.GetContactId();
var customerContact = CustomerContext.Current.GetContactById(contactId);
if (contactId != group.CustomerId)
{
customerContact = CustomerContext.Current.GetContactById(group.CustomerId);
}
if (customerContact != null)
{
SetContext(MarketingContext.ContextConstants.CustomerContact, customerContact);
Guid accountId = (Guid)customerContact.PrimaryKeyId;
Guid organizationId = Guid.Empty;
if (customerContact.ContactOrganization != null)
{
organizationId = (Guid)customerContact.ContactOrganization.PrimaryKeyId;
}
SetContext(MarketingContext.ContextConstants.CustomerSegments, MarketingContext.Current.GetCustomerSegments(accountId, organizationId));
}
}
}
// Set customer promotion history context
SetContext(MarketingContext.ContextConstants.CustomerId, OrderGroup.CustomerId);
// Now load current order usage dto, which will help us determine the usage limits
// Load existing usage Dto for the current order
PromotionUsageDto usageDto = PromotionManager.GetPromotionUsageDto(0, Guid.Empty, group.OrderGroupId);
SetContext(MarketingContext.ContextConstants.PromotionUsage, usageDto);
}
private CustomerProfileWrapper GetCurrentUserProfile()
{
// This method has a strong dependency on ProfileBase and may not be unit tested.
var httpProfile = HttpContext.Current != null ? HttpContext.Current.Profile : null;
var profile = httpProfile == null ? null : new CustomerProfileWrapper(httpProfile);
return profile;
}
/// <summary>
/// Sets the context.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="val">The val.</param>
private void SetContext(string key, object val)
{
if (!MarketingContext.Current.MarketingProfileContext.ContainsKey(key))
MarketingContext.Current.MarketingProfileContext.Add(key, val);
else
MarketingContext.Current.MarketingProfileContext[key] = val;
}
private void UpdateManualDiscounts(OrderGroup orderGroup)
{
var lineItems = orderGroup.OrderForms.SelectMany(x => x.LineItems);
foreach (LineItem lineItem in lineItems)
{
var lineItemManualDiscountAmount = 0m;
foreach (var discount in lineItem.Discounts)
{
if (discount.DiscountName.StartsWith("@"))
{
var previousDiscountAmount = discount.DiscountValue;
if (discount.DiscountName.EndsWith(":PercentageBased", StringComparison.OrdinalIgnoreCase))
{
discount.DiscountValue = discount.DiscountAmount * 0.01m * lineItem.PlacedPrice * lineItem.Quantity;
}
else
{
discount.DiscountValue = discount.DiscountAmount * lineItem.Quantity;
}
lineItemManualDiscountAmount += discount.DiscountValue - previousDiscountAmount;
}
}
var extendedPrice = lineItem.GetExtendedPrice(orderGroup.BillingCurrency).Amount;
lineItemManualDiscountAmount = Math.Min(extendedPrice, lineItemManualDiscountAmount);
lineItem.TrySetDiscountValue(x => x.EntryAmount, lineItem.TryGetDiscountValue(x => x.EntryAmount) + lineItemManualDiscountAmount);
}
}
/// <summary>
/// Calculates the discounts.
/// </summary>
private void CalculateDiscounts()
{
// Update manual discount amount
UpdateManualDiscounts(OrderGroup);
PromotionDto promotionDto = PromotionManager.GetPromotionDto(FrameworkContext.Current.CurrentDateTime);
if (promotionDto.Promotion.Count == 0)
return;
// Get current context
Dictionary<string, object> context = MarketingContext.Current.MarketingProfileContext;
// Parameter that tells if we need to use cached values for promotions or not
bool useCache = false;
// Constract the filter, ignore conditions for now
PromotionFilter filter = new PromotionFilter();
filter.IgnoreConditions = false;
filter.IgnorePolicy = false;
filter.IgnoreSegments = false;
filter.IncludeCoupons = false;
// Get property
OrderGroup order = OrderGroup;
decimal runningTotal = 0;
foreach (OrderForm orderForm in order.OrderForms)
{
runningTotal +=
orderForm.LineItems.Where(c => !IsGiftLineItem(c)).Sum(x => x.Quantity * x.PlacedPrice);
}
// Create Promotion Context
PromotionEntriesSet sourceSet = null;
// Reuse the same context so we can track exclusivity properly
PromotionContext promoContext = new PromotionContext(context, new PromotionEntriesSet(), new PromotionEntriesSet());
promoContext.PromotionResult.RunningTotal = runningTotal;
#region Determine Line item level discounts
int totalNumberOfItems = 0;
// Process line item discounts first
foreach (OrderForm form in order.OrderForms)
{
foreach (OrderFormDiscount discount in form.Discounts)
{
if (!discount.DiscountName.StartsWith("@")/* && discount.DiscountId == -1*/) // ignore custom entries
discount.Delete();
}
// Create source from current form
sourceSet = CreateSetFromOrderForm(form);
// Build dictionary to keep track of entry discount limit
Dictionary<PromotionDto.PromotionRow, decimal?> entryDiscountApplicationCount = new Dictionary<PromotionDto.PromotionRow, decimal?>();
foreach (PromotionDto.PromotionRow promotion in promotionDto.Promotion)
{
if (!promotion.IsMaxEntryDiscountQuantityNull())
{
entryDiscountApplicationCount.Add(promotion, promotion.MaxEntryDiscountQuantity);
}
}
// Now cycle through each line item one by one
IOrderedEnumerable<LineItem> highPlacedPriceFirst = form.LineItems.ToArray().OrderByDescending(x => x.PlacedPrice);
int lineItemCount = highPlacedPriceFirst.Count();
List<PromotionEntriesSet> entriesSetCollection = new List<PromotionEntriesSet>();
foreach (LineItem lineItem in highPlacedPriceFirst)
{
// First remove items
foreach (LineItemDiscount discount in lineItem.Discounts)
{
if (!discount.DiscountName.StartsWith("@")/* && discount.DiscountId == -1*/) // ignore custom entries
discount.Delete();
}
//Exclude gift lineItems from evaluation discounts process
if (IsGiftLineItem(lineItem))
{
continue;
}
totalNumberOfItems++;
// Target only entry promotions
PromotionEntriesSet targetSet = new PromotionEntriesSet();
targetSet.OrderFormId = form.OrderFormId.ToString();
//ET [16.06.2009] If order contains two item with same code, in target hit only first
//targetSet.Entries.Add(sourceSet.FindEntryByCode(lineItem.CatalogEntryId));
targetSet.Entries.Add(CreatePromotionEntryFromLineItem(lineItem));
entriesSetCollection.Add(targetSet);
}
promoContext.TargetGroup = PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Entry).Key;
// Evaluate conditions
MarketingContext.Current.EvaluatePromotions(useCache, promoContext, filter, entryDiscountApplicationCount, sourceSet, entriesSetCollection, null);
// from now on use cache
useCache = true;
}
#endregion
#region Determine Order level discounts
List<PromotionEntriesSet> orderEntriesSetCollection = new List<PromotionEntriesSet>();
foreach (OrderForm form in order.OrderForms)
{
// Now process global order discounts
// Now start processing it
// Create source from current form
sourceSet = CreateSetFromOrderForm(form);
orderEntriesSetCollection.Add(sourceSet);
}
promoContext.TargetGroup = PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Order).Key;
// Evaluate conditions
MarketingContext.Current.EvaluatePromotions(useCache, promoContext, filter, null, orderEntriesSetCollection, false);
//Removing now not aplyied Gift discounts from Order
RemoveGiftPromotionFromOrder(order, promoContext);
#endregion
#region Determine Shipping Discounts
// add shipping fee to RunningTotal after calculating item and order level discounts, in order to apply shipping discounts.
foreach (OrderForm orderForm in order.OrderForms)
{
foreach (Shipment shipment in orderForm.Shipments)
{
promoContext.PromotionResult.RunningTotal += shipment.ShippingSubTotal;
}
}
foreach (OrderForm form in order.OrderForms)
{
List<PromotionEntriesSet> shipmentEntriesSetCollection = new List<PromotionEntriesSet>();
foreach (Shipment shipment in form.Shipments)
{
// Remove old discounts if any
foreach (ShipmentDiscount discount in shipment.Discounts)
{
if (!discount.DiscountName.StartsWith("@")/* && discount.DiscountId == -1*/) // ignore custom entries
discount.Delete();
}
// Create content for current shipment
/*
sourceSet = CreateSetFromOrderForm(form);
promoContext.SourceEntriesSet.Entries = sourceSet.Entries;
* */
PromotionEntriesSet targetSet = CreateSetFromShipment(shipment);
shipmentEntriesSetCollection.Add(targetSet);
}
promoContext.TargetGroup = PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Shipping).Key;
// Evaluate promotions
MarketingContext.Current.EvaluatePromotions(useCache, promoContext, filter, null, shipmentEntriesSetCollection, false);
}
#endregion
#region Start Applying Discounts
foreach (PromotionItemRecord itemRecord in promoContext.PromotionResult.PromotionRecords)
{
if (itemRecord.Status != PromotionItemRecordStatus.Commited)
continue;
// Pre process item record
PreProcessItemRecord(order, itemRecord);
// Applies discount and adjusts the running total
if (itemRecord.AffectedEntriesSet.Entries.Count > 0)
{
var discountAmount = ApplyItemDiscount(order, itemRecord, runningTotal);
if (!(itemRecord.PromotionReward is GiftPromotionReward))
{
runningTotal -= discountAmount;
}
}
}
#endregion
#region True up order level discounts (from Mark's fix for Teleflora)
decimal orderLevelAmount = 0;
decimal lineItemOrderLevelTotal = 0;
foreach (OrderForm form in order.OrderForms)
{
orderLevelAmount += form.Discounts.Cast<OrderFormDiscount>().Where(y => !y.DiscountName.StartsWith("@")).Sum(x => x.DiscountValue);
lineItemOrderLevelTotal += form.LineItems.ToArray().Sum(x => x.OrderLevelDiscountAmount);
if (orderLevelAmount != lineItemOrderLevelTotal)
{
form.LineItems[0].OrderLevelDiscountAmount += orderLevelAmount - lineItemOrderLevelTotal;
}
}
#endregion
}
/// <summary>
/// Pre processes item record adding additional LineItems if needed.
/// </summary>
/// <param name="order">The order.</param>
/// <param name="record">The record.</param>
private void PreProcessItemRecord(OrderGroup order, PromotionItemRecord record)
{
// We do special logic for the gift promotion reward
if (record.PromotionReward is GiftPromotionReward)
{
// Check if item already in the cart, if not add
if (((GiftPromotionReward)record.PromotionReward).AddStrategy == GiftPromotionReward.Strategy.AddWhenNeeded)
{
// We assume that all affected entries are the gifts that need to be added to the cart
foreach (PromotionEntry entry in record.AffectedEntriesSet.Entries)
{
LineItem giftLineItem = FindGiftLineItemInOrder(order, entry.CatalogEntryCode, record);
if (!IsOrderHaveSpecifiedGiftPromotion(order, record))
{
// Didn't find, add it
if (giftLineItem == null)
{
// we should some kind of delegate or common implementation here so we can use the same function in both discount and front end
CatalogEntryResponseGroup responseGroup = new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.Variations);
Entry catEntry = CatalogContext.Current.GetCatalogEntry(entry.CatalogEntryCode, responseGroup);
giftLineItem = AddNewGiftLineItemToOrder(order, catEntry, entry.Quantity);
AddGiftItemToAShipment(giftLineItem, giftLineItem.Parent.LineItems.Count - 1);
CatalogEntryDto entryDto = CatalogContext.Current.GetCatalogEntryDto(giftLineItem.Code, responseGroup);
CatalogEntryDto.CatalogEntryRow entryRow = entryDto.CatalogEntry[0];
Money? price = GetItemPrice(entryRow, giftLineItem, CustomerContext.Current.CurrentContact);
giftLineItem.ListPrice = price.HasValue ? price.Value.Amount : 0m;
giftLineItem.PlacedPrice = giftLineItem.ListPrice;
// populate inventory information for giftLineItem
IWarehouseInventory aggregateInventory = ServiceLocator.Current.GetInstance<IWarehouseInventoryService>().GetTotal(new CatalogKey(entryRow));
PopulateInventoryInfo(aggregateInventory, giftLineItem);
}
else
{
giftLineItem.Quantity = Math.Max(entry.Quantity, giftLineItem.Quantity);
var index = giftLineItem.Parent.LineItems.IndexOf(giftLineItem);
if (!giftLineItem.Parent.Shipments.SelectMany(x => x.LineItemIndexes).Contains(index.ToString()))
{
AddGiftItemToAShipment(giftLineItem, index);
}
}
}
else
{
entry.Quantity = giftLineItem != null ? Math.Min(entry.Quantity, giftLineItem.Quantity) : entry.Quantity;
}
entry.Owner = giftLineItem;
entry.CostPerEntry = giftLineItem != null ? giftLineItem.ListPrice : 0m;
}
}
}
}
private void AddGiftItemToAShipment(LineItem giftLineItem, int lineItemIndex)
{
if (giftLineItem.Parent.Shipments.Any() && lineItemIndex != -1)
{
// When adding gift item to shipment, need to re-add to empty shipment that gift item had been removed before.
// Otherwise if have no empty shipment found, add to the first shipment.
var shipment = giftLineItem.Parent.Shipments.FirstOrDefault(s => s.LineItems.Count() == 0) ?? giftLineItem.Parent.Shipments[0];
shipment.AddLineItemIndex(lineItemIndex, giftLineItem.Quantity);
}
}
private LineItem AddNewGiftLineItemToOrder(OrderGroup order, Entry entry, decimal quantity)
{
LineItem lineItem = order.OrderForms[0].LineItems.AddNew();
// If entry has a parent, add parents name
if (entry.ParentEntry != null)
{
lineItem.DisplayName = String.Format("{0}: {1}", entry.ParentEntry.Name, entry.Name);
lineItem.ParentCatalogEntryId = entry.ParentEntry.ID;
}
else
{
lineItem.DisplayName = entry.Name;
lineItem.ParentCatalogEntryId = String.Empty;
}
lineItem.Code = entry.ID;
//Price price = StoreHelper.GetSalePrice(entry, quantity);
//entry.ItemAttributes always null
//lineItem.ListPrice = entry.ItemAttributes.ListPrice.Amount;
lineItem.MaxQuantity = entry.ItemAttributes.MaxQuantity;
lineItem.MinQuantity = entry.ItemAttributes.MinQuantity;
lineItem.Quantity = quantity;
// try to add warehouseCode from shipment record or other line items
string warehouseCode = string.Empty;
if (order.OrderForms[0].Shipments.Count > 0)
{
warehouseCode = order.OrderForms[0].Shipments[0].WarehouseCode;
}
// Add warehouse from existing items in case not specified for gift item
if (String.IsNullOrEmpty(lineItem.WarehouseCode))
{
warehouseCode = order.OrderForms[0].LineItems[0].WarehouseCode;
}
if (!String.IsNullOrEmpty(warehouseCode))
{
lineItem.WarehouseCode = warehouseCode;
}
lineItem.InventoryStatus = (int)GetInventoryStatus(entry.ID, warehouseCode);
return lineItem;
}
/// <summary>
/// Applies the item discount.
/// </summary>
/// <param name="order">The order.</param>
/// <param name="record">The record.</param>
/// <param name="totalAmount">The total amount.</param>
/// <returns></returns>
private decimal ApplyItemDiscount(OrderGroup order, PromotionItemRecord record, decimal totalAmount)
{
decimal discountAmount = 0;
if (record.PromotionReward.RewardType == PromotionRewardType.AllAffectedEntries)
{
decimal averageDiscountAmount;
if (record.PromotionReward.AmountType == PromotionRewardAmountType.Percentage)
{
discountAmount = _currency.Percentage(record.AffectedEntriesSet.TotalCost, record.PromotionReward.AmountOff);
averageDiscountAmount = discountAmount / record.AffectedEntriesSet.TotalQuantity;
}
else // need to split discount between all items
{
discountAmount = record.PromotionReward.AmountOff;
averageDiscountAmount = record.PromotionReward.AmountOff / record.AffectedEntriesSet.TotalQuantity;
}
foreach (PromotionEntry entry in record.AffectedEntriesSet.Entries)
{
AddDiscountToLineItem(order, record, entry, averageDiscountAmount * entry.Quantity, 0);
}
}
else if (record.PromotionReward.RewardType == PromotionRewardType.EachAffectedEntry)
{
if (record.PromotionReward.AmountType == PromotionRewardAmountType.Percentage)
{
discountAmount = _currency.Percentage(record.AffectedEntriesSet.TotalCost, record.PromotionReward.AmountOff);
foreach (PromotionEntry entry in record.AffectedEntriesSet.Entries)
{
AddDiscountToLineItem(order, record, entry, entry.CostPerEntry * entry.Quantity * record.PromotionReward.AmountOff / 100, 0);
}
}
else
{
discountAmount = record.AffectedEntriesSet.TotalQuantity * record.PromotionReward.AmountOff;
foreach (PromotionEntry entry in record.AffectedEntriesSet.Entries)
{
AddDiscountToLineItem(order, record, entry, record.PromotionReward.AmountOff * entry.Quantity, 0);
}
}
}
else if (record.PromotionReward.RewardType == PromotionRewardType.WholeOrder)
{
decimal percentageOffTotal = 0;
if (record.PromotionReward.AmountType == PromotionRewardAmountType.Percentage)
{
decimal extendedCost = 0;
foreach (OrderForm orderForm in order.OrderForms)
{
extendedCost += orderForm.LineItems.ToArray().Sum(x => x.ExtendedPrice);
}
// calculate percentage adjusted by the running amount, so it will be a little less if running amount is less than total
percentageOffTotal = (record.PromotionReward.AmountOff / 100) * (totalAmount / extendedCost);
discountAmount = _currency.Percentage(totalAmount, record.PromotionReward.AmountOff);
}
else
{
// Calculate percentage off discount price
if (totalAmount > 0)
{
percentageOffTotal = record.PromotionReward.AmountOff / totalAmount;
// but since CostPerEntry is not an adjusted price, we need to take into account additional discounts already applied
percentageOffTotal = percentageOffTotal * (totalAmount / record.AffectedEntriesSet.TotalCost);
discountAmount = record.PromotionReward.AmountOff;
}
else
{
percentageOffTotal = 100m;
discountAmount = 0;
}
}
// Now distribute discount amount evenly over all entries taking into account running total
// Special case for shipments, we consider WholeOrder to be a shipment
if (!record.PromotionItem.DataRow.PromotionGroup.Equals(PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Shipping).Key, StringComparison.OrdinalIgnoreCase))
{
foreach (PromotionEntry entry in record.AffectedEntriesSet.Entries)
{
LineItem item = FindLineItemByPromotionEntry(order, entry);
var orderLevelDiscount = _currency.Round(item.ExtendedPrice * percentageOffTotal);
AddDiscountToLineItem(order, record, entry, 0, orderLevelDiscount);
}
}
}
// Save discounts
if (record.PromotionItem.DataRow.PromotionGroup.Equals(PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Order).Key, StringComparison.OrdinalIgnoreCase)
|| record.PromotionReward is GiftPromotionReward)
{
if (record.PromotionReward.RewardType == PromotionRewardType.WholeOrder && discountAmount > 0)
{
OrderFormDiscount discount = FindOrderFormDiscountById(order, record.PromotionItem.DataRow.PromotionId, Int32.Parse(record.AffectedEntriesSet.OrderFormId));
bool hasOrderFormDiscount = true;
if (discount == null)
{
discount = new OrderFormDiscount();
hasOrderFormDiscount = false;
}
var discountName = record.PromotionItem.DataRow.Name;
if (record.PromotionReward is GiftPromotionReward)
{
discountName = GetGiftPromotionName(record);
}
discount.DiscountName = discountName;
discount.DiscountAmount = record.PromotionReward.AmountOff;
discount.DiscountCode = record.PromotionItem.DataRow.CouponCode;
discount.DiscountValue = hasOrderFormDiscount ? discountAmount + discount.DiscountValue : discountAmount;
discount.DisplayMessage = GetDisplayName(record.PromotionItem.DataRow, Thread.CurrentThread.CurrentCulture.Name);
discount.OrderFormId = Int32.Parse(record.AffectedEntriesSet.OrderFormId);
discount.DiscountId = record.PromotionItem.DataRow.PromotionId;
foreach (OrderForm form in order.OrderForms)
{
if (form.OrderFormId == discount.OrderFormId && !hasOrderFormDiscount)
form.Discounts.Add(discount);
}
}
}
else if (record.PromotionItem.DataRow.PromotionGroup.Equals(PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Shipping).Key, StringComparison.OrdinalIgnoreCase))
{
ShipmentDiscount discount = FindShipmentDiscountById(order, record.PromotionItem.DataRow.PromotionId, Int32.Parse(record.AffectedEntriesSet.ShipmentId));
if (discount == null)
{
discount = new ShipmentDiscount();
}
discount.DiscountAmount = record.PromotionReward.AmountOff;
discount.DiscountCode = record.PromotionItem.DataRow.CouponCode;
discount.DiscountName = record.PromotionItem.DataRow.Name;
discount.DisplayMessage = GetDisplayName(record.PromotionItem.DataRow, Thread.CurrentThread.CurrentCulture.Name);
discount.ShipmentId = Int32.Parse(record.AffectedEntriesSet.ShipmentId);
discount.DiscountId = record.PromotionItem.DataRow.PromotionId;
var shipment = order.OrderForms.SelectMany(o => o.Shipments).FirstOrDefault(s => s.ShipmentId == discount.ShipmentId);
if (shipment != null)
{
shipment.Discounts.Add(discount);
if (record.PromotionReward.AmountType == PromotionRewardAmountType.Percentage)
{
discountAmount = _currency.Percentage(shipment.ShippingSubTotal, record.PromotionReward.AmountOff);
}
else
{
// PromotionReward.AmountOff was calculated in Promotion context, it's not be rounded.
discountAmount = _currency.Round(Math.Min(record.PromotionReward.AmountOff, shipment.ShippingSubTotal));
}
shipment.ShippingDiscountAmount = Math.Min(shipment.ShippingDiscountAmount + discountAmount, shipment.ShippingSubTotal);
// ShippingDiscountAmount will not be subtracted from the ShipmentTotal per discussions on 2/22/2012.
}
discount.DiscountValue = discountAmount;
}
return discountAmount;
}
private void AddDiscountToLineItem(OrderGroup order, PromotionItemRecord itemRecord, PromotionEntry promotionEntry,
decimal itemDiscount, decimal orderLevelDiscount)
{
itemDiscount = _currency.Round(itemDiscount);
orderLevelDiscount = _currency.Round(orderLevelDiscount);
LineItem item = FindLineItemByPromotionEntry(order, promotionEntry);
if (item != null)
{
//reset gift line item discount
if (IsGiftLineItem(item))
{
item.PlacedPrice = promotionEntry.CostPerEntry;
item.LineItemDiscountAmount = itemDiscount;
item.OrderLevelDiscountAmount = 0;
item.ExtendedPrice = item.PlacedPrice;
}
else
{
// Add line item properties
item.LineItemDiscountAmount += itemDiscount;
item.OrderLevelDiscountAmount += orderLevelDiscount;
item.ExtendedPrice = item.PlacedPrice * item.Quantity - item.LineItemDiscountAmount - item.OrderLevelDiscountAmount;
}
if (itemRecord.PromotionItem.DataRow.PromotionGroup.Equals(PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Entry).Key, StringComparison.OrdinalIgnoreCase)
|| itemRecord.PromotionReward is GiftPromotionReward
|| (itemRecord.PromotionItem.DataRow.PromotionGroup.Equals(PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Order).Key,
StringComparison.OrdinalIgnoreCase) && itemRecord.PromotionReward.RewardType == PromotionRewardType.EachAffectedEntry))
{
LineItemDiscount discount = FindLineItemDiscountById(order, itemRecord.PromotionItem.DataRow.PromotionId, item.LineItemId);
if (discount == null)
{
discount = new LineItemDiscount();
item.Discounts.Add(discount);
}
var discountName = itemRecord.PromotionItem.DataRow.Name;
if (itemRecord.PromotionReward is GiftPromotionReward)
{
discount.DiscountName = GetGiftPromotionName(itemRecord);
}
else
{
discount.DiscountName = String.Format("{0}{1}", itemRecord.PromotionItem.DataRow.Name,
itemRecord.PromotionItem.DataRow.OfferType == 1 ? ":PercentageBased" : ":ValueBased");
}
discount.DiscountAmount = itemRecord.PromotionReward.AmountOff;
discount.DiscountCode = itemRecord.PromotionItem.DataRow.CouponCode;
discount.DiscountValue = itemDiscount;
// use the promotion name if the localized display message is null or empty
discount.DisplayMessage = GetDisplayName(itemRecord.PromotionItem.DataRow, Thread.CurrentThread.CurrentCulture.Name);
if (string.IsNullOrEmpty(discount.DisplayMessage))
discount.DisplayMessage = itemRecord.PromotionItem.DataRow.Name;
discount.LineItemId = item.LineItemId;
discount.DiscountId = itemRecord.PromotionItem.DataRow.PromotionId;
}
}
}
private LineItem FindGiftLineItemInOrder(OrderGroup order, string catalogEntryId, PromotionItemRecord promoRecord)
{
var lineItems = order.OrderForms[0].LineItems.ToArray().Where(x => x.Code == catalogEntryId);
foreach (var lineitem in lineItems)
{
foreach (LineItemDiscount discount in lineitem.Discounts)
{
if (discount.DiscountName == GetGiftPromotionName(promoRecord))
{
return lineitem;
}
}
}
return null;
}
private bool IsOrderHaveSpecifiedGiftPromotion(OrderGroup order, PromotionItemRecord promoRecord)
{
bool retVal = false;
foreach (OrderFormDiscount discount in order.OrderForms[0].Discounts)
{
if (GetGiftPromotionName(promoRecord) == discount.DiscountName)
{
retVal = true;
break;
}
}
return retVal;
}
private static LineItem FindLineItemByPromotionEntry(OrderGroup order, PromotionEntry prmotionEntry)
{
LineItem retVal = null;
foreach (OrderForm form in order.OrderForms)
{
foreach (LineItem item in form.LineItems)
{
if (item == prmotionEntry.Owner)
{
retVal = item;
break;
}
}
if (retVal != null)
break;
}
return retVal;
}
/// <summary>
/// Finds the order form discount by id.
/// </summary>
/// <param name="order">The order.</param>
/// <param name="promotionId">The promotion id.</param>
/// <param name="orderFormId">The order form id.</param>
/// <returns></returns>
private OrderFormDiscount FindOrderFormDiscountById(OrderGroup order, int promotionId, int orderFormId)
{
foreach (OrderForm form in order.OrderForms)
{
if (form.OrderFormId == orderFormId)
{
foreach (OrderFormDiscount discount in form.Discounts)
{
if (discount.DiscountId == promotionId)
return discount;
}
}
}
return null;
}
/// <summary>
/// Finds the shipment discount by id.
/// </summary>
/// <param name="order">The order.</param>
/// <param name="promotionId">The promotion id.</param>
/// <param name="shipmentId">The shipment id.</param>
/// <returns></returns>
private ShipmentDiscount FindShipmentDiscountById(OrderGroup order, int promotionId, int shipmentId)
{
foreach (OrderForm form in order.OrderForms)
{
foreach (Shipment shipment in form.Shipments)
{
if (shipment.ShipmentId == shipmentId)
{
foreach (ShipmentDiscount discount in shipment.Discounts)
{
if (discount.DiscountId == promotionId)
return discount;
}
}
}
}
return null;
}
/// <summary>
/// Finds the line item discount by id.
/// </summary>
/// <param name="order">The order.</param>
/// <param name="promotionId">The promotion id.</param>
/// <param name="lineItemId">The line item id.</param>
/// <returns></returns>
private LineItemDiscount FindLineItemDiscountById(OrderGroup order, int promotionId, int lineItemId)
{
foreach (OrderForm form in order.OrderForms)
{
foreach (LineItem lineItem in form.LineItems)
{
foreach (LineItemDiscount discount in lineItem.Discounts)
{
if (discount.DiscountId == promotionId && discount.LineItemId == lineItemId && discount.ObjectState != MetaDataPlus.MetaObjectState.Deleted)
return discount;
}
}
}
return null;
}
/// <summary>
/// Gets the display name.
/// </summary>
/// <param name="row">The row.</param>
/// <param name="languageCode">The language code.</param>
/// <returns></returns>
private string GetDisplayName(PromotionDto.PromotionRow row, string languageCode)
{
PromotionDto.PromotionLanguageRow[] langRows = row.GetPromotionLanguageRows();
if (langRows != null && langRows.Length > 0)
{
foreach (PromotionDto.PromotionLanguageRow lang in langRows)
{
if (lang.LanguageCode.Equals(languageCode, StringComparison.OrdinalIgnoreCase))
{
return lang.DisplayName;
}
}
}
return row.Name;
}
/// <summary>
/// Creates the set from order form.
/// </summary>
/// <param name="form">The form.</param>
/// <returns></returns>
private PromotionEntriesSet CreateSetFromOrderForm(OrderForm form)
{
PromotionEntriesSet set = new PromotionEntriesSet();
set.OrderFormId = form.OrderFormId.ToString();
IOrderedEnumerable<LineItem> lineItemByPrice = form.LineItems.ToArray().Where(x => !IsGiftLineItem(x)).OrderByDescending(x => x.PlacedPrice);
foreach (LineItem lineItem in lineItemByPrice)
{
set.Entries.Add(CreatePromotionEntryFromLineItem(lineItem));
}
return set;
}
/// <summary>
/// Creates the set from shipment.
/// </summary>
/// <param name="shipment">The shipment.</param>
/// <returns></returns>
private PromotionEntriesSet CreateSetFromShipment(Shipment shipment)
{
PromotionEntriesSet set = new PromotionEntriesSet();
set.ShipmentId = shipment.ShipmentId.ToString();
set.OrderFormId = shipment.Parent.OrderFormId.ToString();
foreach (string lineItemIndex in shipment.LineItemIndexes)
{
LineItem lineItem = shipment.Parent.LineItems[Int32.Parse(lineItemIndex)];
if (lineItem != null && !IsGiftLineItem(lineItem))
{
PromotionEntry entry = CreatePromotionEntryFromLineItem(lineItem);
set.Entries.Add(entry);
}
}
return set;
}
/// <summary>
/// Creates the promotion entry from line item.
/// </summary>
/// <param name="lineItem">The line item.</param>
/// <returns></returns>
private PromotionEntry CreatePromotionEntryFromLineItem(LineItem lineItem)
{
string catalogNodes = String.Empty;
string catalogs = String.Empty;
string catalogName = lineItem.Catalog;
string catalogNodeCode = lineItem.CatalogNode;
// Now cycle through all the catalog nodes where this entry is present filtering by specified catalog and node code
// The nodes are only populated when Full or Nodes response group is specified.
// Request full response group so we can reuse the same cached item
Entry entry = CatalogContext.Current.GetCatalogEntry(lineItem.Code, new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.Nodes));
if (entry != null && entry.Nodes != null && entry.Nodes.CatalogNode != null && entry.Nodes.CatalogNode.Length > 0)
{
foreach (CatalogNode node in entry.Nodes.CatalogNode)
{
string entryCatalogName = CatalogContext.Current.GetCatalogDto(node.CatalogId).Catalog[0].Name;
// Skip filtered catalogs
if (!String.IsNullOrEmpty(catalogName) && !entryCatalogName.Equals(catalogName))
continue;
// Skip filtered catalogs nodes
if (!String.IsNullOrEmpty(catalogNodeCode) && !node.ID.Equals(catalogNodeCode, StringComparison.OrdinalIgnoreCase))
continue;
if (String.IsNullOrEmpty(catalogs))
catalogs = entryCatalogName;
else
catalogs += ";" + entryCatalogName;
if (String.IsNullOrEmpty(catalogNodes))
catalogNodes = node.ID;
else
catalogNodes += ";" + node.ID;
}
}
PromotionEntry result = new PromotionEntry(catalogs, catalogNodes, lineItem.Code, lineItem.PlacedPrice);
var promotionEntryPopulateService = (IPromotionEntryPopulate)MarketingContext.Current.PromotionEntryPopulateFunctionClassInfo.CreateInstance();
promotionEntryPopulateService.Populate(result, lineItem);
return result;
}
/// <summary>
/// Removing now not aplyied Gift discounts from Order
/// </summary>
private void RemoveGiftPromotionFromOrder(OrderGroup order, PromotionContext promoContext)
{
var notApliedOldGiftDiscounts = new List<OrderFormDiscount>();
foreach (OrderFormDiscount discount in order.OrderForms[0].Discounts)
{
var promoRecord = promoContext.PromotionResult.PromotionRecords.FirstOrDefault(x => GetGiftPromotionName(x) == discount.DiscountName);
if (promoRecord == null)
{
notApliedOldGiftDiscounts.Add(discount);
}
}
foreach (OrderFormDiscount toRemoveDiscount in notApliedOldGiftDiscounts)
{
toRemoveDiscount.Delete();
//remove Gift items from order
var lineitems = order.OrderForms[0].LineItems.ToArray();
foreach (LineItem lineItem in lineitems)
{
foreach (LineItemDiscount lineItemDiscount in lineItem.Discounts)
{
if (lineItemDiscount.DiscountName == toRemoveDiscount.DiscountName)
{
lineItem.Delete();
}
}
}
}
}
/// <summary>
/// Determines whether [is gift line item] [the specified line item].
/// </summary>
/// <param name="lineItem">The line item.</param>
/// <returns>
/// <c>true</c> if [is gift line item] [the specified line item]; otherwise, <c>false</c>.
/// </returns>
public bool IsGiftLineItem(LineItem lineItem)
{
bool retVal = false;
foreach (LineItemDiscount discount in lineItem.Discounts)
{
if (discount.DiscountName.EndsWith(":Gift"))
{
retVal = true;
break;
}
}
return retVal;
}
/// <summary>
/// Gets the name of the gift promotion.
/// </summary>
/// <param name="promoRecord">The promo record.</param>
/// <returns></returns>
public string GetGiftPromotionName(PromotionItemRecord promoRecord)
{
return "@" + promoRecord.PromotionItem.DataRow.Name + ":Gift";
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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 OpenSim 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.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Avatar.Chat
{
public class ChatModule : IRegionModule, IChatModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private const int DEBUG_CHANNEL = 2147483647;
private bool m_enabled = true;
private int m_saydistance = 30;
private int m_shoutdistance = 100;
private int m_whisperdistance = 10;
private List<Scene> m_scenes = new List<Scene>();
internal object m_syncInit = new object();
#region IRegionModule Members
public virtual void Initialize(Scene scene, IConfigSource config)
{
// wrap this in a try block so that defaults will work if
// the config file doesn't specify otherwise.
try
{
m_enabled = config.Configs["Chat"].GetBoolean("enabled", m_enabled);
if (!m_enabled) return;
m_whisperdistance = config.Configs["Chat"].GetInt("whisper_distance", m_whisperdistance);
m_saydistance = config.Configs["Chat"].GetInt("say_distance", m_saydistance);
m_shoutdistance = config.Configs["Chat"].GetInt("shout_distance", m_shoutdistance);
}
catch (Exception)
{
}
lock (m_syncInit)
{
if (!m_scenes.Contains(scene))
{
m_scenes.Add(scene);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnChatFromWorld += OnChatFromWorld;
scene.EventManager.OnChatBroadcast += OnChatBroadcast;
scene.RegisterModuleInterface<IChatModule>(this);
}
}
m_log.InfoFormat("[CHAT]: Initialized for {0} w:{1} s:{2} S:{3}", scene.RegionInfo.RegionName,
m_whisperdistance, m_saydistance, m_shoutdistance);
}
public virtual void PostInitialize()
{
}
public virtual void Close()
{
}
public virtual string Name
{
get { return "ChatModule"; }
}
public virtual bool IsSharedModule
{
get { return true; }
}
#endregion
public virtual void OnNewClient(IClientAPI client)
{
client.OnChatFromClient += OnChatFromClient;
}
private bool PrefilterChat(Object sender, OSChatMessage c)
{
if (c.Type != ChatTypeEnum.Say)
return false;
string[] separators = {" ", "\t"};
string[] args = c.Message.Split(separators, StringSplitOptions.RemoveEmptyEntries);
if (args.Length < 1)
return false;
if (args[0].Length < 3)
return false;
if (args[0].Substring(0, 2) != "/!")
return false;
if (sender is IClientAPI)
{
HandleChatCommand((IClientAPI)sender, c, args);
return true;
}
return false;
}
public virtual void OnChatFromClient(Object sender, OSChatMessage c)
{
if (PrefilterChat(sender, c))
return;
// redistribute to interested subscribers
Scene scene = (Scene)c.Scene;
scene.EventManager.TriggerOnChatFromClient(sender, c);
// early return if not on public or debug channel
if (c.Channel != 0 && c.Channel != DEBUG_CHANNEL) return;
// sanity check:
if (c.SenderUUID == UUID.Zero)
{
m_log.ErrorFormat("[CHAT] OnChatFromClient from {0} has empty Sender field!", sender);
return;
}
DeliverChatToAvatars(ChatSourceType.Agent, c);
}
public virtual void OnChatFromWorld(Object sender, OSChatMessage c)
{
// early return if not on public or debug channel
if (c.Channel != 0 && c.Channel != DEBUG_CHANNEL) return;
DeliverChatToAvatars(ChatSourceType.Object, c);
}
protected virtual void DeliverChatToAvatars(ChatSourceType sourceType, OSChatMessage c)
{
string fromName = c.From;
UUID fromID = UUID.Zero;
UUID ownerID = c.GeneratingAvatarID;
UUID destID = c.DestinationUUID;
string message = c.Message;
IScene scene = c.Scene;
Vector3 fromPos = c.Position;
Vector3 regionPos = new Vector3(scene.RegionInfo.RegionLocX * Constants.RegionSize,
scene.RegionInfo.RegionLocY * Constants.RegionSize, 0);
if (c.Channel == DEBUG_CHANNEL) c.Type = ChatTypeEnum.DebugChannel;
switch (sourceType)
{
case ChatSourceType.Agent:
if (!(scene is Scene))
{
m_log.WarnFormat("[CHAT]: scene {0} is not a Scene object, cannot obtain scene presence for {1}",
scene.RegionInfo.RegionName, c.SenderUUID);
return;
}
ScenePresence avatar;
if((scene as Scene).TryGetAvatar(c.SenderUUID, out avatar))
{
fromPos = avatar.AbsolutePosition;
fromName = avatar.Name;
fromID = c.SenderUUID;
ownerID = c.SenderUUID;
}
else
{
m_log.WarnFormat("[CHAT]: cannot obtain scene presence for {0}",
c.SenderUUID);
return;
}
break;
case ChatSourceType.Object:
fromID = c.SenderUUID;
break;
}
// TODO: iterate over message
if (message.Length >= 1000) // libomv limit
message = message.Substring(0, 1000);
// m_log.DebugFormat("[CHAT]: DCTA: fromID {0} fromName {1}, cType {2}, sType {3}", fromID, fromName, c.Type, sourceType);
foreach (Scene s in m_scenes)
{
s.ForEachScenePresence(delegate(ScenePresence presence)
{
if (!presence.IsChildAgent)
if ((destID == UUID.Zero) || (destID == presence.UUID))
TrySendChatMessage(presence, fromPos, regionPos, fromID, fromName, ownerID,
c.Type, message, sourceType);
});
}
}
static private Vector3 CenterOfRegion = new Vector3(128, 128, 30);
public virtual void OnChatBroadcast(Object sender, OSChatMessage c)
{
// unless the chat to be broadcast is of type Region, we
// drop it if its channel is neither 0 nor DEBUG_CHANNEL
if (c.Channel != 0 && c.Channel != DEBUG_CHANNEL && c.Type != ChatTypeEnum.Region) return;
ChatTypeEnum cType = c.Type;
if (c.Channel == DEBUG_CHANNEL)
cType = ChatTypeEnum.DebugChannel;
if (cType == ChatTypeEnum.Region)
cType = ChatTypeEnum.Say;
if (c.Message.Length > 1100)
c.Message = c.Message.Substring(0, 1000);
// broadcast chat works by redistributing every incoming chat
// message to each avatar in the scene.
string fromName = c.From;
UUID fromID = UUID.Zero;
UUID ownerID = c.GeneratingAvatarID;
ChatSourceType sourceType = ChatSourceType.Object;
ScenePresence avatar;
if ((c.Scene as Scene).TryGetAvatar(c.SenderUUID, out avatar))
{
fromID = c.SenderUUID;
fromName = avatar.Name;
ownerID = c.SenderUUID;
sourceType = ChatSourceType.Agent;
}
else if (c.SenderUUID != UUID.Zero)
{
fromID = c.SenderUUID;
}
// m_log.DebugFormat("[CHAT] Broadcast: fromID {0} fromName {1}, cType {2}, sType {3}", fromID, fromName, cType, sourceType);
((Scene)c.Scene).ForEachScenePresence(
delegate(ScenePresence presence)
{
// ignore chat from child agents
if (presence.IsChildAgent) return;
IClientAPI client = presence.ControllingClient;
// don't forward SayOwner chat from objects to
// non-owner agents
if ((c.Type == ChatTypeEnum.Owner) &&
(ownerID != client.AgentId))
return;
presence.Scene.EventManager.TriggerOnChatToClient(c.Message, fromID,
client.AgentId, presence.Scene.RegionInfo.RegionID, (uint)Util.UnixTimeSinceEpoch(),
ChatToClientType.InworldChat);
client.SendChatMessage(c.Message, (byte)cType, CenterOfRegion, fromName, fromID, ownerID,
(byte)sourceType, (byte)ChatAudibleLevel.Fully);
});
}
public bool ShouldChatCrossRegions(ChatTypeEnum type)
{
switch (type)
{
case ChatTypeEnum.Whisper: return true;
case ChatTypeEnum.Say: return true;
case ChatTypeEnum.Shout: return true;
case (ChatTypeEnum)3: return true; // 3 is an obsolete version of Say
case ChatTypeEnum.StartTyping: return false;
case ChatTypeEnum.StopTyping: return false;
case ChatTypeEnum.DebugChannel: return false;
case ChatTypeEnum.Region: return false;
case ChatTypeEnum.Owner: return false;
case ChatTypeEnum.Direct: return false; // llRegionSayTo
case ChatTypeEnum.Broadcast: return true;
}
return false; // by default, new types will stay within the region
}
protected virtual void TrySendChatMessage(ScenePresence presence, Vector3 fromPos, Vector3 regionPos,
UUID fromAgentID, string fromName, UUID ownerID, ChatTypeEnum type,
string message, ChatSourceType src)
{
if ((presence.Scene.RegionInfo.RegionLocX != ((uint)regionPos.X) / Constants.RegionSize) ||
(presence.Scene.RegionInfo.RegionLocY != ((uint)regionPos.Y) / Constants.RegionSize))
{ // Different region?
if (!ShouldChatCrossRegions(type))
return;
}
Vector3 fromRegionPos = fromPos + regionPos;
Vector3 toRegionPos = presence.AbsolutePosition +
new Vector3(presence.Scene.RegionInfo.RegionLocX * Constants.RegionSize,
presence.Scene.RegionInfo.RegionLocY * Constants.RegionSize, 0);
// fix the exception that happens if
double fdist = Util.GetDistanceTo(toRegionPos, fromRegionPos);
if (fdist > (double)Int32.MaxValue)
return;
if (fdist < -(double)Int32.MaxValue)
return;
int dis = Math.Abs((int) fdist); // throws an exception on the cast if out of range
if (type == ChatTypeEnum.Whisper && dis > m_whisperdistance ||
type == ChatTypeEnum.Say && dis > m_saydistance ||
type == ChatTypeEnum.Shout && dis > m_shoutdistance)
{
return;
}
presence.Scene.EventManager.TriggerOnChatToClient(message, fromAgentID,
presence.UUID, presence.Scene.RegionInfo.RegionID, (uint)Util.UnixTimeSinceEpoch(),
ChatToClientType.InworldChat);
// TODO: should change so the message is sent through the avatar rather than direct to the ClientView
presence.ControllingClient.SendChatMessage(message, (byte) type, fromPos, fromName, fromAgentID,
ownerID, (byte)src, (byte)ChatAudibleLevel.Fully);
}
private SceneObjectPart FindObject(uint localID)
{
SceneObjectPart part = null;
foreach (Scene scene in m_scenes)
{
part = scene.GetSceneObjectPart(localID);
if (part != null)
break;
}
return part;
}
private SceneObjectPart FindObject(UUID id)
{
SceneObjectPart part = null;
foreach (Scene scene in m_scenes)
{
part = scene.GetSceneObjectPart(id);
if (part != null)
break;
}
return part;
}
private List<SceneObjectGroup> FindMatchingObjects(string name, UUID agentId)
{
List<SceneObjectGroup> results = new List<SceneObjectGroup>();
string target = String.Empty;
UUID targetID;
if (!UUID.TryParse(name, out targetID))
{
targetID = UUID.Zero;
target = name.Trim().ToLower();
if (String.IsNullOrEmpty(target))
return results;
}
int count = 0;
foreach (Scene scene in m_scenes)
{
bool includeAttachments = (agentId == UUID.Zero) ? false : scene.Permissions.IsGod(agentId);
foreach (EntityBase ent in scene.Entities)
{
if (ent is SceneObjectGroup)
{
SceneObjectGroup group = (SceneObjectGroup)ent;
if ((group.IsAttachment) && (!includeAttachments))
continue;
if (targetID != UUID.Zero)
{ // search by user
if (group.OwnerID == targetID)
{
results.Add(group);
count++;
}
}
else
{
// search by object name
if (group.Name.ToLower().Contains(target))
{
results.Add(group);
count++;
}
}
// Don't let this list build up to huge counts if someone searches for "e"...
if (count >= 100)
return results;
}
}
}
return results;
}
private void SendClientChat(IClientAPI client, string format, params Object[] args)
{
Vector3 Pos = new Vector3(128.0f, 128.0f, 128.0f); // close enough, we're sending to the viewer no matter what
string msg = String.Format(format, args);
((Scene)client.Scene).EventManager.TriggerOnChatToClient(msg, UUID.Zero,
client.AgentId, client.Scene.RegionInfo.RegionID, (uint)Util.UnixTimeSinceEpoch(),
ChatToClientType.InworldChat);
client.SendChatMessage(msg, (byte)ChatTypeEnum.Say, Pos, client.Name, UUID.Zero, UUID.Zero,
(byte)ChatSourceType.System, (byte)ChatAudibleLevel.Fully);
}
private void SendSystemChat(IClientAPI client, string format, params Object[] args)
{
Vector3 GodPos = new Vector3(128.0f, 128.0f, 128.0f);
string msg = String.Format(format, args);
((Scene)client.Scene).EventManager.TriggerOnChatToClient(msg, UUID.Zero,
client.AgentId, client.Scene.RegionInfo.RegionID, (uint)Util.UnixTimeSinceEpoch(),
ChatToClientType.InworldChat);
client.SendChatMessage(msg, (byte)ChatTypeEnum.Say, GodPos, "System", UUID.Zero, UUID.Zero,
(byte)ChatSourceType.System, (byte)ChatAudibleLevel.Fully);
}
private void DumpPart(IClientAPI client, Scene scene, SceneObjectPart part)
{
if (part == part.ParentGroup.RootPart)
{
SendSystemChat(client, "Object {0} [{1}] '{2}' at {3}{4}", part.LocalId.ToString(), part.UUID.ToString(), part.Name, Util.LocationShortCode(scene.RegionInfo.RegionName, part.AbsolutePosition), part.ParentGroup.IsAttachment ? " (attached)" : "");
}
else
{
SceneObjectPart root = part.ParentGroup.RootPart;
SendSystemChat(client, "Child prim {0} [{1}] '{2}' at {3}", part.LocalId.ToString(), part.UUID.ToString(), part.Name, Util.LocationShortCode(scene.RegionInfo.RegionName, part.AbsolutePosition));
SendSystemChat(client, "Root prim {0} [{1}] '{2}' at {3}{4}", root.LocalId.ToString(), root.UUID.ToString(), root.Name, Util.LocationShortCode(scene.RegionInfo.RegionName, part.AbsolutePosition), part.ParentGroup.IsAttachment ? " (attached)" : "");
}
}
private void FindObjects(IClientAPI client, string[] args)
{
if (args.Length <= 1)
{
SendSystemChat(client, "Error: expected either a UUID or a local ID for an object or user.");
return;
}
string arg = args[1];
UUID uuid = UUID.Zero;
uint localID = 0;
if (!UUID.TryParse(arg, out uuid))
uuid = UUID.Zero;
if (uuid != UUID.Zero) // see if it's a prim
{
foreach (Scene scene in m_scenes)
{
SceneObjectPart part = scene.GetSceneObjectPart(uuid);
if (part != null)
{
// Allow the user to dump any part (including an attachment) if they specify the UUID.
DumpPart(client, scene, part);
return;
}
}
}
if ((uuid==UUID.Zero) && uint.TryParse(arg, out localID))
{
foreach (Scene scene in m_scenes)
{
SceneObjectPart part = scene.GetSceneObjectPart(localID);
if (part != null)
{
// Allow the user to dump any part (including an attachment) if they are the owner of the attachment.
if (part.IsAttachment && part.OwnerID != client.AgentId && !scene.Permissions.IsGod(client.AgentId))
SendSystemChat(client, "That ID specifies an attachment.");
else
DumpPart(client, scene, part);
return;
}
}
SendSystemChat(client, "Error: Could not find an part with local ID: " + localID.ToString());
return;
}
List<SceneObjectGroup> results;
if (uuid != UUID.Zero) // find by user
{
results = FindMatchingObjects(uuid.ToString(), client.AgentId);
}
else
{
string objName = string.Join(" ", args, 1, args.Length - 1);
results = FindMatchingObjects(objName, client.AgentId);
}
if (results.Count < 1)
{
SendSystemChat(client, "No matching objects found.");
}
else
{
SendSystemChat(client, "{0} matching objects found:", results.Count);
foreach (SceneObjectGroup group in results)
{
DumpPart(client, group.Scene, group.RootPart);
}
}
}
private void NukeObject(IClientAPI client, string[] args)
{
if (args.Length > 1)
{
string arg = args[1];
UUID uuid = UUID.Zero;
uint localID = 0;
if (UUID.TryParse(arg, out uuid))
{
foreach (Scene scene in m_scenes)
{
SceneObjectPart part = scene.GetSceneObjectPart(uuid);
if (part != null)
{
if (part.IsAttachment)
SendSystemChat(client, "That ID specifies an attachment.");
else
{
SceneObjectPart rootPart = part.ParentGroup.RootPart;
scene.DeRezObject(client, rootPart.LocalId, rootPart.GroupID, DeRezAction.Return, UUID.Zero);
}
return;
}
}
SendSystemChat(client, "Error: Could not find an part with UUID: {0}", uuid.ToString());
return;
}
if (uint.TryParse(arg, out localID))
{
foreach (Scene scene in m_scenes)
{
SceneObjectPart part = scene.GetSceneObjectPart(localID);
if (part != null)
{
if (part.IsAttachment)
SendSystemChat(client, "That ID specifies an attachment.");
else
{
SceneObjectPart rootPart = part.ParentGroup.RootPart;
scene.DeRezObject(client, rootPart.LocalId, rootPart.GroupID, DeRezAction.Return, UUID.Zero);
}
return;
}
}
SendSystemChat(client, "Error: Could not find an part with local ID: " + localID.ToString());
return;
}
// fall thru since the error at the end fits here too.
}
SendSystemChat(client, "Error: expected either a UUID or a local ID for an object.");
}
private void ShowOffsimObjects(IClientAPI client)
{
uint count = 0;
foreach (Scene scene in m_scenes)
{
foreach (EntityBase ent in scene.Entities)
{
if (ent is SceneObjectGroup)
{
SceneObjectGroup group = (SceneObjectGroup)ent;
if (group.IsAttachment)
continue;
Vector3 pos = group.AbsolutePosition;
if ((pos.X < 0) || (pos.Y < 0) || (pos.X >= Constants.RegionSize) || (pos.Y >= Constants.RegionSize))
{
count++;
DumpPart(client, scene, group.RootPart);
}
}
}
}
SendSystemChat(client, "{0} off-sim objects found:", count);
}
private void DebugCrossings(IClientAPI client)
{
bool newValue = !client.DebugCrossings;
client.DebugCrossings = newValue;
SendSystemChat(client, "Crossing debug messages are now: {0}", newValue ? "enabled" : "disabled");
}
private void ShowUpdates(IClientAPI client, string[] args)
{
string[] inArgs = { String.Empty, args[2] };
foreach (Scene scene in m_scenes)
{
string output = scene.GetTopUpdatesOutput(inArgs);
SendSystemChat(client, "{0}", output);
}
}
private void ShowNeighborsRange(IClientAPI client, bool updated)
{
foreach (Scene scene in m_scenes)
{
SendSystemChat(client, "Neighbors range from {0} is {1}{2}.",
scene.RegionInfo.RegionName, updated?"now ":"", client.NeighborsRange);
}
}
private bool NeighborsRange(IClientAPI client, string arg)
{
foreach (Scene scene in m_scenes)
{
try
{
uint range = Convert.ToUInt32(arg);
if ((range == 1) || (range == 2))
{
client.NeighborsRange = range;
return true;
}
}
catch (Exception) {
SendClientChat(client, "Expected a neighbors range of 1 or 2.");
}
}
return false; // if we get here, it wasn't updated.
}
private void HandleChatCommand(IClientAPI client, OSChatMessage c, string[] args)
{
SendClientChat(client, "{0}", string.Join(" ",args));
switch (args[0].ToLower())
{
case "/!find":
FindObjects(client, args);
break;
case "/!nuke":
NukeObject(client, args);
break;
case "/!show":
if (args.Length > 1)
{
if ((args.Length > 2) && (args[1] == "updates"))
{
ShowUpdates(client, args);
}
else
if ((args[1] == "offsim") || (args[1] == "off-sim"))
{
ShowOffsimObjects(client);
}
}
break;
case "/!debug":
if (args.Length > 1)
{
if ((args[1] == "crossings") || (args[1] == "cross"))
{
DebugCrossings(client);
return;
}
}
SendSystemChat(client, "Region chat command was not recognized. Did you intend? /!debug crossings");
break;
case "/!neighbor": // lets allow some variations on the spelling etc. for 'muricans :p
case "/!neighbors":
case "/!neighbour":
case "/!neighbours":
if ((args.Length > 1) && ((args[1] == "range") || (args[1] == "show")))
{
if (args.Length > 2)
{
if (NeighborsRange(client, args[2])) // if changed
{
ScenePresence avatar;
if ((client.Scene as Scene).TryGetAvatar(c.SenderUUID, out avatar))
avatar.UpdateForDrawDistanceChange(); // update the visible neighbors
ShowNeighborsRange(client, true);
}
break;
}
}
// else show the current value
ShowNeighborsRange(client, false);
break;
default:
SendSystemChat(client, "Region chat command was not recognized.");
break;
}
}
}
}
| |
using System;
namespace Krs.Ats.IBNet
{
/// <summary>
/// Execution details returned by Interactive Brokers
/// </summary>
[Serializable()]
public class Execution
{
#region Private Variables
private String accountNumber;
private int clientId;
private String exchange;
private String executionId;
private int liquidation;
private int orderId;
private int permId;
private double price;
private int shares;
private ExecutionSide side;
private String time;
private int cumQuantity;
private decimal avgPrice;
private String orderRef;
#endregion
#region Constructors
/// <summary>
/// Default Constructor
/// </summary>
public Execution()
{
}
/// <summary>
/// Full Constructor
/// </summary>
/// <param name="orderId">The order id.</param>
/// <param name="clientId">TWS orders have a fixed client id of "0."</param>
/// <param name="executionId">Unique order execution id.</param>
/// <param name="time">The order execution time.</param>
/// <param name="accountNumber">The customer account number.</param>
/// <param name="exchange">Exchange that executed the order.</param>
/// <param name="side">Specifies if the transaction was a sale or a purchase.</param>
/// <param name="shares">The number of shares filled.</param>
/// <param name="price">The order execution price.</param>
/// <param name="permId">The TWS id used to identify orders, remains the same over TWS sessions.</param>
/// <param name="liquidation">Identifies the position as one to be liquidated last should the need arise.</param>
/// <param name="cumQuantity">Cumulative quantity. Used in regular trades, combo trades and legs of the combo.</param>
/// <param name="avgPrice">Average price. Used in regular trades, combo trades and legs of the combo.</param>
/// <param name="orderRef">Order Reference</param>
public Execution(int orderId, int clientId, String executionId, String time, String accountNumber,
String exchange, ExecutionSide side, int shares, double price, int permId, int liquidation,
int cumQuantity, decimal avgPrice, string orderRef)
{
this.orderId = orderId;
this.clientId = clientId;
this.executionId = executionId;
this.time = time;
this.accountNumber = accountNumber;
this.exchange = exchange;
this.side = side;
this.shares = shares;
this.price = price;
this.permId = permId;
this.liquidation = liquidation;
this.cumQuantity = cumQuantity;
this.avgPrice = avgPrice;
this.orderRef = orderRef;
}
#endregion
#region Properties
/// <summary>
/// The order id.
/// </summary>
/// <remarks>TWS orders have a fixed order id of "0."</remarks>
public int OrderId
{
get { return orderId; }
set { orderId = value; }
}
/// <summary>
/// The id of the client that placed the order.
/// </summary>
/// <remarks>TWS orders have a fixed client id of "0."</remarks>
public int ClientId
{
get { return clientId; }
set { clientId = value; }
}
/// <summary>
/// Unique order execution id.
/// </summary>
public string ExecutionId
{
get { return executionId; }
set { executionId = value; }
}
/// <summary>
/// The order execution time.
/// </summary>
public string Time
{
get { return time; }
set { time = value; }
}
/// <summary>
/// The customer account number.
/// </summary>
public string AccountNumber
{
get { return accountNumber; }
set { accountNumber = value; }
}
/// <summary>
/// Exchange that executed the order.
/// </summary>
public string Exchange
{
get { return exchange; }
set { exchange = value; }
}
/// <summary>
/// Specifies if the transaction was a sale or a purchase.
/// </summary>
/// <remarks>Valid values are:
/// <list type="bullet">
/// <item>Bought</item>
/// <item>Sold</item>
/// </list>
/// </remarks>
public ExecutionSide Side
{
get { return side; }
set { side = value; }
}
/// <summary>
/// The number of shares filled.
/// </summary>
public int Shares
{
get { return shares; }
set { shares = value; }
}
/// <summary>
/// The order execution price.
/// </summary>
public double Price
{
get { return price; }
set { price = value; }
}
/// <summary>
/// The TWS id used to identify orders, remains the same over TWS sessions.
/// </summary>
public int PermId
{
get { return permId; }
set { permId = value; }
}
/// <summary>
/// Identifies the position as one to be liquidated last should the need arise.
/// </summary>
public int Liquidation
{
get { return liquidation; }
set { liquidation = value; }
}
/// <summary>
/// Cumulative Quantity
/// </summary>
public int CumQuantity
{
get { return cumQuantity; }
set { cumQuantity = value; }
}
/// <summary>
/// Average Price
/// </summary>
public decimal AvgPrice
{
get { return avgPrice; }
set { avgPrice = value; }
}
/// <summary>
/// OrderRef.
/// </summary>
public string OrderRef
{
get { return orderRef; }
set { orderRef = value; }
}
/// <summary>
/// EvRule.
/// </summary>
public string EvRule { get; set; }
/// <summary>
/// EvMultiplier.
/// </summary>
public double EvMultipler { get; set; }
#endregion
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using Alachisoft.NCache.Caching;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Common.Monitoring;
using System.Collections.Generic;
using Alachisoft.NCache.Common.Caching;
using Alachisoft.NCache.Common.Locking;
using Alachisoft.NCache.Util;
using Alachisoft.NCache.Common.Protobuf;
using Alachisoft.NCache.Caching.Pooling;
using Alachisoft.NCache.Common.Pooling;
using Alachisoft.NCache.SocketServer.Pooling;
using Runtime = Alachisoft.NCache.Runtime;
using Alachisoft.NCache.Common.Util;
using System.Text;
using Alachisoft.NCache.SocketServer.RuntimeLogging;
using System.Diagnostics;
using Alachisoft.NCache.SocketServer.Util;
namespace Alachisoft.NCache.SocketServer.Command
{
class RemoveCommand : CommandBase
{
protected struct CommandInfo
{
public bool DoAsync;
public long RequestId;
public string Key;
public BitSet FlagMap;
public short DsItemRemovedId;
public object LockId;
public ulong Version;
public string ProviderName;
public LockAccessType LockAccessType;
}
CommandInfo cmdInfo;
private readonly BitSet _bitSet;
private readonly RemoveResponse _removeResponse;
private readonly OperationContext _operationContext;
private OperationResult _removeResult = OperationResult.Success;
internal override OperationResult OperationResult
{
get
{
return _removeResult;
}
}
public override bool CanHaveLargedata
{
get
{
return true;
}
}
public RemoveCommand()
{
_bitSet = new BitSet();
_removeResponse = new RemoveResponse();
_operationContext = new OperationContext();
}
public override void ExecuteCommand(ClientManager clientManager, Alachisoft.NCache.Common.Protobuf.Command command)
{
int overload;
string exception = null;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
try
{
overload = command.MethodOverload;
cmdInfo = ParseCommand(command, clientManager);
}
catch (System.Exception exc)
{
_removeResult = OperationResult.Failure;
if (!base.immatureId.Equals("-2"))
{
//PROTOBUF:RESPONSE
_serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponseWithType(exc, command.requestID, command.commandID, clientManager.ClientVersion));
}
return;
}
CompressedValueEntry flagValueEntry = null;
NCache nCache = clientManager.CmdExecuter as NCache;
if (!cmdInfo.DoAsync)
{
OperationContext operationContext = null;
try
{
Notifications notification = null;
if (cmdInfo.DsItemRemovedId != -1)
{
notification = new Notifications(clientManager.ClientID, -1, -1, -1, -1, cmdInfo.DsItemRemovedId
, Runtime.Events.EventDataFilter.None, Runtime.Events.EventDataFilter.None); //DataFilter not required
}
operationContext = _operationContext;
operationContext.Add(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
operationContext.Add(OperationContextFieldName.ClientId, clientManager.ClientID);
operationContext.Add(OperationContextFieldName.MethodOverload, overload);
operationContext.Add(OperationContextFieldName.RaiseCQNotification, true);
CommandsUtil.PopulateClientIdInContext(ref operationContext, clientManager.ClientAddress);
flagValueEntry = nCache.Cache.Remove(cmdInfo.Key, cmdInfo.FlagMap, notification, cmdInfo.LockId, cmdInfo.Version, cmdInfo.LockAccessType, cmdInfo.ProviderName, operationContext);
stopWatch.Stop();
UserBinaryObject ubObject = null;
if (flagValueEntry != null)
{
if (flagValueEntry.Value is UserBinaryObject)
ubObject = (UserBinaryObject)flagValueEntry.Value;
else
{
var flag = flagValueEntry.Flag;
ubObject = (flagValueEntry == null) ? null : (UserBinaryObject)nCache.Cache.SocketServerDataService.GetClientData(flagValueEntry.Value, ref flag, LanguageContext.DOTNET);
}
}
//PROTOBUF:RESPONSE
RemoveResponse removeResponse = _removeResponse;
if (ubObject != null)
{
removeResponse.value.AddRange(ubObject.DataList);
removeResponse.flag = flagValueEntry.Flag.Data;
removeResponse.itemType = MiscUtil.EntryTypeToProtoItemType(flagValueEntry.Type);
}
if (clientManager.ClientVersion >= 5000)
{
ResponseHelper.SetResponse(removeResponse, command.requestID, command.commandID);
_serializedResponsePackets.Add(ResponseHelper.SerializeResponse(removeResponse, Response.Type.REMOVE));
}
else
{
Response response = Stash.ProtobufResponse;
{
response.remove = removeResponse;
};
ResponseHelper.SetResponse(response, command.requestID, command.commandID, Response.Type.REMOVE);
_serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response));
}
}
catch (System.Exception exc)
{
_removeResult = OperationResult.Failure;
exception = exc.ToString();
_serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponseWithType(exc, command.requestID, command.commandID, clientManager.ClientVersion));
}
finally
{
operationContext?.MarkFree(NCModulesConstants.SocketServer);
cmdInfo.FlagMap?.MarkFree(NCModulesConstants.SocketServer);
TimeSpan executionTime = stopWatch.Elapsed;
if (flagValueEntry != null)
{
MiscUtil.ReturnEntryToPool(flagValueEntry.Entry, clientManager.CacheTransactionalPool);
MiscUtil.ReturnCompressedEntryToPool(flagValueEntry, clientManager.CacheTransactionalPool);
}
try
{
if (Alachisoft.NCache.Management.APILogging.APILogManager.APILogManger != null && Alachisoft.NCache.Management.APILogging.APILogManager.EnableLogging)
{
APILogItemBuilder log = new APILogItemBuilder(MethodsName.REMOVE.ToLower());
log.GenerateRemoveAPILogItem(cmdInfo.Key, cmdInfo.FlagMap, cmdInfo.LockId, (long)cmdInfo.Version, cmdInfo.LockAccessType, cmdInfo.ProviderName, cmdInfo.DsItemRemovedId, overload, exception, executionTime, clientManager.ClientID.ToLower(), clientManager.ClientSocketId.ToString());
}
}
catch
{
}
}
}
else
{
OperationContext operationContext = null;
try
{
cmdInfo.FlagMap = new BitSet { Data = cmdInfo.FlagMap.Data };
object[] package = null;
if (cmdInfo.RequestId != -1 || cmdInfo.DsItemRemovedId != -1)
{
package = new object[] { cmdInfo.Key, cmdInfo.FlagMap, new Notifications(clientManager.ClientID,
Convert.ToInt32(cmdInfo.RequestId),
-1,
-1,
(short)(cmdInfo.RequestId == -1 ? -1 : 0),
cmdInfo.DsItemRemovedId
,Runtime.Events.EventDataFilter.None, Runtime.Events.EventDataFilter.None),cmdInfo.ProviderName}; //DataFilter not required
}
else
{
package = new object[] { cmdInfo.Key, cmdInfo.FlagMap, null, cmdInfo.ProviderName };
}
operationContext = OperationContext.CreateAndMarkInUse(clientManager.CacheFakePool, NCModulesConstants.SocketServer);
operationContext.Add(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
operationContext.Add(OperationContextFieldName.RaiseCQNotification, true);
operationContext.Add(OperationContextFieldName.MethodOverload, overload);
nCache.Cache.RemoveAsync(package, operationContext);
stopWatch.Stop();
}
finally
{
operationContext?.MarkFree(NCModulesConstants.SocketServer);
TimeSpan executionTime = stopWatch.Elapsed;
try
{
if (Alachisoft.NCache.Management.APILogging.APILogManager.APILogManger != null && Alachisoft.NCache.Management.APILogging.APILogManager.EnableLogging)
{
APILogItemBuilder log = new APILogItemBuilder(MethodsName.RemoveAsync.ToLower());
log.GenerateRemoveAPILogItem(cmdInfo.Key, cmdInfo.FlagMap, cmdInfo.LockId, (long)cmdInfo.Version, cmdInfo.LockAccessType, cmdInfo.ProviderName, cmdInfo.DsItemRemovedId, overload, exception, executionTime, clientManager.ClientID.ToLower(), clientManager.ClientSocketId.ToString());
}
}
catch { }
}
}
}
private CommandInfo ParseCommand(Alachisoft.NCache.Common.Protobuf.Command command, ClientManager clientManager)
{
CommandInfo cmdInfo = new CommandInfo();
Alachisoft.NCache.Common.Protobuf.RemoveCommand removeCommand = command.removeCommand;
cmdInfo.DoAsync = removeCommand.isAsync;
cmdInfo.DsItemRemovedId = (short)removeCommand.datasourceItemRemovedCallbackId;
BitSet bitset = BitSet.CreateAndMarkInUse(clientManager.CacheTransactionalPool, NCModulesConstants.SocketServer);
bitset.Data =((byte)removeCommand.flag);
cmdInfo.FlagMap = bitset;
cmdInfo.Key = clientManager.CacheTransactionalPool.StringPool.GetString(removeCommand.key);
cmdInfo.LockAccessType = (LockAccessType)removeCommand.lockAccessType;
cmdInfo.LockId = removeCommand.lockId;
cmdInfo.RequestId = removeCommand.requestId;
cmdInfo.Version = removeCommand.version;
cmdInfo.ProviderName = !string.IsNullOrEmpty(removeCommand.providerName) ? removeCommand.providerName : null;
return cmdInfo;
}
public sealed override void ResetLeasable()
{
base.ResetLeasable();
_bitSet.ResetLeasable();
_removeResponse.ResetLeasable();
_operationContext.ResetLeasable();
}
}
}
| |
// 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 Xunit;
namespace System.IO.Tests
{
public class DirectoryInfo_CreateSubDirectory : FileSystemTest
{
#region UniversalTests
[Fact]
public void NullAsPath_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(null));
}
[Fact]
public void EmptyAsPath_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(string.Empty));
}
[Fact]
public void PathAlreadyExistsAsFile()
{
string path = GetTestFileName();
File.Create(Path.Combine(TestDirectory, path)).Dispose();
Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(path));
Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(IOServices.AddTrailingSlashIfNeeded(path)));
Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(IOServices.RemoveTrailingSlash(path)));
}
[Theory]
[InlineData(FileAttributes.Hidden)]
[InlineData(FileAttributes.ReadOnly)]
[InlineData(FileAttributes.Normal)]
public void PathAlreadyExistsAsDirectory(FileAttributes attributes)
{
string path = GetTestFileName();
DirectoryInfo testDir = Directory.CreateDirectory(Path.Combine(TestDirectory, path));
FileAttributes original = testDir.Attributes;
try
{
testDir.Attributes = attributes;
Assert.Equal(testDir.FullName, new DirectoryInfo(TestDirectory).CreateSubdirectory(path).FullName);
}
finally
{
testDir.Attributes = original;
}
}
[Fact]
public void DotIsCurrentDirectory()
{
string path = GetTestFileName();
DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(path, "."));
Assert.Equal(IOServices.RemoveTrailingSlash(Path.Combine(TestDirectory, path)), result.FullName);
result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(path, ".") + Path.DirectorySeparatorChar);
Assert.Equal(IOServices.AddTrailingSlashIfNeeded(Path.Combine(TestDirectory, path)), result.FullName);
}
[Fact]
public void Conflicting_Parent_Directory()
{
string path = Path.Combine(TestDirectory, GetTestFileName(), "c");
Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(path));
}
[Fact]
public void DotDotIsParentDirectory()
{
DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(GetTestFileName(), ".."));
Assert.Equal(IOServices.RemoveTrailingSlash(TestDirectory), result.FullName);
result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(GetTestFileName(), "..") + Path.DirectorySeparatorChar);
Assert.Equal(IOServices.AddTrailingSlashIfNeeded(TestDirectory), result.FullName);
}
[Fact]
public void SubDirectoryIsParentDirectory_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(TestDirectory, "..")));
Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory + "/path").CreateSubdirectory("../../path2"));
}
[Theory,
MemberData(nameof(ValidPathComponentNames))]
public void ValidPathWithTrailingSlash(string component)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string path = IOServices.AddTrailingSlashIfNeeded(component);
DirectoryInfo result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path);
Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName);
Assert.True(Directory.Exists(result.FullName));
}
[Theory,
MemberData(nameof(ValidPathComponentNames))]
public void ValidPathWithoutTrailingSlash(string component)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string path = component;
DirectoryInfo result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path);
Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName);
Assert.True(Directory.Exists(result.FullName));
}
[Fact]
public void ValidPathWithMultipleSubdirectories()
{
string dirName = Path.Combine(GetTestFileName(), "Test", "Test", "Test");
DirectoryInfo dir = new DirectoryInfo(TestDirectory).CreateSubdirectory(dirName);
Assert.Equal(dir.FullName, Path.Combine(TestDirectory, dirName));
}
[Fact]
public void AllowedSymbols()
{
string dirName = Path.GetRandomFileName() + "!@#$%^&";
DirectoryInfo dir = new DirectoryInfo(TestDirectory).CreateSubdirectory(dirName);
Assert.Equal(dir.FullName, Path.Combine(TestDirectory, dirName));
}
#endregion
#region PlatformSpecific
[Theory,
MemberData(nameof(ControlWhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)] // Control whitespace in path throws ArgumentException
public void WindowsControlWhiteSpace(string component)
{
// CreateSubdirectory will throw when passed a path with control whitespace e.g. "\t"
string path = IOServices.RemoveTrailingSlash(GetTestFileName());
Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(component));
}
[Theory,
MemberData(nameof(SimpleWhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)] // Simple whitespace is trimmed in path
public void WindowsSimpleWhiteSpace(string component)
{
// CreateSubdirectory trims all simple whitespace, returning us the parent directory
// that called CreateSubdirectory
string path = IOServices.RemoveTrailingSlash(GetTestFileName());
DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(component);
Assert.True(Directory.Exists(result.FullName));
Assert.Equal(TestDirectory, IOServices.RemoveTrailingSlash(result.FullName));
}
[Theory,
MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Whitespace as path allowed
public void UnixWhiteSpaceAsPath_Allowed(string path)
{
new DirectoryInfo(TestDirectory).CreateSubdirectory(path);
Assert.True(Directory.Exists(Path.Combine(TestDirectory, path)));
}
[Theory,
MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Trailing whitespace in path treated as significant
public void UnixNonSignificantTrailingWhiteSpace(string component)
{
// Unix treats trailing/prename whitespace as significant and a part of the name.
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string path = IOServices.RemoveTrailingSlash(testDir.Name) + component;
DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(path);
Assert.True(Directory.Exists(result.FullName));
Assert.NotEqual(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName));
}
[ConditionalFact(nameof(UsingNewNormalization))]
[PlatformSpecific(TestPlatforms.Windows)] // Extended windows path
public void ExtendedPathSubdirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath());
Assert.True(testDir.Exists);
DirectoryInfo subDir = testDir.CreateSubdirectory("Foo");
Assert.True(subDir.Exists);
Assert.StartsWith(IOInputs.ExtendedPrefix, subDir.FullName);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // UNC shares
public void UNCPathWithOnlySlashes()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.Throws<ArgumentException>(() => testDir.CreateSubdirectory("//"));
}
#endregion
}
}
| |
/*
Copyright 2012 Michael Edwards
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.Collections.ObjectModel;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.Configuration.Attributes;
using Sitecore;
using Sitecore.Collections;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.DataProviders;
using Sitecore.Data.DataProviders.Sql;
using Sitecore.Data.Items;
using Sitecore.Exceptions;
using Sitecore.Mvc.Extensions;
using Sitecore.SecurityModel;
using Sitecore.Shell.Feeds.Sections;
namespace Glass.Mapper.Sc.CodeFirst
{
/// <summary>
/// Class GlassDataProvider
/// </summary>
public class GlassDataProvider : DataProvider
{
public static bool DisableItemHandlerWhenDeletingFields = false;
private static readonly object _setupLock = new object();
private bool _setupComplete;
private bool _setupProcessing;
#region IDs
/// <summary>
/// Taken from sitecore database
/// </summary>
private static readonly ID TemplateFolderId = new ID("{3C1715FE-6A13-4FCF-845F-DE308BA9741D}");
/// <summary>
/// The glass folder id
/// </summary>
public static ID GlassFolderId = new ID("{19BC20D3-CCAB-4048-9CA9-4AA631AB109F}");
#region Templates
/// <summary>
/// /sitecore/templates/System/Templates/Template section
/// </summary>
private static readonly ID SectionTemplateId = new ID("{E269FBB5-3750-427A-9149-7AA950B49301}");
/// <summary>
/// The field template id
/// </summary>
private static readonly ID FieldTemplateId = new ID("{455A3E98-A627-4B40-8035-E683A0331AC7}");
/// <summary>
/// The template template id
/// </summary>
private static readonly ID TemplateTemplateId = new ID("{AB86861A-6030-46C5-B394-E8F99E8B87DB}");
/// <summary>
/// The folder template id
/// </summary>
private static readonly ID FolderTemplateId = new ID("{A87A00B1-E6DB-45AB-8B54-636FEC3B5523}");
/// <summary>
/// The ID of the base templates field
/// </summary>
public static ID BaseTemplateField = new ID("{12C33F3F-86C5-43A5-AEB4-5598CEC45116}");
#endregion
#endregion
/// <summary>
/// Gets the name of the database.
/// </summary>
/// <value>The name of the database.</value>
public string DatabaseName { get; private set; }
/// <summary>
/// The name of the GlassContext to load
/// </summary>
public string ContextName { get; set; }
/// <summary>
/// Gets or sets the section table.
/// </summary>
/// <value>The section table.</value>
private List<SectionInfo> SectionTable { get; set; }
/// <summary>
/// Gets or sets the field table.
/// </summary>
/// <value>The field table.</value>
private List<FieldInfo> FieldTable { get; set; }
/// <summary>
/// Gets the current context.
/// </summary>
/// <value>
/// The current context.
/// </value>
public Context CurrentContext
{
get { return Context.Contexts[ContextName]; }
}
/// <summary>
/// Gets the type configurations.
/// </summary>
/// <value>
/// The type configurations.
/// </value>
public Dictionary<Type, SitecoreTypeConfiguration> TypeConfigurations
{
get
{
return CurrentContext.TypeConfigurations
.Where(x => x.Value is SitecoreTypeConfiguration)
.ToDictionary(x => x.Key, x => x.Value as SitecoreTypeConfiguration);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="GlassDataProvider"/> class.
/// </summary>
public GlassDataProvider()
{
SectionTable = new List<SectionInfo>();
FieldTable = new List<FieldInfo>();
}
/// <summary>
/// Initializes a new instance of the <see cref="GlassDataProvider"/> class.
/// </summary>
/// <param name="databaseName">Name of the database.</param>
/// <param name="context">The context.</param>
public GlassDataProvider(string databaseName, string context)
: this()
{
DatabaseName = databaseName;
ContextName = context;
}
/// <summary>
/// Gets the definition of an item.
/// </summary>
/// <param name="itemId">The item ID.</param>
/// <param name="context">The context.</param>
/// <returns>Sitecore.Data.ItemDefinition.</returns>
public override ItemDefinition GetItemDefinition(ID itemId, CallContext context)
{
if (!_setupComplete)
return base.GetItemDefinition(itemId, context);
var sectiontable = SectionTable.ToList();//prevent "Collection was modified"
var section = sectiontable.FirstOrDefault(x => x.SectionId == itemId);
if (section != null)
{
return new GlassItemDefinition(itemId, section.Name, SectionTemplateId, ID.Null);
}
var fieldtable = FieldTable.ToList();//prevent "Collection was modified"
var field = fieldtable.FirstOrDefault(x => x.FieldId == itemId);
if (field != null)
{
return new GlassItemDefinition(itemId, field.Name, FieldTemplateId, ID.Null);
}
return base.GetItemDefinition(itemId, context);
}
/// <summary>
/// Gets a list of all the language that have been defined
/// in the database.
/// </summary>
/// <param name="context">The context.</param>
/// <returns>LanguageCollection.</returns>
public override LanguageCollection GetLanguages(CallContext context)
{
return GetSqlProvider(this.Database).GetLanguages(context);
}
public override VersionUriList GetItemVersions(ItemDefinition itemDefinition, CallContext context)
{
if (itemDefinition is GlassItemDefinition)
return base.GetItemVersions(itemDefinition, context);
return null;
}
#region GetItemFields
/// <summary>
/// Gets the fields of a specific item version.
/// </summary>
/// <param name="itemDefinition">The item.</param>
/// <param name="versionUri">The version URI.</param>
/// <param name="context">The context.</param>
/// <returns>Sitecore.Data.FieldList.</returns>
public override FieldList GetItemFields(ItemDefinition itemDefinition, VersionUri versionUri, CallContext context)
{
if (!_setupComplete)
return base.GetItemFields(itemDefinition, versionUri, context);
var fields = new FieldList();
var sectionTable = SectionTable.ToList();//prevent "Collection was modified"
var sectionInfo = sectionTable.FirstOrDefault(x => x.SectionId == itemDefinition.ID);
if (sectionInfo != null)
{
GetStandardFields(fields, sectionInfo.SectionSortOrder >= 0 ? sectionInfo.SectionSortOrder : 100);
return fields;
}
var fieldtable = FieldTable.ToList();//prevent "Collection was modified"
var fieldInfo = fieldtable.FirstOrDefault(x => x.FieldId == itemDefinition.ID);
if (fieldInfo != null)
{
GetStandardFields(fields, fieldInfo.FieldSortOrder >= 0 ? fieldInfo.FieldSortOrder : 100);
GetFieldFields(fieldInfo, fields);
return fields;
}
return base.GetItemFields(itemDefinition, versionUri, context);
}
/// <summary>
/// Gets the standard fields.
/// </summary>
/// <param name="fields">The fields.</param>
/// <param name="index">The index.</param>
private void GetStandardFields(FieldList fields, int index)
{
fields.Add(FieldIDs.ReadOnly, "1");
fields.Add(FieldIDs.Sortorder, index.ToString(CultureInfo.InvariantCulture));
}
/// <summary>
/// Gets the field fields.
/// </summary>
/// <param name="info">The info.</param>
/// <param name="fields">The fields.</param>
private void GetFieldFields(FieldInfo info, FieldList fields)
{
if (!string.IsNullOrEmpty(info.Title))
fields.Add(TemplateFieldIDs.Title, info.Title);
fields.Add(TemplateFieldIDs.Type, info.GetFieldType());
if (!string.IsNullOrEmpty(info.Source))
fields.Add(TemplateFieldIDs.Source, info.Source);
fields.Add(TemplateFieldIDs.Shared, info.IsShared ? "1" : "0");
fields.Add(TemplateFieldIDs.Unversioned, info.IsUnversioned ? "1" : "0");
foreach (var fieldFieldValue in info.FieldFieldValues)
{
fields.Add(ID.Parse(fieldFieldValue.Key), fieldFieldValue.Value);
}
fields.Add(TemplateFieldIDs.Validation, info.ValidationRegularExpression ?? "");
fields.Add(TemplateFieldIDs.ValidationText, info.ValidationErrorText ?? "");
if (info.IsRequired)
{
fields.Add(Global.IDs.TemplateFieldIds.QuickActionBarFieldId, Global.IDs.TemplateFieldIds.IsRequiredId);
fields.Add(Global.IDs.TemplateFieldIds.ValidateButtonFieldId, Global.IDs.TemplateFieldIds.IsRequiredId);
fields.Add(Global.IDs.TemplateFieldIds.ValidatorBarFieldId, Global.IDs.TemplateFieldIds.IsRequiredId);
fields.Add(Global.IDs.TemplateFieldIds.WorkflowFieldId, Global.IDs.TemplateFieldIds.IsRequiredId);
}
}
#endregion
#region GetChildIDs
/// <summary>
/// Gets the child ids of an item.
/// </summary>
/// <param name="itemDefinition">The item definition.</param>
/// <param name="context">The context.</param>
/// <returns>Sitecore.Collections.IDList.</returns>
public override IDList GetChildIDs(ItemDefinition itemDefinition, CallContext context)
{
if (!_setupComplete)
return base.GetChildIDs(itemDefinition, context);
if (TypeConfigurations.Any(x => x.Value.TemplateId == itemDefinition.ID))
{
var cls = TypeConfigurations.First(x => x.Value.TemplateId == itemDefinition.ID).Value;
return GetChildIDsTemplate(cls, itemDefinition, context, GetSqlProvider(context.DataManager.Database));
}
var section = SectionTable.FirstOrDefault(x => x.SectionId == itemDefinition.ID);
if (section != null)
{
return GetChildIDsSection(section, context, GetSqlProvider(context.DataManager.Database));
}
return base.GetChildIDs(itemDefinition, context);
}
/// <summary>
/// Gets the child I ds template.
/// </summary>
/// <param name="template">The template.</param>
/// <param name="itemDefinition">The item definition.</param>
/// <param name="context">The context.</param>
/// <param name="sqlProvider">The SQL provider.</param>
/// <returns>
/// IDList.
/// </returns>
private IDList GetChildIDsTemplate(SitecoreTypeConfiguration template, ItemDefinition itemDefinition, CallContext context, DataProvider sqlProvider)
{
var fields = new IDList();
var processed = new List<string>();
var sections = template.Properties
.Where(x => x.PropertyInfo.DeclaringType == template.Type)
.OfType<SitecoreFieldConfiguration>()
.Select(x => new { x.SectionName, x.SectionSortOrder });
//If sitecore contains a section with the same name in the database, use that one instead of creating a new one
var existing = sqlProvider.GetChildIDs(itemDefinition, context).OfType<ID>().Select(id => sqlProvider.GetItemDefinition(id, context))
.Where(item => item.TemplateID == SectionTemplateId).ToList();
foreach (var section in sections)
{
if (processed.Contains(section.SectionName) || section.SectionName.IsNullOrEmpty())
continue;
var record = SectionTable.FirstOrDefault(x => x.TemplateId == itemDefinition.ID && x.Name == section.SectionName);
if (record == null)
{
var exists = existing.FirstOrDefault(def => def.Name.Equals(section.SectionName, StringComparison.InvariantCultureIgnoreCase));
var newId = GetUniqueGuid(itemDefinition.ID + section.SectionName);
record = exists != null ?
new SectionInfo(section.SectionName, exists.ID, itemDefinition.ID, section.SectionSortOrder) { Existing = true } :
new SectionInfo(section.SectionName, new ID(newId), itemDefinition.ID, 100);
SectionTable.Add(record);
}
processed.Add(section.SectionName);
if (!record.Existing)
fields.Add(record.SectionId);
}
//we need to add sections already in the db, 'cause we have to
foreach (var sqlOne in existing.Where(ex => SectionTable.All(s => s.SectionId != ex.ID)))
{
SectionTable.Add(new SectionInfo(sqlOne.Name, sqlOne.ID, itemDefinition.ID, 0) { Existing = true } );
}
return fields;
}
/// <summary>
/// Gets the child I ds section.
/// </summary>
/// <param name="section">The section.</param>
/// <param name="context">The context.</param>
/// <param name="sqlProvider">The SQL provider.</param>
/// <returns>
/// IDList.
/// </returns>
private IDList GetChildIDsSection(SectionInfo section, CallContext context, DataProvider sqlProvider)
{
var config = TypeConfigurations.First(x => x.Value.TemplateId == section.TemplateId);
var cls = config.Value;
var fields = cls.Properties.OfType<SitecoreFieldConfiguration>();
IDList fieldIds = new IDList();
var interfaces = cls.Type.GetInterfaces().Where(i => System.Attribute.IsDefined(i,typeof (Glass.Mapper.Sc.Configuration.Attributes.SitecoreTypeAttribute)));
foreach (var field in fields)
{
//fix: added check on interfaces, if field resides on interface then skip here
var propertyFromInterface = interfaces.FirstOrDefault(inter => inter.GetProperty(field.PropertyInfo.Name) != null
&& inter.GetProperty(field.PropertyInfo.Name).GetCustomAttributes(typeof(SitecoreFieldAttribute), false).Any());
if (field.PropertyInfo.DeclaringType != cls.Type || propertyFromInterface != null)
continue;
if (field.CodeFirst && field.SectionName == section.Name && !ID.IsNullOrEmpty(field.FieldId))
{
var fieldtable = FieldTable.ToList();//prevent "Collection was modified"
var record = fieldtable.FirstOrDefault(x => x.FieldId == field.FieldId);
//test if the fields exists in the database: if so, we're using codefirst now, so remove it.
var existing = sqlProvider.GetItemDefinition(field.FieldId, context);
if (existing != null)
{
using (new SecurityDisabler())
{
if (DisableItemHandlerWhenDeletingFields)
{
using (new DisableItemHandler())
sqlProvider.DeleteItem(existing, context);
}
else
{
sqlProvider.DeleteItem(existing, context);
}
}
}
if (record == null)
{
string fieldName = field.FieldName.IsNullOrEmpty() ? field.PropertyInfo.Name : field.FieldName;
record = new FieldInfo(field.FieldId, section.SectionId, fieldName, field.FieldType, field.CustomFieldType,
field.FieldSource, field.FieldTitle, field.IsShared, field.IsUnversioned,
field.FieldSortOrder, field.ValidationRegularExpression,
field.ValidationErrorText, field.IsRequired);
if (field.FieldValueConfigs != null && field.FieldValueConfigs.Any())
{
foreach (var ffv in field.FieldValueConfigs)
{
record.FieldFieldValues.Add(ffv.FieldId, ffv.FieldValue);
}
}
}
fieldIds.Add(record.FieldId);
FieldTable.Add(record);
}
}
return fieldIds;
}
#endregion
/// <summary>
/// Gets the parent ID of an item.
/// </summary>
/// <param name="itemDefinition">The item definition.</param>
/// <param name="context">The context.</param>
/// <returns>Sitecore.Data.ID.</returns>
public override ID GetParentID(ItemDefinition itemDefinition, CallContext context)
{
if (!_setupComplete)
return base.GetParentID(itemDefinition, context);
var sectionTable = SectionTable.ToList();//prevent "Collection was modified"
var section = sectionTable.FirstOrDefault(x => x.SectionId == itemDefinition.ID);
if (section != null)
{
return section.TemplateId;
}
var fieldtable = FieldTable.ToList();//prevent "Collection was modified"
var field = fieldtable.FirstOrDefault(x => x.FieldId == itemDefinition.ID);
if (field != null)
{
return field.SectionId;
}
return base.GetParentID(itemDefinition, context);
}
/// <summary>
/// Creates a item.
/// </summary>
/// <param name="itemId">The item ID.</param>
/// <param name="itemName">Name of the item.</param>
/// <param name="templateId">The template ID.</param>
/// <param name="parent">The parent.</param>
/// <param name="context">The context.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
public override bool CreateItem(ID itemId, string itemName, ID templateId, ItemDefinition parent, CallContext context)
{
return false;
}
/// <summary>
/// Saves an item.
/// </summary>
/// <param name="itemDefinition">The item definition.</param>
/// <param name="changes">The changes.</param>
/// <param name="context">The context.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
public override bool SaveItem(ItemDefinition itemDefinition, ItemChanges changes, CallContext context)
{
return false;
}
/// <summary>
/// Deletes an item.
/// </summary>
/// <param name="itemDefinition">The item definition.</param>
/// <param name="context">The context.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
public override bool DeleteItem(ItemDefinition itemDefinition, CallContext context)
{
return false;
}
/// <summary>
/// Setups the specified context.
/// </summary>
/// <param name="db">The db.</param>
public void Initialise(Database db)
{
if (_setupComplete || _setupProcessing)
return;
lock (_setupLock)
{
try
{
if (_setupComplete || _setupProcessing)
return;
Sitecore.Diagnostics.Log.Info("Started CodeFirst setup " + db.Name, this);
_setupProcessing = true;
var manager = new DataManager(db);
var context = new CallContext(manager, db.GetDataProviders().Count());
var sqlProvider = GetSqlProvider(db);
var glassFolder = GetGlassTemplateFolder(sqlProvider, context);
if (CurrentContext != null)
{
foreach (var cls in TypeConfigurations.Where(x => x.Value.CodeFirst))
{
var templateDefinition = sqlProvider.GetItemDefinition(cls.Value.TemplateId, context);
if (templateDefinition == ItemDefinition.Empty || templateDefinition == null)
{
var containingFolder = GetTemplateFolder(cls.Key.Namespace, glassFolder, sqlProvider, context);
templateDefinition = CreateTemplateItem(db, cls.Value, cls.Key, sqlProvider, containingFolder, context);
}
BaseTemplateChecks(templateDefinition, cls.Value, db);
//initialize sections and children
foreach (ID sectionId in GetChildIDsTemplate(cls.Value, templateDefinition, context, sqlProvider))
{
GetChildIDsSection(SectionTable.First(s => s.SectionId == sectionId), context, sqlProvider);
}
}
if (Settings.GetBoolSetting("AutomaticallyRemoveDeletedTemplates", true))
RemoveDeletedClasses(glassFolder, sqlProvider, context);
ClearCaches(db);
}
Sitecore.Diagnostics.Log.Info("Finished CodeFirst setup " + db.Name, this);
}
catch (Exception ex)
{
Sitecore.Diagnostics.Log.Error("CodeFirst error " + ex.Message, ex, this);
throw;
}
finally
{
_setupComplete = true;
}
}
}
/// <summary>
/// Creates the template item.
/// </summary>
/// <param name="db">The db.</param>
/// <param name="config">The config.</param>
/// <param name="type">The type.</param>
/// <param name="sqlDataProvider">The SQL data provider.</param>
/// <param name="containingFolder">The containing folder.</param>
/// <param name="context">The context.</param>
/// <returns></returns>
/// <exception cref="Sitecore.Exceptions.RequiredObjectIsNullException">TemplateItem is null for ID {0}.Formatted(templateDefinition.ID)</exception>
private ItemDefinition CreateTemplateItem(
Database db,
SitecoreTypeConfiguration config,
Type type,
DataProvider sqlDataProvider,
ItemDefinition containingFolder,
CallContext context)
{
//create the template in Sitecore
string templateName = string.IsNullOrEmpty(config.TemplateName) ? type.Name : config.TemplateName;
sqlDataProvider.CreateItem(config.TemplateId, templateName, TemplateTemplateId, containingFolder, context);
var templateDefinition = sqlDataProvider.GetItemDefinition(config.TemplateId, context);
ClearCaches(db);
var templateItem = db.GetItem(templateDefinition.ID);
if (templateItem == null)
throw new RequiredObjectIsNullException("TemplateItem is null for ID {0}".Formatted(templateDefinition.ID));
using (new ItemEditing(templateItem, true))
{
templateItem["__Base template"] = "{1930BBEB-7805-471A-A3BE-4858AC7CF696}";
}
return templateDefinition;
}
/// <summary>
/// Gets the template folder that the class template should be created in using the classes
/// namespace.
/// </summary>
/// <param name="nameSpace"></param>
/// <param name="defaultFolder"></param>
/// <param name="sqlDataProvider"></param>
/// <param name="context"></param>
/// <returns></returns>
private ItemDefinition GetTemplateFolder(string nameSpace, ItemDefinition defaultFolder, DataProvider sqlDataProvider, CallContext context)
{
//setup folders
IEnumerable<string> namespaces = nameSpace.Split('.');
namespaces = namespaces.SkipWhile(x => x != "Templates").Skip(1);
ItemDefinition containingFolder = defaultFolder;
foreach (var ns in namespaces)
{
var children = sqlDataProvider.GetChildIDs(containingFolder, context);
ItemDefinition found = null;
foreach (ID child in children)
{
if (!ID.IsNullOrEmpty(child))
{
var childDef = sqlDataProvider.GetItemDefinition(child, context);
if (childDef.Name == ns)
found = childDef;
}
}
if (found == null)
{
ID newId = ID.NewID;
sqlDataProvider.CreateItem(newId, ns, FolderTemplateId, containingFolder, context);
found = sqlDataProvider.GetItemDefinition(newId, context);
}
containingFolder = found;
}
if (containingFolder == null)
{
Sitecore.Diagnostics.Log.Error("Failed to load containing folder {0}".Formatted(nameSpace), this);
throw new RequiredObjectIsNullException("Failed to load containing folder {0}".Formatted(nameSpace));
}
return containingFolder;
}
/// <summary>
/// Clears the all caches on the database
/// </summary>
/// <param name="db"></param>
private void ClearCaches(Database db)
{
db.Caches.DataCache.Clear();
db.Caches.ItemCache.Clear();
db.Caches.ItemPathsCache.Clear();
db.Caches.StandardValuesCache.Clear();
db.Caches.PathCache.Clear();
}
/// <summary>
/// Gets the base SQL provider that will store physical items
/// </summary>
/// <param name="db"></param>
/// <returns></returns>
private DataProvider GetSqlProvider(Database db)
{
var providers = db.GetDataProviders();
var provider = providers.FirstOrDefault(x => x is SqlDataProvider);
if (provider == null)
{
Sitecore.Diagnostics.Log.Error("Failed to find SqlDataProvider", this);
throw new RequiredObjectIsNullException("Failed to find SqlDataProvider");
}
return provider;
}
/// <summary>
/// Creates the item /sitecore/templates/glasstemplates
/// </summary>
/// <param name="provider"></param>
/// <param name="context"></param>
/// <returns></returns>
private ItemDefinition GetGlassTemplateFolder(DataProvider provider, CallContext context)
{
var templateFolder = provider.GetItemDefinition(TemplateFolderId, context);
var glassFolder = provider.GetItemDefinition(GlassFolderId, context);
if (glassFolder == ItemDefinition.Empty || glassFolder == null)
{
provider.CreateItem(GlassFolderId, "GlassTemplates", FolderTemplateId, templateFolder, context);
glassFolder = provider.GetItemDefinition(GlassFolderId, context);
}
if (glassFolder == null)
{
Sitecore.Diagnostics.Log.Error("Failed to find GlassTemplates folder", this);
throw new RequiredObjectIsNullException("Failed to find GlassTemplates folder");
}
return glassFolder;
}
/// <summary>
/// Check a folder and all sub folders in Sitecore for templates
/// </summary>
/// <param name="folder">The folder.</param>
/// <param name="sqlDataProvider">The SQL data provider.</param>
/// <param name="context">The context.</param>
/// <returns>
/// True of the folder is deleted itself.
/// </returns>
private bool RemoveDeletedClasses(ItemDefinition folder, DataProvider sqlDataProvider, CallContext context)
{
if (folder == null) throw new ArgumentNullException("folder");
if (sqlDataProvider == null) throw new ArgumentNullException("sqlDataProvider");
if (context == null) throw new ArgumentNullException("context");
var childIds = sqlDataProvider.GetChildIDs(folder, context);
//check child items
foreach (ID childId in childIds.ToArray())
{
var childDefinition = sqlDataProvider.GetItemDefinition(childId, context);
//if child is template check the template still exists in the code base
if (childDefinition.TemplateID == TemplateTemplateId)
{
if (TypeConfigurations.Any(x => x.Value.TemplateId == childDefinition.ID && x.Value.CodeFirst))
continue;
sqlDataProvider.DeleteItem(childDefinition, context);
childIds.Remove(childDefinition.ID);
}
// if the child is a folder check the children of the folder
else if (childDefinition.TemplateID == FolderTemplateId)
{
//if the folder itself is deleted then remove from the parent
if (RemoveDeletedClasses(childDefinition, sqlDataProvider, context))
{
childIds.Remove(childDefinition.ID);
}
}
}
//if there are no children left delete the folder
if (childIds.Count == 0 && folder.ID != GlassFolderId)
{
sqlDataProvider.DeleteItem(folder, context);
return true;
}
return false;
}
/// <summary>
/// Bases the template checks.
/// </summary>
/// <param name="template">The template.</param>
/// <param name="config">The config.</param>
/// <param name="db">The database.</param>
private void BaseTemplateChecks(
ItemDefinition template,
SitecoreTypeConfiguration config,
Database db)
{
//check base templates
var templateItem = db.GetItem(template.ID);
var baseTemplatesField = templateItem[FieldIDs.BaseTemplate];
var sb = new StringBuilder(baseTemplatesField);
Sitecore.Diagnostics.Log.Info("Type {0}".Formatted(config.Type.FullName), this);
Action<Type> idCheck = type =>
{
Sitecore.Diagnostics.Log.Info("ID Check {0}".Formatted(type.FullName), this);
if (!TypeConfigurations.ContainsKey(type)) return;
var baseConfig = TypeConfigurations[type];
if (baseConfig != null && baseConfig.TemplateId.Guid != Guid.Empty)
{
if (!baseTemplatesField.Contains(baseConfig.TemplateId.ToString()))
{
sb.Append("|{0}".Formatted(baseConfig.TemplateId));
}
}
};
Type baseType = config.Type.BaseType;
while (baseType != null)
{
idCheck(baseType);
baseType = baseType.BaseType;
}
config.Type.GetInterfaces().ForEach(idCheck);
//dirty fix for circular template inheritance
var baseTemplates = sb.ToString().Split('|').ToList();
baseTemplates.Remove(config.TemplateId.ToString());
sb.Clear();
sb.Append(string.Join("|", baseTemplates));
if (baseTemplatesField != sb.ToString())
{
templateItem.Editing.BeginEdit();
templateItem[FieldIDs.BaseTemplate] = sb.ToString();
templateItem.Editing.EndEdit();
}
}
public static Guid GetUniqueGuid(string input)
{
//this code will generate a unique Guid for a string (unique with a 2^20.96 probability of a collision)
//http://stackoverflow.com/questions/2190890/how-can-i-generate-guid-for-a-string-values
using (MD5 md5 = MD5.Create())
{
byte[] hash = md5.ComputeHash(Encoding.Default.GetBytes(input));
var guid = new Guid(hash);
return guid == Guid.Empty ? Guid.NewGuid() : guid;
}
}
}
}
| |
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 iOS.WebServiceExample.WebAPI.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>();
}
/// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and 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))
{
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="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <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,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[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;
}
}
}
| |
/*
* 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.Globalization;
using System.Reflection;
using System.Text;
using System.Threading;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.ScriptEngine.Shared;
namespace OpenSim.ScriptEngine.Components.DotNetEngine.Scheduler
{
public partial class ScriptManager
{
private Queue<LoadUnloadStructure> LUQueue = new Queue<LoadUnloadStructure>();
private int LoadUnloadMaxQueueSize = 500;
private Object scriptLock = new Object();
//private Dictionary<InstanceData, DetectParams[]> detparms = new Dictionary<InstanceData, DetectParams[]>();
// Load/Unload structure
public void AddScript(ScriptStructure script)
{
lock (LUQueue)
{
if ((LUQueue.Count >= LoadUnloadMaxQueueSize))
{
m_log.ErrorFormat("[{0}] ERROR: Load queue count is at {1} of max {2}. Ignoring load request for script LocalID: {3}, ItemID: {4}.",
Name, LUQueue.Count, LoadUnloadMaxQueueSize, script.LocalID, script.ItemID);
return;
}
LoadUnloadStructure ls = new LoadUnloadStructure();
ls.Script = script;
ls.Action = LoadUnloadStructure.LUType.Load;
LUQueue.Enqueue(ls);
}
}
public void RemoveScript(uint localID, UUID itemID)
{
LoadUnloadStructure ls = new LoadUnloadStructure();
// See if we can find script
if (!TryGetScript(localID, itemID, ref ls.Script))
{
// Set manually
ls.Script.LocalID = localID;
ls.Script.ItemID = itemID;
}
ls.Script.StartParam = 0;
ls.Action = LoadUnloadStructure.LUType.Unload;
ls.PostOnRez = false;
lock (LUQueue)
{
LUQueue.Enqueue(ls);
}
}
internal bool DoScriptLoadUnload()
{
bool ret = false;
// if (!m_started)
// return;
lock (LUQueue)
{
if (LUQueue.Count > 0)
{
LoadUnloadStructure item = LUQueue.Dequeue();
ret = true;
if (item.Action == LoadUnloadStructure.LUType.Unload)
{
_StopScript(item.Script.LocalID, item.Script.ItemID);
RemoveScript(item.Script.LocalID, item.Script.ItemID);
}
else if (item.Action == LoadUnloadStructure.LUType.Load)
{
m_log.DebugFormat("[{0}] Loading script", Name);
_StartScript(item);
}
}
}
return ret;
}
//public void _StartScript(uint localID, UUID itemID, string Script, int startParam, bool postOnRez)
private void _StartScript(LoadUnloadStructure ScriptObject)
{
m_log.DebugFormat(
"[{0}]: ScriptManager StartScript: localID: {1}, itemID: {2}",
Name, ScriptObject.Script.LocalID, ScriptObject.Script.ItemID);
// We will initialize and start the script.
// It will be up to the script itself to hook up the correct events.
SceneObjectPart m_host = ScriptObject.Script.RegionInfo.Scene.GetSceneObjectPart(ScriptObject.Script.LocalID);
if (null == m_host)
{
m_log.ErrorFormat(
"[{0}]: Could not find scene object part corresponding " +
"to localID {1} to start script",
Name, ScriptObject.Script.LocalID);
return;
}
//UUID assetID = UUID.Zero;
TaskInventoryItem taskInventoryItem = new TaskInventoryItem();
//if (m_host.TaskInventory.TryGetValue(ScriptObject.Script.ItemID, out taskInventoryItem))
// assetID = taskInventoryItem.AssetID;
ScenePresence presence =
ScriptObject.Script.RegionInfo.Scene.GetScenePresence(taskInventoryItem.OwnerID);
CultureInfo USCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = USCulture;
try
{
//
// Compile script to an assembly
//
//TODO: DEBUG
BaseClassFactory.MakeBaseClass(ScriptObject.Script);
m_log.DebugFormat("[{0}] Compiling script {1}", Name, ScriptObject.Script.Name);
string fileName = "";
try
{
IScriptCompiler compiler =
ScriptObject.Script.RegionInfo.FindCompiler(ScriptObject.Script.ScriptMetaData);
//RegionInfoStructure currentRegionInfo = ScriptObject.Script.RegionInfo;
fileName = compiler.Compile(ScriptObject.Script.ScriptMetaData,
ref ScriptObject.Script.Source);
ScriptObject.Script.AssemblyFileName = fileName;
}
catch (Exception e)
{
m_log.ErrorFormat("[{0}] Internal error while compiling \"{1}\": {2}", Name, ScriptObject.Script.Name, e.ToString());
}
m_log.DebugFormat("[{0}] Compiled \"{1}\" to assembly: \"{2}\".", Name, ScriptObject.Script.Name, fileName);
// Add it to our script memstruct
MemAddScript(ScriptObject.Script);
ScriptAssemblies.IScript CompiledScript;
CompiledScript = CurrentRegion.ScriptLoader.LoadScript(ScriptObject.Script);
ScriptObject.Script.State = "default";
ScriptObject.Script.ScriptObject = CompiledScript;
ScriptObject.Script.Disabled = false;
ScriptObject.Script.Running = true;
//id.LineMap = LSLCompiler.LineMap();
//id.Script = CompiledScript;
//id.Source = item.Script.Script;
//item.StartParam = startParam;
// TODO: Fire the first start-event
//int eventFlags =
// m_scriptEngine.m_ScriptManager.GetStateEventFlags(
// localID, itemID);
//m_host.SetScriptEvents(itemID, eventFlags);
ScriptObject.Script.RegionInfo.Executors_Execute(ScriptObject.Script,
new EventParams(ScriptObject.Script.LocalID, ScriptObject.Script.ItemID, "state_entry", new object[] { }, new Region.ScriptEngine.Shared.DetectParams[0])
);
if (ScriptObject.PostOnRez)
{
ScriptObject.Script.RegionInfo.Executors_Execute(ScriptObject.Script,
new EventParams(ScriptObject.Script.LocalID, "on_rez", new object[]
{new Region.ScriptEngine.Shared.LSL_Types.LSLInteger(ScriptObject.StartParam)
}, new Region.ScriptEngine.Shared.DetectParams[0]));
}
}
catch (Exception e) // LEGIT: User Scripting
{
if (presence != null && (!ScriptObject.PostOnRez))
presence.ControllingClient.SendAgentAlertMessage(
"Script saved with errors, check debug window!",
false);
try
{
// DISPLAY ERROR INWORLD
string text = "Error compiling script:\n" +
e.Message.ToString();
if (text.Length > 1100)
text = text.Substring(0, 1099);
ScriptObject.Script.RegionInfo.Scene.SimChat(Utils.StringToBytes(text),
ChatTypeEnum.DebugChannel, 2147483647,
m_host.AbsolutePosition, m_host.Name, m_host.UUID,
false);
}
catch (Exception e2) // LEGIT: User Scripting
{
m_log.Error("[" +
Name +
"]: Error displaying error in-world: " +
e2.ToString());
m_log.Error("[" +
Name + "]: " +
"Errormessage: Error compiling script:\r\n" +
e2.Message.ToString());
}
}
}
public void _StopScript(uint localID, UUID itemID)
{
ScriptStructure ss = new ScriptStructure();
if (!TryGetScript(localID, itemID, ref ss))
return;
m_log.DebugFormat("[{0}] Unloading script", Name);
// Stop long command on script
//AsyncCommandManager.RemoveScript(ss);
try
{
// Get AppDomain
// Tell script not to accept new requests
ss.Running = false;
ss.Disabled = true;
//AppDomain ad = ss.AppDomain;
// Remove from internal structure
MemRemoveScript(localID, itemID);
// TODO: Tell AppDomain that we have stopped script
}
catch (Exception e) // LEGIT: User Scripting
{
m_log.Error("[" +
Name +
"]: Exception stopping script localID: " +
localID + " LLUID: " + itemID.ToString() +
": " + e.ToString());
}
}
}
}
| |
//------------------------------------------------------------------------------
// Symbooglix
//
//
// Copyright 2014-2017 Daniel Liew
//
// This file is licensed under the MIT license.
// See LICENSE.txt for details.
//------------------------------------------------------------------------------
using System;
using System.IO;
using Microsoft.Boogie;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
namespace Symbooglix
{
public interface ITerminationType
{
ExecutionState State
{
get;
}
ProgramLocation ExitLocation
{
get;
}
string GetMessage();
}
public abstract class TerminationTypeWithSatAndUnsatExpr : ITerminationType
{
protected TerminationTypeWithSatAndUnsatExpr()
{
this.ConditionForSat = null;
this.ConditionForUnsat = null;
}
// This is the condition that could be added to the ExecutionState's
// constraints and would be satisfiable. This is intended to be used
// for getting a model from the solver
// If the Expr is not available then this will return null.
public Expr ConditionForSat
{
get;
set;
}
// This is the condition that could be added to an ExecutionState's
// constraints to make them unsatisfiable. This is intended to be used
// to determine the unsat core.
// If the Expr is not available then this will return null.
public Expr ConditionForUnsat
{
get;
set;
}
public abstract string GetMessage();
public ExecutionState State
{
get;
internal set;
}
public ProgramLocation ExitLocation
{
get;
internal set;
}
}
public class TerminatedWithoutError : ITerminationType
{
public TerminatedWithoutError(ReturnCmd location)
{
this.ExitLocation = new ProgramLocation(location);
}
public string GetMessage()
{
Debug.Assert(ExitLocation.IsTransferCmd && ExitLocation.AsTransferCmd is ReturnCmd);
var returnCmd = ExitLocation.AsTransferCmd as ReturnCmd;
return "Terminated without error at " +
returnCmd.tok.filename + ":" +
returnCmd.tok.line + " " +
returnCmd.GetProgramLocation().Line;
}
public ExecutionState State
{
get;
internal set;
}
public ProgramLocation ExitLocation
{
get;
private set;
}
}
public class TerminatedAtFailingAssert : TerminationTypeWithSatAndUnsatExpr
{
public TerminatedAtFailingAssert(AssertCmd location)
{
this.ExitLocation = new ProgramLocation(location);
}
public override string GetMessage()
{
Debug.Assert(ExitLocation.IsCmd && ExitLocation.AsCmd is AssertCmd);
var assertCmd = ExitLocation.AsCmd as AssertCmd;
return "Terminated with assertion failure " +
assertCmd.tok.filename + ":" +
assertCmd.tok.line + ": " +
assertCmd.ToString().TrimEnd('\n');
}
}
public class TerminatedAtUnsatisfiableAssume : TerminationTypeWithSatAndUnsatExpr
{
public TerminatedAtUnsatisfiableAssume(AssumeCmd location)
{
this.ExitLocation = new ProgramLocation(location);
}
public override string GetMessage()
{
Debug.Assert(ExitLocation.IsCmd && ExitLocation.AsCmd is AssumeCmd);
var assumeCmd = ExitLocation.AsCmd as AssumeCmd;
return "Terminated with unsatisfiable assumption " +
assumeCmd.tok.filename + ":" +
assumeCmd.tok.line + ": " +
assumeCmd.ToString().TrimEnd('\n');
}
}
// This is only for requires on program entry points
public class TerminatedAtUnsatisfiableEntryRequires : TerminationTypeWithSatAndUnsatExpr
{
public TerminatedAtUnsatisfiableEntryRequires(Requires requires)
{
this.ExitLocation = new ProgramLocation(requires);
}
public override string GetMessage()
{
Debug.Assert(ExitLocation.IsRequires);
var requires = ExitLocation.AsRequires;
return "Terminated at program entry point at an unsatisfiable requires " +
requires.tok.filename + ":" +
requires.tok.line + ": " +
requires.Condition.ToString().TrimEnd('\n');
}
}
public class TerminatedAtFailingRequires : TerminationTypeWithSatAndUnsatExpr
{
public TerminatedAtFailingRequires(Requires requires)
{
this.ExitLocation = new ProgramLocation(requires);
}
public override string GetMessage()
{
Debug.Assert(ExitLocation.IsRequires);
var requires = ExitLocation.AsRequires;
return "Terminated with failing requires " +
requires.tok.filename + ":" +
requires.tok.line + ": " +
requires.Condition.ToString().TrimEnd('\n');
}
}
public class TerminatedAtFailingEnsures : TerminationTypeWithSatAndUnsatExpr
{
public TerminatedAtFailingEnsures(Ensures ensures)
{
this.ExitLocation = new ProgramLocation(ensures);
}
public override string GetMessage()
{
Debug.Assert(ExitLocation.IsEnsures);
var ensures = ExitLocation.AsEnsures;
return "Terminated with failing ensures " +
ensures.tok.filename + ":" +
ensures.tok.line + ": " +
ensures.Condition.ToString().TrimEnd('\n');
}
}
// This is for Ensures that we try assume when calling into
// a procedure
public class TerminatedAtUnsatisfiableEnsures : TerminationTypeWithSatAndUnsatExpr
{
public TerminatedAtUnsatisfiableEnsures(Ensures ensures)
{
this.ExitLocation = new ProgramLocation(ensures);
}
public override string GetMessage()
{
Debug.Assert(ExitLocation.IsEnsures);
var ensures = ExitLocation.AsEnsures;
return "Terminated with unsatisfiable ensures " +
ensures.tok.filename + ":" +
ensures.tok.line + ": " +
ensures.Condition.ToString().TrimEnd('\n');
}
}
public class TerminatedAtUnsatisfiableAxiom : TerminationTypeWithSatAndUnsatExpr
{
public TerminatedAtUnsatisfiableAxiom(Axiom axiom)
{
this.ExitLocation = new ProgramLocation(axiom);
}
public override string GetMessage ()
{
Debug.Assert(ExitLocation.IsAxiom);
var axiom = ExitLocation.AsAxiom;
return "Terminated with unsatisfiable axiom " +
axiom.tok.filename + ":" +
axiom.tok.line + ": " +
axiom.Expr.ToString();
}
}
public class TerminatedWithDisallowedSpeculativePath : ITerminationType
{
public string GetMessage()
{
return "Disallowed speculative path. Starting at " + ExitLocation.ToString();
}
public TerminatedWithDisallowedSpeculativePath(ProgramLocation loc)
{
this.ExitLocation = loc;
}
public ExecutionState State
{
get;
internal set;
}
public ProgramLocation ExitLocation
{
get;
private set;
}
}
public class TerminatedAtGotoWithUnsatisfiableTargets : ITerminationType
{
public TerminatedAtGotoWithUnsatisfiableTargets(GotoCmd gotoCmd)
{
this.ExitLocation = gotoCmd.GetProgramLocation();
}
public string GetMessage()
{
Debug.Assert(ExitLocation.IsTransferCmd && ExitLocation.AsTransferCmd is GotoCmd);
var gotoCmd = ExitLocation.AsTransferCmd as GotoCmd;
string line = "";
using (var SW = new StringWriter())
{
gotoCmd.Emit(new TokenTextWriter("", SW, /*setTokens=*/false, /*pretty=*/false), 0);
line = SW.ToString().TrimEnd('\n');
}
return "Terminated with no satisfiable path available from goto " +
gotoCmd.tok.filename + ":" +
gotoCmd.tok.line + " " +
line;
}
public ExecutionState State
{
get;
internal set;
}
public ProgramLocation ExitLocation
{
get;
internal set;
}
}
public class TerminatedWithDisallowedExplicitBranchDepth : ITerminationType
{
public TerminatedWithDisallowedExplicitBranchDepth(ProgramLocation location)
{
Debug.Assert(location != null, "location cannot be null");
this.ExitLocation = location;
State = null;
}
public string GetMessage()
{
var depth = State != null ? ( State.ExplicitBranchDepth ) : -1;
var s = "Terminated with Explicit branch depth exceeded (";
if (depth == -1)
s += "unknown";
else
s += depth.ToString();
s += ") at " + ExitLocation.ToString();
return s;
}
public ExecutionState State
{
get;
internal set;
}
public ProgramLocation ExitLocation
{
get;
internal set;
}
}
public class TerminatedWithDisallowedLoopBound : ITerminationType
{
public TerminatedWithDisallowedLoopBound(ProgramLocation location, BigInteger loopBound)
{
Debug.Assert(location != null, "location cannot be null");
this.LoopBound = loopBound;
this.ExitLocation = location;
State = null;
}
public string GetMessage()
{
String msg = String.Format("Terminated with loop bound {0} exceeded at {1}:{2}",
LoopBound,
ExitLocation.FileName,
ExitLocation.LineNumber);
return msg;
}
public ExecutionState State {
get;
internal set;
}
public ProgramLocation ExitLocation {
get;
internal set;
}
public BigInteger LoopBound {
get;
internal set;
}
}
public class TerminatedWithUnsatisfiableUniqueAttribute : TerminationTypeWithSatAndUnsatExpr
{
IList<Constant> UniqueVariables;
public TerminatedWithUnsatisfiableUniqueAttribute(IList<Constant> variables)
{
Debug.Assert(variables.Count > 1);
// Just make the exit location the first variable
this.ExitLocation = variables[0].GetProgramLocation();
this.UniqueVariables = variables;
}
public override string GetMessage()
{
var SB = new StringBuilder();
var theType = UniqueVariables[0].TypedIdent.Type;
SB.Append("Terminated with unsatisfiable unique attribute for variables of type ");
SB.Append(theType.ToString());
return SB.ToString();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ApiManagement
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// AuthorizationServerOperations operations.
/// </summary>
public partial interface IAuthorizationServerOperations
{
/// <summary>
/// Lists a collection of authorization servers defined within a
/// service instance.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to 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<AuthorizationServerContract>>> ListByServiceWithHttpMessagesAsync(string resourceGroupName, string serviceName, ODataQuery<AuthorizationServerContract> odataQuery = default(ODataQuery<AuthorizationServerContract>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the details of the authorization server specified by its
/// identifier.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='authsid'>
/// Identifier of the authorization server.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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<AuthorizationServerContract,AuthorizationServerGetHeaders>> GetWithHttpMessagesAsync(string resourceGroupName, string serviceName, string authsid, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates new authorization server or updates an existing
/// authorization server.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='authsid'>
/// Identifier of the authorization server.
/// </param>
/// <param name='parameters'>
/// Create or update parameters.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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<AuthorizationServerContract>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, string authsid, AuthorizationServerContract parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the details of the authorization server specified by its
/// identifier.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='authsid'>
/// Identifier of the authorization server.
/// </param>
/// <param name='parameters'>
/// OAuth2 Server settings Update parameters.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the authorization server to
/// update. A value of "*" can be used for If-Match to unconditionally
/// apply the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> UpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, string authsid, AuthorizationServerUpdateContract parameters, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes specific authorization server instance.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='authsid'>
/// Identifier of the authorization server.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the authentication server to
/// delete. A value of "*" can be used for If-Match to unconditionally
/// apply the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serviceName, string authsid, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists a collection of authorization servers defined within a
/// service instance.
/// </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<AuthorizationServerContract>>> ListByServiceNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeRefactorings.GenerateFromMembers.GenerateEqualsAndGetHashCode;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.GenerateFromMembers.GenerateEqualsAndGetHashCode
{
public class GenerateEqualsAndGetHashCodeTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace)
{
return new GenerateEqualsAndGetHashCodeCodeRefactoringProvider();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsSingleField()
{
await TestAsync(
@"using System . Collections . Generic ; class Program { [|int a ;|] } ",
@"using System . Collections . Generic ; class Program { int a ; public override bool Equals ( object obj ) { var program = obj as Program ; return program != null && EqualityComparer < int > . Default . Equals ( a , program . a ) ; } } ",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsLongName()
{
await TestAsync(
@"using System . Collections . Generic ; class ReallyLongName { [|int a ;|] } ",
@"using System . Collections . Generic ; class ReallyLongName { int a ; public override bool Equals ( object obj ) { var name = obj as ReallyLongName ; return name != null && EqualityComparer < int > . Default . Equals ( a , name . a ) ; } } ",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsKeywordName()
{
await TestAsync(
@"using System . Collections . Generic ; class ReallyLongLong { [|long a ;|] } ",
@"using System . Collections . Generic ; class ReallyLongLong { long a ; public override bool Equals ( object obj ) { var @long = obj as ReallyLongLong ; return @long != null && EqualityComparer < long > . Default . Equals ( a , @long . a ) ; } } ",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsProperty()
{
await TestAsync(
@"using System . Collections . Generic ; class ReallyLongName { [|int a ; string B { get ; }|] } ",
@"using System . Collections . Generic ; class ReallyLongName { int a ; string B { get ; } public override bool Equals ( object obj ) { var name = obj as ReallyLongName ; return name != null && EqualityComparer < int > . Default . Equals ( a , name . a ) && EqualityComparer < string > . Default . Equals ( B , name . B ) ; } } ",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsBaseTypeWithNoEquals()
{
await TestAsync(
@"class Base { } class Program : Base { [|int i ;|] } ",
@"using System . Collections . Generic; class Base { } class Program : Base { int i ; public override bool Equals ( object obj ) { var program = obj as Program ; return program != null && EqualityComparer < int > . Default . Equals ( i , program . i ) ; } } ",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsBaseWithOverriddenEquals()
{
await TestAsync(
@"using System . Collections . Generic ; class Base { public override bool Equals ( object o ) { } } class Program : Base { [|int i ; string S { get ; }|] } ",
@"using System . Collections . Generic ; class Base { public override bool Equals ( object o ) { } } class Program : Base { int i ; string S { get ; } public override bool Equals ( object obj ) { var program = obj as Program ; return program != null && base . Equals ( obj ) && EqualityComparer < int > . Default . Equals ( i , program . i ) && EqualityComparer < string > . Default . Equals ( S , program . S ) ; } } ",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsOverriddenDeepBase()
{
await TestAsync(
@"using System . Collections . Generic ; class Base { public override bool Equals ( object o ) { } } class Middle : Base { } class Program : Middle { [|int i ; string S { get ; }|] } ",
@"using System . Collections . Generic ; class Base { public override bool Equals ( object o ) { } } class Middle : Base { } class Program : Middle { int i ; string S { get ; } public override bool Equals ( object obj ) { var program = obj as Program ; return program != null && base . Equals ( obj ) && EqualityComparer < int > . Default . Equals ( i , program . i ) && EqualityComparer < string > . Default . Equals ( S , program . S ) ; } } ",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsStruct()
{
await TestAsync(
@"using System . Collections . Generic ; struct ReallyLongName { [|int i ; string S { get ; }|] } ",
@"using System . Collections . Generic ; struct ReallyLongName { int i ; string S { get ; } public override bool Equals ( object obj ) { if ( ! ( obj is ReallyLongName ) ) { return false ; } var name = ( ReallyLongName ) obj ; return EqualityComparer < int > . Default . Equals ( i , name . i ) && EqualityComparer < string > . Default . Equals ( S , name . S ) ; } } ",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestEqualsGenericType()
{
var code = @"
using System.Collections.Generic;
class Program<T>
{
[|int i;|]
}
";
var expected = @"
using System.Collections.Generic;
class Program<T>
{
int i;
public override bool Equals(object obj)
{
var program = obj as Program<T>;
return program != null && EqualityComparer<int>.Default.Equals(i, program.i);
}
}
";
await TestAsync(code, expected, compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeSingleField()
{
await TestAsync(
@"using System . Collections . Generic ; class Program { [|int i ;|] } ",
@"using System . Collections . Generic ; class Program { int i ; public override int GetHashCode ( ) { return EqualityComparer < int > . Default . GetHashCode ( i ) ; } } ",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeTypeParameter()
{
await TestAsync(
@"using System . Collections . Generic ; class Program < T > { [|T i ;|] } ",
@"using System . Collections . Generic ; class Program < T > { T i ; public override int GetHashCode ( ) { return EqualityComparer < T > . Default . GetHashCode ( i ) ; } } ",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeGenericType()
{
await TestAsync(
@"using System . Collections . Generic ; class Program < T > { [|Program < T > i ;|] } ",
@"using System . Collections . Generic ; class Program < T > { Program < T > i ; public override int GetHashCode ( ) { return EqualityComparer < Program < T > > . Default . GetHashCode ( i ) ; } } ",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestGetHashCodeMultipleMembers()
{
await TestAsync(
@"using System . Collections . Generic ; class Program { [|int i ; string S { get ; }|] } ",
@"using System . Collections . Generic ; class Program { int i ; string S { get ; } public override int GetHashCode ( ) { var hashCode = EqualityComparer < int > . Default . GetHashCode ( i ) ; hashCode = hashCode * - 1521134295 + EqualityComparer < string > . Default . GetHashCode ( S ) ; return hashCode ; } } ",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestSmartTagText1()
{
await TestSmartTagTextAsync(
@"using System . Collections . Generic ; class Program { [|bool b ; HashSet < string > s ;|] public Program ( bool b ) { this . b = b ; } } ",
FeaturesResources.Generate_Equals_object);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestSmartTagText2()
{
await TestSmartTagTextAsync(
@"using System . Collections . Generic ; class Program { [|bool b ; HashSet < string > s ;|] public Program ( bool b ) { this . b = b ; } } ",
FeaturesResources.Generate_GetHashCode,
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestSmartTagText3()
{
await TestSmartTagTextAsync(
@"using System . Collections . Generic ; class Program { [|bool b ; HashSet < string > s ;|] public Program ( bool b ) { this . b = b ; } } ",
FeaturesResources.Generate_Both,
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task Tuple_Disabled()
{
await TestAsync(@"using System . Collections . Generic ; class C { [|(int, string) a ;|] } ",
@"using System . Collections . Generic ; class C { (int, string) a ; public override bool Equals ( object obj ) { var c = obj as C ; return c != null && EqualityComparer < (int, string) > . Default . Equals ( a , c . a ) ; } } ",
index: 0,
parseOptions: TestOptions.Regular.WithLanguageVersion(CodeAnalysis.CSharp.LanguageVersion.CSharp6));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task Tuples_Equals()
{
await TestAsync(
@"using System . Collections . Generic ; class C { [|(int, string) a ;|] } ",
@"using System . Collections . Generic ; class C { (int, string) a ; public override bool Equals ( object obj ) { var c = obj as C ; return c != null && EqualityComparer < (int, string) > . Default . Equals ( a , c . a ) ; } } ",
index: 0,
parseOptions: TestOptions.Regular, withScriptOption: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TupleWithNames_Equals()
{
await TestAsync(
@"using System . Collections . Generic ; class C { [|(int x, string y) a ;|] } ",
@"using System . Collections . Generic ; class C { (int x, string y) a ; public override bool Equals ( object obj ) { var c = obj as C ; return c != null && EqualityComparer < (int x, string y) > . Default . Equals ( a , c . a ) ; } } ",
index: 0,
parseOptions: TestOptions.Regular, withScriptOption: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task Tuple_HashCode()
{
await TestAsync(
@"using System . Collections . Generic ; class Program { [|(int, string) i ;|] } ",
@"using System . Collections . Generic ; class Program { (int, string) i ; public override int GetHashCode ( ) { return EqualityComparer < (int, string) > . Default . GetHashCode ( i ) ; } } ",
index: 1,
parseOptions: TestOptions.Regular, withScriptOption: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TupleWithNames_HashCode()
{
await TestAsync(
@"using System . Collections . Generic ; class Program { [|(int x, string y) i ;|] } ",
@"using System . Collections . Generic ; class Program { (int x, string y) i ; public override int GetHashCode ( ) { return EqualityComparer < (int x, string y) > . Default . GetHashCode ( i ) ; } } ",
index: 1,
parseOptions: TestOptions.Regular,
withScriptOption: true);
}
}
}
| |
// 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 Xunit;
namespace System.Buffers.Tests
{
public class BasicUnitTests
{
[Fact]
public void ByteSpanEmptyCreateArrayTest()
{
var empty = Span<byte>.Empty;
var array = empty.ToArray();
Assert.Equal(0, array.Length);
}
[Fact]
public void ByteReadOnlySpanEmptyCreateArrayTest()
{
var empty = ReadOnlySpan<byte>.Empty;
var array = empty.ToArray();
Assert.Equal(0, array.Length);
}
[Fact]
public unsafe void ByteSpanEqualsTestsTwoDifferentInstancesOfBuffersWithOneValueDifferent()
{
const int bufferLength = 128;
byte[] buffer1 = new byte[bufferLength];
byte[] buffer2 = new byte[bufferLength];
for (int i = 0; i < bufferLength; i++)
{
buffer1[i] = (byte)(bufferLength + 1 - i);
buffer2[i] = (byte)(bufferLength + 1 - i);
}
fixed (byte* buffer1pinned = buffer1)
fixed (byte* buffer2pinned = buffer2)
{
Span<byte> b1 = new Span<byte>(buffer1pinned, bufferLength);
Span<byte> b2 = new Span<byte>(buffer2pinned, bufferLength);
for (int i = 0; i < bufferLength; i++)
{
for (int diffPosition = i; diffPosition < bufferLength; diffPosition++)
{
buffer1[diffPosition] = unchecked((byte)(buffer1[diffPosition] + 1));
Assert.False(b1.Slice(i).SequenceEqual(b2.Slice(i)));
}
}
}
}
[Fact]
public unsafe void ByteReadOnlySpanEqualsTestsTwoDifferentInstancesOfBuffersWithOneValueDifferent()
{
const int bufferLength = 128;
byte[] buffer1 = new byte[bufferLength];
byte[] buffer2 = new byte[bufferLength];
for (int i = 0; i < bufferLength; i++)
{
buffer1[i] = (byte)(bufferLength + 1 - i);
buffer2[i] = (byte)(bufferLength + 1 - i);
}
fixed (byte* buffer1pinned = buffer1)
fixed (byte* buffer2pinned = buffer2)
{
ReadOnlySpan<byte> b1 = new ReadOnlySpan<byte>(buffer1pinned, bufferLength);
ReadOnlySpan<byte> b2 = new ReadOnlySpan<byte>(buffer2pinned, bufferLength);
for (int i = 0; i < bufferLength; i++)
{
for (int diffPosition = i; diffPosition < bufferLength; diffPosition++)
{
buffer1[diffPosition] = unchecked((byte)(buffer1[diffPosition] + 1));
Assert.False(b1.Slice(i).SequenceEqual(b2.Slice(i)));
}
}
}
}
[Theory]
[InlineData(new byte[0], 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 0, 2)]
[InlineData(new byte[2] { 0, 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 1, 1)]
[InlineData(new byte[2] { 0, 0 }, 2, 0)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 3)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 1)]
public void ByteSpanCtorWithRangeValidCases(byte[] bytes, int start, int length)
{
Span<byte> span = new Span<byte>(bytes, start, length);
}
[Theory]
[InlineData(new byte[0], 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 0, 2)]
[InlineData(new byte[2] { 0, 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 1, 1)]
[InlineData(new byte[2] { 0, 0 }, 2, 0)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 3)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 1)]
public void ByteReadOnlySpanCtorWithRangeValidCases(byte[] bytes, int start, int length)
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(bytes, start, length);
}
[Theory]
[InlineData(new byte[0], 1, 0)]
[InlineData(new byte[0], 1, -1)]
[InlineData(new byte[0], 0, 1)]
[InlineData(new byte[0], -1, 0)]
[InlineData(new byte[0], 5, 5)]
[InlineData(new byte[1] { 0 }, 0, 2)]
[InlineData(new byte[1] { 0 }, 1, 1)]
[InlineData(new byte[1] { 0 }, -1, 2)]
[InlineData(new byte[2] { 0, 0 }, 0, 3)]
[InlineData(new byte[2] { 0, 0 }, 1, 2)]
[InlineData(new byte[2] { 0, 0 }, 2, 1)]
[InlineData(new byte[2] { 0, 0 }, 3, 0)]
[InlineData(new byte[2] { 0, 0 }, 1, -1)]
[InlineData(new byte[2] { 0, 0 }, 2, int.MaxValue)]
[InlineData(new byte[2] { 0, 0 }, int.MinValue, int.MinValue)]
[InlineData(new byte[2] { 0, 0 }, int.MaxValue, int.MaxValue)]
[InlineData(new byte[2] { 0, 0 }, int.MinValue, int.MaxValue)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 3)]
[InlineData(new byte[3] { 0, 0, 0 }, 2, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 15, 0)]
public void ByteSpanCtorWithRangeThrowsArgumentOutOfRangeException(byte[] bytes, int start, int length)
{
try
{
Span<byte> span = new Span<byte>(bytes, start, length);
Assert.True(false);
}
catch (Exception ex)
{
Assert.True(ex is ArgumentOutOfRangeException);
}
}
[Theory]
[InlineData(new byte[0], 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 0, 2)]
[InlineData(new byte[2] { 0, 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 1, 1)]
[InlineData(new byte[2] { 0, 0 }, 2, 0)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 3)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 1)]
public void ByteSpanSliceWithRangeValidCases(byte[] bytes, int start, int length)
{
Span<byte> span = new Span<byte>(bytes, start, length);
}
[Theory]
[InlineData(new byte[0], 1, 0)]
[InlineData(new byte[0], 1, -1)]
[InlineData(new byte[0], 0, 1)]
[InlineData(new byte[0], -1, 0)]
[InlineData(new byte[0], 5, 5)]
[InlineData(new byte[1] { 0 }, 0, 2)]
[InlineData(new byte[1] { 0 }, 1, 1)]
[InlineData(new byte[1] { 0 }, -1, 2)]
[InlineData(new byte[2] { 0, 0 }, 0, 3)]
[InlineData(new byte[2] { 0, 0 }, 1, 2)]
[InlineData(new byte[2] { 0, 0 }, 2, 1)]
[InlineData(new byte[2] { 0, 0 }, 3, 0)]
[InlineData(new byte[2] { 0, 0 }, 1, -1)]
[InlineData(new byte[2] { 0, 0 }, 2, int.MaxValue)]
[InlineData(new byte[2] { 0, 0 }, int.MinValue, int.MinValue)]
[InlineData(new byte[2] { 0, 0 }, int.MaxValue, int.MaxValue)]
[InlineData(new byte[2] { 0, 0 }, int.MinValue, int.MaxValue)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 3)]
[InlineData(new byte[3] { 0, 0, 0 }, 2, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 15, 0)]
public void ByteSpanSliceWithRangeThrowsArgumentOutOfRangeException1(byte[] bytes, int start, int length)
{
var span = new Span<byte>(bytes);
try
{
Span<byte> slice = span.Slice(start, length);
Assert.True(false);
}
catch (Exception ex)
{
Assert.True(ex is ArgumentOutOfRangeException);
}
}
[Theory]
[InlineData(new byte[0], 0)]
[InlineData(new byte[1] { 0 }, 0)]
[InlineData(new byte[1] { 0 }, 1)]
[InlineData(new byte[2] { 0, 0 }, 0)]
[InlineData(new byte[2] { 0, 0 }, 1)]
[InlineData(new byte[2] { 0, 0 }, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 0)]
[InlineData(new byte[3] { 0, 0, 0 }, 1)]
[InlineData(new byte[3] { 0, 0, 0 }, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 3)]
public void ByteSpanSliceWithStartRangeValidCases(byte[] bytes, int start)
{
Span<byte> span = new Span<byte>(bytes).Slice(start);
}
[Theory]
[InlineData(new byte[0], int.MinValue)]
[InlineData(new byte[0], -1)]
[InlineData(new byte[0], 1)]
[InlineData(new byte[0], int.MaxValue)]
[InlineData(new byte[1] { 0 }, int.MinValue)]
[InlineData(new byte[1] { 0 }, -1)]
[InlineData(new byte[1] { 0 }, 2)]
[InlineData(new byte[1] { 0 }, int.MaxValue)]
[InlineData(new byte[2] { 0, 0 }, int.MinValue)]
[InlineData(new byte[2] { 0, 0 }, -1)]
[InlineData(new byte[2] { 0, 0 }, 3)]
[InlineData(new byte[2] { 0, 0 }, int.MaxValue)]
public void ByteSpanSliceWithStartRangeThrowsArgumentOutOfRangeException(byte[] bytes, int start)
{
var span = new Span<byte>(bytes);
try
{
Span<byte> slice = span.Slice(start);
Assert.True(false);
}
catch (Exception ex)
{
Assert.True(ex is ArgumentOutOfRangeException);
}
}
public void ByteReadOnlySpanCtorWithRangeThrowsArgumentOutOfRangeException(byte[] bytes, int start, int length)
{
try
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(bytes, start, length);
Assert.True(false);
}
catch (Exception ex)
{
Assert.True(ex is ArgumentOutOfRangeException);
}
}
[Fact]
public void SetSpan()
{
var destination = new Span<byte>(new byte[100]);
var source = new Span<byte>(new byte[] { 1, 2, 3 });
source.CopyTo(destination);
for (int i = 0; i < source.Length; i++)
{
Assert.Equal(source[i], destination[i]);
}
}
[Fact]
public void SetArray()
{
var destination = new Span<byte>(new byte[100]);
var source = new byte[] { 1, 2, 3 };
source.CopyTo(destination);
for (int i = 0; i < source.Length; i++)
{
Assert.Equal(source[i], destination[i]);
}
}
[Fact]
public void CovariantSlicesNotSupported1()
{
object[] array = new string[10];
try
{
var slice = new Span<object>(array);
Assert.True(false);
}
catch (Exception ex)
{
Assert.True(ex is ArrayTypeMismatchException);
}
}
[Fact]
public void CovariantSlicesNotSupported2()
{
object[] array = new string[10];
try
{
var slice = array.AsSpan(0);
Assert.True(false);
}
catch (Exception ex)
{
Assert.True(ex is ArrayTypeMismatchException);
}
}
[Fact]
public void CovariantSlicesNotSupported3()
{
object[] array = new string[10];
try
{
var slice = new Span<object>(array, 0, 10);
Assert.True(false);
}
catch (Exception ex)
{
Assert.True(ex is ArrayTypeMismatchException);
}
}
[Fact]
public void OwnedBufferDisposedAfterFinalizerGCKeepAliveTest()
{
MemoryManager<byte> owned = new CustomMemoryForTest<byte>(new byte[1024]);
var buffer = owned.Memory;
var slice = buffer.Slice(1);
var span = buffer.Span;
var sliceSpan = slice.Span;
span[5] = 42;
sliceSpan[10] = 24;
GC.Collect(2);
GC.WaitForPendingFinalizers();
try
{
span = buffer.Span;
sliceSpan = slice.Span;
}
catch (ObjectDisposedException ex)
{
Assert.True(false, "There shouldn't be any Object Disposed Exception here. " + ex.Message);
}
Assert.Equal(42, span[5]);
Assert.Equal(24, sliceSpan[10]);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Specialized;
using Avalonia.Collections;
using Avalonia.Controls.Generators;
using Avalonia.Controls.Templates;
using Avalonia.Controls.Utils;
using Avalonia.LogicalTree;
using Avalonia.Styling;
namespace Avalonia.Controls.Presenters
{
/// <summary>
/// Base class for controls that present items inside an <see cref="ItemsControl"/>.
/// </summary>
public abstract class ItemsPresenterBase : Control, IItemsPresenter, ITemplatedControl, IChildIndexProvider
{
/// <summary>
/// Defines the <see cref="Items"/> property.
/// </summary>
public static readonly DirectProperty<ItemsPresenterBase, IEnumerable> ItemsProperty =
ItemsControl.ItemsProperty.AddOwner<ItemsPresenterBase>(o => o.Items, (o, v) => o.Items = v);
/// <summary>
/// Defines the <see cref="ItemsPanel"/> property.
/// </summary>
public static readonly StyledProperty<ITemplate<IPanel>> ItemsPanelProperty =
ItemsControl.ItemsPanelProperty.AddOwner<ItemsPresenterBase>();
/// <summary>
/// Defines the <see cref="ItemTemplate"/> property.
/// </summary>
public static readonly StyledProperty<IDataTemplate> ItemTemplateProperty =
ItemsControl.ItemTemplateProperty.AddOwner<ItemsPresenterBase>();
private IEnumerable _items;
private IDisposable _itemsSubscription;
private bool _createdPanel;
private IItemContainerGenerator _generator;
private EventHandler<ChildIndexChangedEventArgs> _childIndexChanged;
/// <summary>
/// Initializes static members of the <see cref="ItemsPresenter"/> class.
/// </summary>
static ItemsPresenterBase()
{
TemplatedParentProperty.Changed.AddClassHandler<ItemsPresenterBase>((x,e) => x.TemplatedParentChanged(e));
}
/// <summary>
/// Gets or sets the items to be displayed.
/// </summary>
public IEnumerable Items
{
get
{
return _items;
}
set
{
_itemsSubscription?.Dispose();
_itemsSubscription = null;
if (!IsHosted && _createdPanel && value is INotifyCollectionChanged incc)
{
_itemsSubscription = incc.WeakSubscribe(ItemsCollectionChanged);
}
SetAndRaise(ItemsProperty, ref _items, value);
if (_createdPanel)
{
ItemsChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
}
/// <summary>
/// Gets the item container generator.
/// </summary>
public IItemContainerGenerator ItemContainerGenerator
{
get
{
if (_generator == null)
{
_generator = CreateItemContainerGenerator();
}
return _generator;
}
internal set
{
if (_generator != null)
{
throw new InvalidOperationException("ItemContainerGenerator already created.");
}
_generator = value;
}
}
/// <summary>
/// Gets or sets a template which creates the <see cref="Panel"/> used to display the items.
/// </summary>
public ITemplate<IPanel> ItemsPanel
{
get { return GetValue(ItemsPanelProperty); }
set { SetValue(ItemsPanelProperty, value); }
}
/// <summary>
/// Gets or sets the data template used to display the items in the control.
/// </summary>
public IDataTemplate ItemTemplate
{
get { return GetValue(ItemTemplateProperty); }
set { SetValue(ItemTemplateProperty, value); }
}
/// <summary>
/// Gets the panel used to display the items.
/// </summary>
public IPanel Panel
{
get;
private set;
}
protected bool IsHosted => TemplatedParent is IItemsPresenterHost;
event EventHandler<ChildIndexChangedEventArgs> IChildIndexProvider.ChildIndexChanged
{
add => _childIndexChanged += value;
remove => _childIndexChanged -= value;
}
/// <inheritdoc/>
public override sealed void ApplyTemplate()
{
if (!_createdPanel)
{
CreatePanel();
}
}
/// <inheritdoc/>
public virtual void ScrollIntoView(int index)
{
}
/// <inheritdoc/>
void IItemsPresenter.ItemsChanged(NotifyCollectionChangedEventArgs e)
{
if (Panel != null)
{
ItemsChanged(e);
_childIndexChanged?.Invoke(this, new ChildIndexChangedEventArgs());
}
}
/// <summary>
/// Creates the <see cref="ItemContainerGenerator"/> for the control.
/// </summary>
/// <returns>
/// An <see cref="IItemContainerGenerator"/> or null.
/// </returns>
protected virtual IItemContainerGenerator CreateItemContainerGenerator()
{
var i = TemplatedParent as ItemsControl;
var result = i?.ItemContainerGenerator;
if (result == null)
{
result = new ItemContainerGenerator(this);
result.ItemTemplate = ItemTemplate;
}
result.Materialized += ContainerActionHandler;
result.Dematerialized += ContainerActionHandler;
result.Recycled += ContainerActionHandler;
return result;
}
private void ContainerActionHandler(object sender, ItemContainerEventArgs e)
{
for (var i = 0; i < e.Containers.Count; i++)
{
_childIndexChanged?.Invoke(this, new ChildIndexChangedEventArgs(e.Containers[i].ContainerControl));
}
}
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
Panel.Measure(availableSize);
return Panel.DesiredSize;
}
/// <inheritdoc/>
protected override Size ArrangeOverride(Size finalSize)
{
Panel.Arrange(new Rect(finalSize));
return finalSize;
}
/// <summary>
/// Called when the <see cref="Panel"/> is created.
/// </summary>
/// <param name="panel">The panel.</param>
protected virtual void PanelCreated(IPanel panel)
{
}
/// <summary>
/// Called when the items for the presenter change, either because <see cref="Items"/>
/// has been set, the items collection has been modified, or the panel has been created.
/// </summary>
/// <param name="e">A description of the change.</param>
/// <remarks>
/// The panel is guaranteed to be created when this method is called.
/// </remarks>
protected virtual void ItemsChanged(NotifyCollectionChangedEventArgs e)
{
ItemContainerSync.ItemsChanged(this, Items, e);
}
/// <summary>
/// Creates the <see cref="Panel"/> when <see cref="ApplyTemplate"/> is called for the first
/// time.
/// </summary>
private void CreatePanel()
{
Panel = ItemsPanel.Build();
Panel.SetValue(TemplatedParentProperty, TemplatedParent);
LogicalChildren.Clear();
VisualChildren.Clear();
LogicalChildren.Add(Panel);
VisualChildren.Add(Panel);
_createdPanel = true;
if (!IsHosted && _itemsSubscription == null && Items is INotifyCollectionChanged incc)
{
_itemsSubscription = incc.WeakSubscribe(ItemsCollectionChanged);
}
PanelCreated(Panel);
}
/// <summary>
/// Called when the <see cref="Items"/> collection changes.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The event args.</param>
private void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (_createdPanel)
{
ItemsChanged(e);
}
}
private void TemplatedParentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.NewValue as IItemsPresenterHost)?.RegisterItemsPresenter(this);
}
int IChildIndexProvider.GetChildIndex(ILogical child)
{
if (child is IControl control && ItemContainerGenerator is { } generator)
{
var index = ItemContainerGenerator.IndexFromContainer(control);
return index;
}
return -1;
}
bool IChildIndexProvider.TryGetTotalCount(out int count)
{
return Items.TryGetCountFast(out count);
}
}
}
| |
// ResizableOptions.cs
// Script#/Libraries/jQuery/UI
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Runtime.CompilerServices;
namespace jQueryApi.UI.Interactions {
/// <summary>
/// Options used to initialize or customize Resizable.
/// </summary>
[ScriptImport]
[ScriptIgnoreNamespace]
[ScriptName("Object")]
public sealed class ResizableOptions {
public ResizableOptions() {
}
public ResizableOptions(params object[] nameValuePairs) {
}
/// <summary>
/// This event is triggered when the resizable is created.
/// </summary>
[ScriptField]
public jQueryEventHandler Create {
get {
return null;
}
set {
}
}
/// <summary>
/// This event is triggered during the resize, on the drag of the resize handler.
/// </summary>
[ScriptField]
public jQueryUIEventHandler<ResizeEvent> Resize {
get {
return null;
}
set {
}
}
/// <summary>
/// This event is triggered at the start of a resize operation.
/// </summary>
[ScriptField]
public jQueryUIEventHandler<ResizeStartEvent> Start {
get {
return null;
}
set {
}
}
/// <summary>
/// This event is triggered at the end of a resize operation.
/// </summary>
[ScriptField]
public jQueryUIEventHandler<ResizeStopEvent> Stop {
get {
return null;
}
set {
}
}
/// <summary>
/// Resize these elements synchronous when resizing.
/// </summary>
[ScriptField]
public object AlsoResize {
get {
return null;
}
set {
}
}
/// <summary>
/// Animates to the final size after resizing.
/// </summary>
[ScriptField]
public bool Animate {
get {
return false;
}
set {
}
}
/// <summary>
/// Duration time for animating, in milliseconds. Other possible values: 'slow', 'normal', 'fast'.
/// </summary>
[ScriptField]
public object AnimateDuration {
get {
return null;
}
set {
}
}
/// <summary>
/// Easing effect for animating.
/// </summary>
[ScriptField]
public string AnimateEasing {
get {
return null;
}
set {
}
}
/// <summary>
/// If set to true, resizing is constrained by the original aspect ratio. Otherwise a custom aspect ratio can be specified, such as 9 / 16, or 0.5.
/// </summary>
[ScriptField]
public object AspectRatio {
get {
return null;
}
set {
}
}
/// <summary>
/// If set to true, automatically hides the handles except when the mouse hovers over the element.
/// </summary>
[ScriptField]
public bool AutoHide {
get {
return false;
}
set {
}
}
/// <summary>
/// Prevents resizing if you start on elements matching the selector.
/// </summary>
[ScriptField]
public string Cancel {
get {
return null;
}
set {
}
}
/// <summary>
/// Constrains resizing to within the bounds of the specified element. Possible values: 'parent', 'document', a DOMElement, or a Selector.
/// </summary>
[ScriptField]
public object Containment {
get {
return null;
}
set {
}
}
/// <summary>
/// Tolerance, in milliseconds, for when resizing should start. If specified, resizing will not start until after mouse is moved beyond duration. This can help prevent unintended resizing when clicking on an element.
/// </summary>
[ScriptField]
public int Delay {
get {
return 0;
}
set {
}
}
/// <summary>
/// Disables the resizable if set to true.
/// </summary>
[ScriptField]
public bool Disabled {
get {
return false;
}
set {
}
}
/// <summary>
/// Tolerance, in pixels, for when resizing should start. If specified, resizing will not start until after mouse is moved beyond distance. This can help prevent unintended resizing when clicking on an element.
/// </summary>
[ScriptField]
public int Distance {
get {
return 0;
}
set {
}
}
/// <summary>
/// If set to true, a semi-transparent helper element is shown for resizing.
/// </summary>
[ScriptField]
public bool Ghost {
get {
return false;
}
set {
}
}
/// <summary>
/// Snaps the resizing element to a grid, every x and y pixels. Array values: [x, y]
/// </summary>
[ScriptField]
public Array Grid {
get {
return null;
}
set {
}
}
/// <summary>
/// If specified as a string, should be a comma-split list of any of the following: 'n, e, s, w, ne, se, sw, nw, all'. The necessary handles will be auto-generated by the plugin.<para>If specified as an object, the following keys are supported: { n, e, s, w, ne, se, sw, nw }. The value of any specified should be a jQuery selector matching the child element of the resizable to use as that handle. If the handle is not a child of the resizable, you can pass in the DOMElement or a valid jQuery object directly.</para>
/// </summary>
[ScriptField]
public object Handles {
get {
return null;
}
set {
}
}
/// <summary>
/// This is the css class that will be added to a proxy element to outline the resize during the drag of the resize handle. Once the resize is complete, the original element is sized.
/// </summary>
[ScriptField]
public string Helper {
get {
return null;
}
set {
}
}
/// <summary>
/// This is the maximum height the resizable should be allowed to resize to.
/// </summary>
[ScriptField]
public int MaxHeight {
get {
return 0;
}
set {
}
}
/// <summary>
/// This is the maximum width the resizable should be allowed to resize to.
/// </summary>
[ScriptField]
public int MaxWidth {
get {
return 0;
}
set {
}
}
/// <summary>
/// This is the minimum height the resizable should be allowed to resize to.
/// </summary>
[ScriptField]
public int MinHeight {
get {
return 0;
}
set {
}
}
/// <summary>
/// This is the minimum width the resizable should be allowed to resize to.
/// </summary>
[ScriptField]
public int MinWidth {
get {
return 0;
}
set {
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the dynamodb-2012-08-10.normal.json service model.
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.DynamoDBv2.Model;
namespace Amazon.DynamoDBv2
{
/// <summary>
/// Interface for accessing DynamoDB
///
/// Amazon DynamoDB
/// <para>
/// <b>Overview</b>
/// </para>
///
/// <para>
/// This is the Amazon DynamoDB API Reference. This guide provides descriptions and samples
/// of the low-level DynamoDB API. For information about DynamoDB application development,
/// go to the <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/">Amazon
/// DynamoDB Developer Guide</a>.
/// </para>
///
/// <para>
/// Instead of making the requests to the low-level DynamoDB API directly from your application,
/// we recommend that you use the AWS Software Development Kits (SDKs). The easy-to-use
/// libraries in the AWS SDKs make it unnecessary to call the low-level DynamoDB API directly
/// from your application. The libraries take care of request authentication, serialization,
/// and connection management. For more information, go to <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/UsingAWSSDK.html">Using
/// the AWS SDKs with DynamoDB</a> in the <i>Amazon DynamoDB Developer Guide</i>.
/// </para>
///
/// <para>
/// If you decide to code against the low-level DynamoDB API directly, you will need to
/// write the necessary code to authenticate your requests. For more information on signing
/// your requests, go to <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/API.html">Using
/// the DynamoDB API</a> in the <i>Amazon DynamoDB Developer Guide</i>.
/// </para>
///
/// <para>
/// The following are short descriptions of each low-level API action, organized by function.
/// </para>
///
/// <para>
/// <b>Managing Tables</b>
/// </para>
/// <ul> <li>
/// <para>
/// <i>CreateTable</i> - Creates a table with user-specified provisioned throughput settings.
/// You must designate one attribute as the hash primary key for the table; you can optionally
/// designate a second attribute as the range primary key. DynamoDB creates indexes on
/// these key attributes for fast data access. Optionally, you can create one or more
/// secondary indexes, which provide fast data access using non-key attributes.
/// </para>
/// </li> <li>
/// <para>
/// <i>DescribeTable</i> - Returns metadata for a table, such as table size, status, and
/// index information.
/// </para>
/// </li> <li>
/// <para>
/// <i>UpdateTable</i> - Modifies the provisioned throughput settings for a table. Optionally,
/// you can modify the provisioned throughput settings for global secondary indexes on
/// the table.
/// </para>
/// </li> <li>
/// <para>
/// <i>ListTables</i> - Returns a list of all tables associated with the current AWS account
/// and endpoint.
/// </para>
/// </li> <li>
/// <para>
/// <i>DeleteTable</i> - Deletes a table and all of its indexes.
/// </para>
/// </li> </ul>
/// <para>
/// For conceptual information about managing tables, go to <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.html">Working
/// with Tables</a> in the <i>Amazon DynamoDB Developer Guide</i>.
/// </para>
///
/// <para>
/// <b>Reading Data</b>
/// </para>
/// <ul> <li>
/// <para>
/// <i>GetItem</i> - Returns a set of attributes for the item that has a given primary
/// key. By default, <i>GetItem</i> performs an eventually consistent read; however, applications
/// can request a strongly consistent read instead.
/// </para>
/// </li> <li>
/// <para>
/// <i>BatchGetItem</i> - Performs multiple <i>GetItem</i> requests for data items using
/// their primary keys, from one table or multiple tables. The response from <i>BatchGetItem</i>
/// has a size limit of 16 MB and returns a maximum of 100 items. Both eventually consistent
/// and strongly consistent reads can be used.
/// </para>
/// </li> <li>
/// <para>
/// <i>Query</i> - Returns one or more items from a table or a secondary index. You must
/// provide a specific hash key value. You can narrow the scope of the query using comparison
/// operators against a range key value, or on the index key. <i>Query</i> supports either
/// eventual or strong consistency. A single response has a size limit of 1 MB.
/// </para>
/// </li> <li>
/// <para>
/// <i>Scan</i> - Reads every item in a table; the result set is eventually consistent.
/// You can limit the number of items returned by filtering the data attributes, using
/// conditional expressions. <i>Scan</i> can be used to enable ad-hoc querying of a table
/// against non-key attributes; however, since this is a full table scan without using
/// an index, <i>Scan</i> should not be used for any application query use case that requires
/// predictable performance.
/// </para>
/// </li> </ul>
/// <para>
/// For conceptual information about reading data, go to <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html">Working
/// with Items</a> and <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html">Query
/// and Scan Operations</a> in the <i>Amazon DynamoDB Developer Guide</i>.
/// </para>
///
/// <para>
/// <b>Modifying Data</b>
/// </para>
/// <ul> <li>
/// <para>
/// <i>PutItem</i> - Creates a new item, or replaces an existing item with a new item
/// (including all the attributes). By default, if an item in the table already exists
/// with the same primary key, the new item completely replaces the existing item. You
/// can use conditional operators to replace an item only if its attribute values match
/// certain conditions, or to insert a new item only if that item doesn't already exist.
/// </para>
/// </li> <li>
/// <para>
/// <i>UpdateItem</i> - Modifies the attributes of an existing item. You can also use
/// conditional operators to perform an update only if the item's attribute values match
/// certain conditions.
/// </para>
/// </li> <li>
/// <para>
/// <i>DeleteItem</i> - Deletes an item in a table by primary key. You can use conditional
/// operators to perform a delete an item only if the item's attribute values match certain
/// conditions.
/// </para>
/// </li> <li>
/// <para>
/// <i>BatchWriteItem</i> - Performs multiple <i>PutItem</i> and <i>DeleteItem</i> requests
/// across multiple tables in a single request. A failure of any request(s) in the batch
/// will not cause the entire <i>BatchWriteItem</i> operation to fail. Supports batches
/// of up to 25 items to put or delete, with a maximum total request size of 16 MB.
/// </para>
/// </li> </ul>
/// <para>
/// For conceptual information about modifying data, go to <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html">Working
/// with Items</a> and <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html">Query
/// and Scan Operations</a> in the <i>Amazon DynamoDB Developer Guide</i>.
/// </para>
/// </summary>
public partial interface IAmazonDynamoDB : IDisposable
{
#region BatchGetItem
/// <summary>
/// Initiates the asynchronous execution of the BatchGetItem operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the BatchGetItem operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<BatchGetItemResponse> BatchGetItemAsync(BatchGetItemRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region BatchWriteItem
/// <summary>
/// Initiates the asynchronous execution of the BatchWriteItem operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the BatchWriteItem operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<BatchWriteItemResponse> BatchWriteItemAsync(BatchWriteItemRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CreateTable
/// <summary>
/// Initiates the asynchronous execution of the CreateTable operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateTable operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CreateTableResponse> CreateTableAsync(CreateTableRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteItem
/// <summary>
/// Initiates the asynchronous execution of the DeleteItem operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteItem operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteItemResponse> DeleteItemAsync(DeleteItemRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteTable
/// <summary>
/// Initiates the asynchronous execution of the DeleteTable operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteTable operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteTableResponse> DeleteTableAsync(DeleteTableRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeTable
/// <summary>
/// Initiates the asynchronous execution of the DescribeTable operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeTable operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeTableResponse> DescribeTableAsync(DescribeTableRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetItem
/// <summary>
/// Initiates the asynchronous execution of the GetItem operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetItem operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetItemResponse> GetItemAsync(GetItemRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListTables
/// <summary>
/// Initiates the asynchronous execution of the ListTables operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListTables operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListTablesResponse> ListTablesAsync(ListTablesRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PutItem
/// <summary>
/// Initiates the asynchronous execution of the PutItem operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PutItem operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<PutItemResponse> PutItemAsync(PutItemRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region Query
/// <summary>
/// Initiates the asynchronous execution of the Query operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the Query operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<QueryResponse> QueryAsync(QueryRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region Scan
/// <summary>
/// Initiates the asynchronous execution of the Scan operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the Scan operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ScanResponse> ScanAsync(ScanRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region UpdateItem
/// <summary>
/// Initiates the asynchronous execution of the UpdateItem operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateItem operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<UpdateItemResponse> UpdateItemAsync(UpdateItemRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region UpdateTable
/// <summary>
/// Initiates the asynchronous execution of the UpdateTable operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateTable operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<UpdateTableResponse> UpdateTableAsync(UpdateTableRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using Xunit;
using Xunit.Abstractions;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public class CertTests
{
private const string PrivateKeySectionHeader = "[Private Key]";
private const string PublicKeySectionHeader = "[Public Key]";
private readonly ITestOutputHelper _log;
public CertTests(ITestOutputHelper output)
{
_log = output;
}
[Fact]
public static void X509CertTest()
{
string certSubject = @"CN=Microsoft Corporate Root Authority, OU=ITG, O=Microsoft, L=Redmond, S=WA, C=US, E=pkit@microsoft.com";
using (X509Certificate cert = new X509Certificate(Path.Combine("TestData", "microsoft.cer")))
{
Assert.Equal(certSubject, cert.Subject);
Assert.Equal(certSubject, cert.Issuer);
int snlen = cert.GetSerialNumber().Length;
Assert.Equal(16, snlen);
byte[] serialNumber = new byte[snlen];
Buffer.BlockCopy(cert.GetSerialNumber(), 0,
serialNumber, 0,
snlen);
Assert.Equal(0xF6, serialNumber[0]);
Assert.Equal(0xB3, serialNumber[snlen / 2]);
Assert.Equal(0x2A, serialNumber[snlen - 1]);
Assert.Equal("1.2.840.113549.1.1.1", cert.GetKeyAlgorithm());
int pklen = cert.GetPublicKey().Length;
Assert.Equal(270, pklen);
byte[] publicKey = new byte[pklen];
Buffer.BlockCopy(cert.GetPublicKey(), 0,
publicKey, 0,
pklen);
Assert.Equal(0x30, publicKey[0]);
Assert.Equal(0xB6, publicKey[9]);
Assert.Equal(1, publicKey[pklen - 1]);
}
}
[Fact]
public static void X509Cert2Test()
{
string certName = @"E=admin@digsigtrust.com, CN=ABA.ECOM Root CA, O=""ABA.ECOM, INC."", L=Washington, S=DC, C=US";
DateTime notBefore = new DateTime(1999, 7, 12, 17, 33, 53, DateTimeKind.Utc).ToLocalTime();
DateTime notAfter = new DateTime(2009, 7, 9, 17, 33, 53, DateTimeKind.Utc).ToLocalTime();
using (X509Certificate2 cert2 = new X509Certificate2(Path.Combine("TestData", "test.cer")))
{
Assert.Equal(certName, cert2.IssuerName.Name);
Assert.Equal(certName, cert2.SubjectName.Name);
Assert.Equal("ABA.ECOM Root CA", cert2.GetNameInfo(X509NameType.DnsName, true));
PublicKey pubKey = cert2.PublicKey;
Assert.Equal("RSA", pubKey.Oid.FriendlyName);
Assert.Equal(notAfter, cert2.NotAfter);
Assert.Equal(notBefore, cert2.NotBefore);
Assert.Equal(notAfter.ToString(), cert2.GetExpirationDateString());
Assert.Equal(notBefore.ToString(), cert2.GetEffectiveDateString());
Assert.Equal("00D01E4090000046520000000100000004", cert2.SerialNumber);
Assert.Equal("1.2.840.113549.1.1.5", cert2.SignatureAlgorithm.Value);
Assert.Equal("7A74410FB0CD5C972A364B71BF031D88A6510E9E", cert2.Thumbprint);
Assert.Equal(3, cert2.Version);
}
}
[Fact]
[OuterLoop("May require using the network, to download CRLs and intermediates")]
public void TestVerify()
{
bool success;
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
{
// Fails because expired (NotAfter = 10/16/2016)
Assert.False(microsoftDotCom.Verify(), "MicrosoftDotComSslCertBytes");
}
using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
{
// NotAfter=10/31/2023
success = microsoftDotComIssuer.Verify();
if (!success)
{
LogVerifyErrors(microsoftDotComIssuer, "MicrosoftDotComIssuerBytes");
}
Assert.True(success, "MicrosoftDotComIssuerBytes");
}
// High Sierra fails to build a chain for a self-signed certificate with revocation enabled.
// https://github.com/dotnet/corefx/issues/21875
if (!PlatformDetection.IsMacOsHighSierra)
{
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
{
// NotAfter=7/17/2036
success = microsoftDotComRoot.Verify();
if (!success)
{
LogVerifyErrors(microsoftDotComRoot, "MicrosoftDotComRootBytes");
}
Assert.True(success, "MicrosoftDotComRootBytes");
}
}
}
private void LogVerifyErrors(X509Certificate2 cert, string testName)
{
// Emulate cert.Verify() implementation in order to capture and log errors.
try
{
using (var chain = new X509Chain())
{
if (!chain.Build(cert))
{
foreach (X509ChainStatus chainStatus in chain.ChainStatus)
{
_log.WriteLine(string.Format($"X509Certificate2.Verify error: {testName}, {chainStatus.Status}, {chainStatus.StatusInformation}"));
}
}
else
{
_log.WriteLine(string.Format($"X509Certificate2.Verify expected error; received none: {testName}"));
}
}
}
catch (Exception e)
{
_log.WriteLine($"X509Certificate2.Verify exception: {testName}, {e}");
}
}
[Fact]
public static void X509CertEmptyToString()
{
using (var c = new X509Certificate())
{
string expectedResult = "System.Security.Cryptography.X509Certificates.X509Certificate";
Assert.Equal(expectedResult, c.ToString());
Assert.Equal(expectedResult, c.ToString(false));
Assert.Equal(expectedResult, c.ToString(true));
}
}
[Fact]
public static void X509Cert2EmptyToString()
{
using (var c2 = new X509Certificate2())
{
string expectedResult = "System.Security.Cryptography.X509Certificates.X509Certificate2";
Assert.Equal(expectedResult, c2.ToString());
Assert.Equal(expectedResult, c2.ToString(false));
Assert.Equal(expectedResult, c2.ToString(true));
}
}
[Fact]
public static void X509Cert2ToStringVerbose()
{
using (X509Store store = new X509Store("My", StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 c in store.Certificates)
{
Assert.False(string.IsNullOrWhiteSpace(c.ToString(true)));
c.Dispose();
}
}
}
[Theory]
[MemberData(nameof(StorageFlags))]
public static void X509Certificate2ToStringVerbose_WithPrivateKey(X509KeyStorageFlags keyStorageFlags)
{
using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, keyStorageFlags))
{
string certToString = cert.ToString(true);
Assert.Contains(PrivateKeySectionHeader, certToString);
Assert.Contains(PublicKeySectionHeader, certToString);
}
}
[Fact]
public static void X509Certificate2ToStringVerbose_NoPrivateKey()
{
using (var cert = new X509Certificate2(TestData.MsCertificatePemBytes))
{
string certToString = cert.ToString(true);
Assert.DoesNotContain(PrivateKeySectionHeader, certToString);
Assert.Contains(PublicKeySectionHeader, certToString);
}
}
[Fact]
public static void X509Cert2CreateFromEmptyPfx()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.EmptyPfx));
}
[Fact]
public static void X509Cert2CreateFromPfxFile()
{
using (X509Certificate2 cert2 = new X509Certificate2(Path.Combine("TestData", "DummyTcpServer.pfx")))
{
// OID=RSA Encryption
Assert.Equal("1.2.840.113549.1.1.1", cert2.GetKeyAlgorithm());
}
}
[Fact]
public static void X509Cert2CreateFromPfxWithPassword()
{
using (X509Certificate2 cert2 = new X509Certificate2(Path.Combine("TestData", "test.pfx"), "test"))
{
// OID=RSA Encryption
Assert.Equal("1.2.840.113549.1.1.1", cert2.GetKeyAlgorithm());
}
}
[Fact]
public static void X509Certificate2FromPkcs7DerFile()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(Path.Combine("TestData", "singlecert.p7b")));
}
[Fact]
public static void X509Certificate2FromPkcs7PemFile()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(Path.Combine("TestData", "singlecert.p7c")));
}
[Fact]
public static void X509Certificate2FromPkcs7DerBlob()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.Pkcs7SingleDerBytes));
}
[Fact]
public static void X509Certificate2FromPkcs7PemBlob()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.Pkcs7SinglePemBytes));
}
[Fact]
public static void UseAfterDispose()
{
using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate))
{
IntPtr h = c.Handle;
// Do a couple of things that would only be true on a valid certificate, as a precondition.
Assert.NotEqual(IntPtr.Zero, h);
byte[] actualThumbprint = c.GetCertHash();
c.Dispose();
// For compat reasons, Dispose() acts like the now-defunct Reset() method rather than
// causing ObjectDisposedExceptions.
h = c.Handle;
Assert.Equal(IntPtr.Zero, h);
// State held on X509Certificate
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash());
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithm());
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParameters());
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParametersString());
Assert.ThrowsAny<CryptographicException>(() => c.GetPublicKey());
Assert.ThrowsAny<CryptographicException>(() => c.GetSerialNumber());
Assert.ThrowsAny<CryptographicException>(() => c.Issuer);
Assert.ThrowsAny<CryptographicException>(() => c.Subject);
Assert.ThrowsAny<CryptographicException>(() => c.NotBefore);
Assert.ThrowsAny<CryptographicException>(() => c.NotAfter);
// State held on X509Certificate2
Assert.ThrowsAny<CryptographicException>(() => c.RawData);
Assert.ThrowsAny<CryptographicException>(() => c.SignatureAlgorithm);
Assert.ThrowsAny<CryptographicException>(() => c.Version);
Assert.ThrowsAny<CryptographicException>(() => c.SubjectName);
Assert.ThrowsAny<CryptographicException>(() => c.IssuerName);
Assert.ThrowsAny<CryptographicException>(() => c.PublicKey);
Assert.ThrowsAny<CryptographicException>(() => c.Extensions);
Assert.ThrowsAny<CryptographicException>(() => c.PrivateKey);
}
}
[Fact]
public static void ExportPublicKeyAsPkcs12()
{
using (X509Certificate2 publicOnly = new X509Certificate2(TestData.MsCertificate))
{
// Pre-condition: There's no private key
Assert.False(publicOnly.HasPrivateKey);
// macOS 10.12 (Sierra) fails to create a PKCS#12 blob if it has no private keys within it.
bool shouldThrow = RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
try
{
byte[] pkcs12Bytes = publicOnly.Export(X509ContentType.Pkcs12);
Assert.False(shouldThrow, "PKCS#12 export of a public-only certificate threw as expected");
// Read it back as a collection, there should be only one cert, and it should
// be equal to the one we started with.
using (ImportedCollection ic = Cert.Import(pkcs12Bytes))
{
X509Certificate2Collection fromPfx = ic.Collection;
Assert.Equal(1, fromPfx.Count);
Assert.Equal(publicOnly, fromPfx[0]);
}
}
catch (CryptographicException)
{
if (!shouldThrow)
{
throw;
}
}
}
}
public static IEnumerable<object> StorageFlags => CollectionImportTests.StorageFlags;
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using Encog.Util;
namespace Encog.MathUtil.Matrices.Decomposition
{
/// <summary>
/// Singular Value Decomposition.
///
/// For an m-by-n matrix A with m >= n, the singular value decomposition is an
/// m-by-n orthogonal matrix U, an n-by-n diagonal matrix S, and an n-by-n
/// orthogonal matrix V so that A = U*S*V'.
///
/// The singular values, sigma[k] = S[k][k], are ordered so that sigma[0] >=
/// sigma[1] >= ... >= sigma[n-1].
///
/// The singular value decompostion always exists, so the constructor will never
/// fail. The matrix condition number and the effective numerical rank can be
/// computed from this decomposition.
///
/// This file based on a class from the public domain JAMA package.
/// http://math.nist.gov/javanumerics/jama/
/// </summary>
public class SingularValueDecomposition
{
/// <summary>
/// rows
/// </summary>
private readonly int m;
/// <summary>
/// cols
/// </summary>
private readonly int n;
/// <summary>
/// Array for internal storage of singular values.
/// </summary>
private readonly double[] s;
/// <summary>
/// The U matrix.
/// </summary>
private readonly double[][] umatrix;
/// <summary>
/// The V matrix.
/// </summary>
private readonly double[][] vmatrix;
/// <summary>
/// Construct the singular value decomposition
/// </summary>
/// <param name="Arg">Rectangular matrix</param>
public SingularValueDecomposition(Matrix Arg)
{
// Derived from LINPACK code.
// Initialize.
double[][] A = Arg.GetArrayCopy();
m = Arg.Rows;
n = Arg.Cols;
/*
* Apparently the failing cases are only a proper subset of (m<n), so
* let's not throw error. Correct fix to come later? if (m<n) { throw
* new IllegalArgumentException("Jama SVD only works for m >= n"); }
*/
int nu = Math.Min(m, n);
s = new double[Math.Min(m + 1, n)];
umatrix = EngineArray.AllocateDouble2D(m, nu);
vmatrix = EngineArray.AllocateDouble2D(n, n);
var e = new double[n];
var work = new double[m];
bool wantu = true;
bool wantv = true;
// Reduce A to bidiagonal form, storing the diagonal elements
// in s and the super-diagonal elements in e.
int nct = Math.Min(m - 1, n);
int nrt = Math.Max(0, Math.Min(n - 2, m));
for (int k = 0; k < Math.Max(nct, nrt); k++)
{
if (k < nct)
{
// Compute the transformation for the k-th column and
// place the k-th diagonal in s[k].
// Compute 2-norm of k-th column without under/overflow.
s[k] = 0;
for (int i = k; i < m; i++)
{
s[k] = EncogMath.Hypot(s[k], A[i][k]);
}
if (s[k] != 0.0)
{
if (A[k][k] < 0.0)
{
s[k] = -s[k];
}
for (int i = k; i < m; i++)
{
A[i][k] /= s[k];
}
A[k][k] += 1.0;
}
s[k] = -s[k];
}
for (int j = k + 1; j < n; j++)
{
if ((k < nct) & (s[k] != 0.0))
{
// Apply the transformation.
double t = 0;
for (int i = k; i < m; i++)
{
t += A[i][k]*A[i][j];
}
t = -t/A[k][k];
for (int i = k; i < m; i++)
{
A[i][j] += t*A[i][k];
}
}
// Place the k-th row of A into e for the
// subsequent calculation of the row transformation.
e[j] = A[k][j];
}
if (wantu & (k < nct))
{
// Place the transformation in U for subsequent back
// multiplication.
for (int i = k; i < m; i++)
{
umatrix[i][k] = A[i][k];
}
}
if (k < nrt)
{
// Compute the k-th row transformation and place the
// k-th super-diagonal in e[k].
// Compute 2-norm without under/overflow.
e[k] = 0;
for (int i = k + 1; i < n; i++)
{
e[k] = EncogMath.Hypot(e[k], e[i]);
}
if (e[k] != 0.0)
{
if (e[k + 1] < 0.0)
{
e[k] = -e[k];
}
for (int i = k + 1; i < n; i++)
{
e[i] /= e[k];
}
e[k + 1] += 1.0;
}
e[k] = -e[k];
if ((k + 1 < m) & (e[k] != 0.0))
{
// Apply the transformation.
for (int i = k + 1; i < m; i++)
{
work[i] = 0.0;
}
for (int j = k + 1; j < n; j++)
{
for (int i = k + 1; i < m; i++)
{
work[i] += e[j]*A[i][j];
}
}
for (int j = k + 1; j < n; j++)
{
double t = -e[j]/e[k + 1];
for (int i = k + 1; i < m; i++)
{
A[i][j] += t*work[i];
}
}
}
if (wantv)
{
// Place the transformation in V for subsequent
// back multiplication.
for (int i = k + 1; i < n; i++)
{
vmatrix[i][k] = e[i];
}
}
}
}
// Set up the final bidiagonal matrix or order p.
int p = Math.Min(n, m + 1);
if (nct < n)
{
s[nct] = A[nct][nct];
}
if (m < p)
{
s[p - 1] = 0.0;
}
if (nrt + 1 < p)
{
e[nrt] = A[nrt][p - 1];
}
e[p - 1] = 0.0;
// If required, generate U.
if (wantu)
{
for (int j = nct; j < nu; j++)
{
for (int i = 0; i < m; i++)
{
umatrix[i][j] = 0.0;
}
umatrix[j][j] = 1.0;
}
for (int k = nct - 1; k >= 0; k--)
{
if (s[k] != 0.0)
{
for (int j = k + 1; j < nu; j++)
{
double t = 0;
for (int i = k; i < m; i++)
{
t += umatrix[i][k]*umatrix[i][j];
}
t = -t/umatrix[k][k];
for (int i = k; i < m; i++)
{
umatrix[i][j] += t*umatrix[i][k];
}
}
for (int i = k; i < m; i++)
{
umatrix[i][k] = -umatrix[i][k];
}
umatrix[k][k] = 1.0 + umatrix[k][k];
for (int i = 0; i < k - 1; i++)
{
umatrix[i][k] = 0.0;
}
}
else
{
for (int i = 0; i < m; i++)
{
umatrix[i][k] = 0.0;
}
umatrix[k][k] = 1.0;
}
}
}
// If required, generate V.
if (wantv)
{
for (int k = n - 1; k >= 0; k--)
{
if ((k < nrt) & (e[k] != 0.0))
{
for (int j = k + 1; j < nu; j++)
{
double t = 0;
for (int i = k + 1; i < n; i++)
{
t += vmatrix[i][k]*vmatrix[i][j];
}
t = -t/vmatrix[k + 1][k];
for (int i = k + 1; i < n; i++)
{
vmatrix[i][j] += t*vmatrix[i][k];
}
}
}
for (int i = 0; i < n; i++)
{
vmatrix[i][k] = 0.0;
}
vmatrix[k][k] = 1.0;
}
}
// Main iteration loop for the singular values.
int pp = p - 1;
int iter = 0;
double eps = Math.Pow(2.0, -52.0);
double tiny = Math.Pow(2.0, -966.0);
while (p > 0)
{
int k, kase;
// Here is where a test for too many iterations would go.
// This section of the program inspects for
// negligible elements in the s and e arrays. On
// completion the variables kase and k are set as follows.
// kase = 1 if s(p) and e[k-1] are negligible and k<p
// kase = 2 if s(k) is negligible and k<p
// kase = 3 if e[k-1] is negligible, k<p, and
// s(k), ..., s(p) are not negligible (qr step).
// kase = 4 if e(p-1) is negligible (convergence).
for (k = p - 2; k >= -1; k--)
{
if (k == -1)
{
break;
}
if (Math.Abs(e[k]) <= tiny + eps
*(Math.Abs(s[k]) + Math.Abs(s[k + 1])))
{
e[k] = 0.0;
break;
}
}
if (k == p - 2)
{
kase = 4;
}
else
{
int ks;
for (ks = p - 1; ks >= k; ks--)
{
if (ks == k)
{
break;
}
double t = (ks != p ? Math.Abs(e[ks]) : 0.0)
+ (ks != k + 1 ? Math.Abs(e[ks - 1]) : 0.0);
if (Math.Abs(s[ks]) <= tiny + eps*t)
{
s[ks] = 0.0;
break;
}
}
if (ks == k)
{
kase = 3;
}
else if (ks == p - 1)
{
kase = 1;
}
else
{
kase = 2;
k = ks;
}
}
k++;
// Perform the task indicated by kase.
switch (kase)
{
// Deflate negligible s(p).
case 1:
{
double f = e[p - 2];
e[p - 2] = 0.0;
for (int j = p - 2; j >= k; j--)
{
double t = EncogMath.Hypot(s[j], f);
double cs = s[j]/t;
double sn = f/t;
s[j] = t;
if (j != k)
{
f = -sn*e[j - 1];
e[j - 1] = cs*e[j - 1];
}
if (wantv)
{
for (int i = 0; i < n; i++)
{
t = cs*vmatrix[i][j] + sn*vmatrix[i][p - 1];
vmatrix[i][p - 1] = -sn*vmatrix[i][j] + cs*vmatrix[i][p - 1];
vmatrix[i][j] = t;
}
}
}
}
break;
// Split at negligible s(k).
case 2:
{
double f = e[k - 1];
e[k - 1] = 0.0;
for (int j = k; j < p; j++)
{
double t = EncogMath.Hypot(s[j], f);
double cs = s[j]/t;
double sn = f/t;
s[j] = t;
f = -sn*e[j];
e[j] = cs*e[j];
if (wantu)
{
for (int i = 0; i < m; i++)
{
t = cs*umatrix[i][j] + sn*umatrix[i][k - 1];
umatrix[i][k - 1] = -sn*umatrix[i][j] + cs*umatrix[i][k - 1];
umatrix[i][j] = t;
}
}
}
}
break;
// Perform one qr step.
case 3:
{
// Calculate the shift.
double scale = Math.Max(Math.Max(Math
.Max(Math.Max(Math.Abs(s[p - 1]), Math.Abs(s[p - 2])),
Math.Abs(e[p - 2])), Math.Abs(s[k])), Math
.Abs(
e[k]));
double sp = s[p - 1]/scale;
double spm1 = s[p - 2]/scale;
double epm1 = e[p - 2]/scale;
double sk = s[k]/scale;
double ek = e[k]/scale;
double b = ((spm1 + sp)*(spm1 - sp) + epm1*epm1)/2.0;
double c = (sp*epm1)*(sp*epm1);
double shift = 0.0;
if ((b != 0.0) | (c != 0.0))
{
shift = Math.Sqrt(b*b + c);
if (b < 0.0)
{
shift = -shift;
}
shift = c/(b + shift);
}
double f = (sk + sp)*(sk - sp) + shift;
double g = sk*ek;
// Chase zeros.
for (int j = k; j < p - 1; j++)
{
double t = EncogMath.Hypot(f, g);
double cs = f/t;
double sn = g/t;
if (j != k)
{
e[j - 1] = t;
}
f = cs*s[j] + sn*e[j];
e[j] = cs*e[j] - sn*s[j];
g = sn*s[j + 1];
s[j + 1] = cs*s[j + 1];
if (wantv)
{
for (int i = 0; i < n; i++)
{
t = cs*vmatrix[i][j] + sn*vmatrix[i][j + 1];
vmatrix[i][j + 1] = -sn*vmatrix[i][j] + cs*vmatrix[i][j + 1];
vmatrix[i][j] = t;
}
}
t = EncogMath.Hypot(f, g);
cs = f/t;
sn = g/t;
s[j] = t;
f = cs*e[j] + sn*s[j + 1];
s[j + 1] = -sn*e[j] + cs*s[j + 1];
g = sn*e[j + 1];
e[j + 1] = cs*e[j + 1];
if (wantu && (j < m - 1))
{
for (int i = 0; i < m; i++)
{
t = cs*umatrix[i][j] + sn*umatrix[i][j + 1];
umatrix[i][j + 1] = -sn*umatrix[i][j] + cs*umatrix[i][j + 1];
umatrix[i][j] = t;
}
}
}
e[p - 2] = f;
iter = iter + 1;
}
break;
// Convergence.
case 4:
{
// Make the singular values positive.
if (s[k] <= 0.0)
{
s[k] = (s[k] < 0.0 ? -s[k] : 0.0);
if (wantv)
{
for (int i = 0; i <= pp; i++)
{
vmatrix[i][k] = -vmatrix[i][k];
}
}
}
// Order the singular values.
while (k < pp)
{
if (s[k] >= s[k + 1])
{
break;
}
double t = s[k];
s[k] = s[k + 1];
s[k + 1] = t;
if (wantv && (k < n - 1))
{
for (int i = 0; i < n; i++)
{
t = vmatrix[i][k + 1];
vmatrix[i][k + 1] = vmatrix[i][k];
vmatrix[i][k] = t;
}
}
if (wantu && (k < m - 1))
{
for (int i = 0; i < m; i++)
{
t = umatrix[i][k + 1];
umatrix[i][k + 1] = umatrix[i][k];
umatrix[i][k] = t;
}
}
k++;
}
iter = 0;
p--;
}
break;
}
}
}
/// <summary>
/// Return the left singular vectors
/// </summary>
public Matrix U
{
get { return new Matrix(umatrix); }
}
/// <summary>
/// Return the right singular vectors
/// </summary>
public Matrix V
{
get { return new Matrix(vmatrix); }
}
/// <summary>
/// The singular values.
/// </summary>
public double[] SingularValues
{
get { return s; }
}
/// <summary>
/// Return the diagonal matrix of singular values
/// </summary>
public Matrix S
{
get
{
var x = new Matrix(n, n);
double[][] s = x.Data;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
s[i][j] = 0.0;
}
s[i][i] = this.s[i];
}
return x;
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public double Norm2()
{
return s[0];
}
/// <summary>
/// Two norm condition number
/// </summary>
/// <returns>max(S)/min(S)</returns>
public double Cond()
{
return s[0]/s[Math.Min(m, n) - 1];
}
/// <summary>
/// Effective numerical matrix rank
/// </summary>
/// <returns>The rank</returns>
public int Rank()
{
double eps = Math.Pow(2.0, -52.0);
double tol = Math.Max(m, n)*s[0]*eps;
int r = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] > tol)
{
r++;
}
}
return r;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
namespace Microsoft.Azure.Management.Automation
{
public static partial class RunbookOperationsExtensions
{
/// <summary>
/// Retrieve the content of runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <returns>
/// The response model for the runbook content operation.
/// </returns>
public static RunbookContentResponse Content(this IRunbookOperations operations, string resourceGroupName, string automationAccount, string runbookName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRunbookOperations)s).ContentAsync(resourceGroupName, automationAccount, runbookName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve the content of runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <returns>
/// The response model for the runbook content operation.
/// </returns>
public static Task<RunbookContentResponse> ContentAsync(this IRunbookOperations operations, string resourceGroupName, string automationAccount, string runbookName)
{
return operations.ContentAsync(resourceGroupName, automationAccount, runbookName, CancellationToken.None);
}
/// <summary>
/// Create the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The create or update parameters for runbook.
/// </param>
/// <returns>
/// The response model for the runbook create response.
/// </returns>
public static RunbookCreateOrUpdateResponse CreateOrUpdate(this IRunbookOperations operations, string resourceGroupName, string automationAccount, RunbookCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRunbookOperations)s).CreateOrUpdateAsync(resourceGroupName, automationAccount, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The create or update parameters for runbook.
/// </param>
/// <returns>
/// The response model for the runbook create response.
/// </returns>
public static Task<RunbookCreateOrUpdateResponse> CreateOrUpdateAsync(this IRunbookOperations operations, string resourceGroupName, string automationAccount, RunbookCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None);
}
/// <summary>
/// Create the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The create or update parameters for runbook.
/// </param>
/// <returns>
/// The response model for the runbook create response.
/// </returns>
public static RunbookCreateOrUpdateResponse CreateOrUpdateWithDraft(this IRunbookOperations operations, string resourceGroupName, string automationAccount, RunbookCreateOrUpdateDraftParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRunbookOperations)s).CreateOrUpdateWithDraftAsync(resourceGroupName, automationAccount, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The create or update parameters for runbook.
/// </param>
/// <returns>
/// The response model for the runbook create response.
/// </returns>
public static Task<RunbookCreateOrUpdateResponse> CreateOrUpdateWithDraftAsync(this IRunbookOperations operations, string resourceGroupName, string automationAccount, RunbookCreateOrUpdateDraftParameters parameters)
{
return operations.CreateOrUpdateWithDraftAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None);
}
/// <summary>
/// Delete the runbook by name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IRunbookOperations operations, string resourceGroupName, string automationAccount, string runbookName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRunbookOperations)s).DeleteAsync(resourceGroupName, automationAccount, runbookName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete the runbook by name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IRunbookOperations operations, string resourceGroupName, string automationAccount, string runbookName)
{
return operations.DeleteAsync(resourceGroupName, automationAccount, runbookName, CancellationToken.None);
}
/// <summary>
/// Retrieve the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <returns>
/// The response model for the get runbook operation.
/// </returns>
public static RunbookGetResponse Get(this IRunbookOperations operations, string resourceGroupName, string automationAccount, string runbookName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRunbookOperations)s).GetAsync(resourceGroupName, automationAccount, runbookName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <returns>
/// The response model for the get runbook operation.
/// </returns>
public static Task<RunbookGetResponse> GetAsync(this IRunbookOperations operations, string resourceGroupName, string automationAccount, string runbookName)
{
return operations.GetAsync(resourceGroupName, automationAccount, runbookName, CancellationToken.None);
}
/// <summary>
/// Retrieve a list of runbooks. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <returns>
/// The response model for the list runbook operation.
/// </returns>
public static RunbookListResponse List(this IRunbookOperations operations, string resourceGroupName, string automationAccount)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRunbookOperations)s).ListAsync(resourceGroupName, automationAccount);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve a list of runbooks. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <returns>
/// The response model for the list runbook operation.
/// </returns>
public static Task<RunbookListResponse> ListAsync(this IRunbookOperations operations, string resourceGroupName, string automationAccount)
{
return operations.ListAsync(resourceGroupName, automationAccount, CancellationToken.None);
}
/// <summary>
/// Retrieve next list of runbooks. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <returns>
/// The response model for the list runbook operation.
/// </returns>
public static RunbookListResponse ListNext(this IRunbookOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRunbookOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve next list of runbooks. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <returns>
/// The response model for the list runbook operation.
/// </returns>
public static Task<RunbookListResponse> ListNextAsync(this IRunbookOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
/// <summary>
/// Update the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The patch parameters for runbook.
/// </param>
/// <returns>
/// The response model for the get runbook operation.
/// </returns>
public static RunbookGetResponse Patch(this IRunbookOperations operations, string resourceGroupName, string automationAccount, RunbookPatchParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRunbookOperations)s).PatchAsync(resourceGroupName, automationAccount, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Update the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IRunbookOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The patch parameters for runbook.
/// </param>
/// <returns>
/// The response model for the get runbook operation.
/// </returns>
public static Task<RunbookGetResponse> PatchAsync(this IRunbookOperations operations, string resourceGroupName, string automationAccount, RunbookPatchParameters parameters)
{
return operations.PatchAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: controlmessage.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace CloudFoundry.Dropsonde.Control {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Controlmessage {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_control_ControlMessage__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::CloudFoundry.Dropsonde.Control.ControlMessage, global::CloudFoundry.Dropsonde.Control.ControlMessage.Builder> internal__static_control_ControlMessage__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static Controlmessage() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChRjb250cm9sbWVzc2FnZS5wcm90bxIHY29udHJvbBoWaGVhcnRiZWF0cmVx",
"dWVzdC5wcm90bxoKdXVpZC5wcm90byLqAQoOQ29udHJvbE1lc3NhZ2USDgoG",
"b3JpZ2luGAEgAigJEiEKCmlkZW50aWZpZXIYAiACKAsyDS5jb250cm9sLlVV",
"SUQSEQoJdGltZXN0YW1wGAMgAigDEjgKC2NvbnRyb2xUeXBlGAQgAigOMiMu",
"Y29udHJvbC5Db250cm9sTWVzc2FnZS5Db250cm9sVHlwZRIzChBoZWFydGJl",
"YXRSZXF1ZXN0GAUgASgLMhkuY29udHJvbC5IZWFydGJlYXRSZXF1ZXN0IiMK",
"C0NvbnRyb2xUeXBlEhQKEEhlYXJ0YmVhdFJlcXVlc3QQAUIhqgIeQ2xvdWRG",
"b3VuZHJ5LkRyb3Bzb25kZS5Db250cm9s"));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_control_ControlMessage__Descriptor = Descriptor.MessageTypes[0];
internal__static_control_ControlMessage__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::CloudFoundry.Dropsonde.Control.ControlMessage, global::CloudFoundry.Dropsonde.Control.ControlMessage.Builder>(internal__static_control_ControlMessage__Descriptor,
new string[] { "Origin", "Identifier", "Timestamp", "ControlType", "HeartbeatRequest", });
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
global::CloudFoundry.Dropsonde.Control.Heartbeatrequest.RegisterAllExtensions(registry);
global::CloudFoundry.Dropsonde.Control.Uuid.RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
global::CloudFoundry.Dropsonde.Control.Heartbeatrequest.Descriptor,
global::CloudFoundry.Dropsonde.Control.Uuid.Descriptor,
}, assigner);
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ControlMessage : pb::GeneratedMessage<ControlMessage, ControlMessage.Builder> {
private ControlMessage() { }
private static readonly ControlMessage defaultInstance = new ControlMessage().MakeReadOnly();
private static readonly string[] _controlMessageFieldNames = new string[] { "controlType", "heartbeatRequest", "identifier", "origin", "timestamp" };
private static readonly uint[] _controlMessageFieldTags = new uint[] { 32, 42, 18, 10, 24 };
public static ControlMessage DefaultInstance {
get { return defaultInstance; }
}
public override ControlMessage DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override ControlMessage ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::CloudFoundry.Dropsonde.Control.Controlmessage.internal__static_control_ControlMessage__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<ControlMessage, ControlMessage.Builder> InternalFieldAccessors {
get { return global::CloudFoundry.Dropsonde.Control.Controlmessage.internal__static_control_ControlMessage__FieldAccessorTable; }
}
#region Nested types
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Types {
public enum ControlType {
HeartbeatRequest = 1,
}
}
#endregion
public const int OriginFieldNumber = 1;
private bool hasOrigin;
private string origin_ = "";
public bool HasOrigin {
get { return hasOrigin; }
}
public string Origin {
get { return origin_; }
}
public const int IdentifierFieldNumber = 2;
private bool hasIdentifier;
private global::CloudFoundry.Dropsonde.Control.UUID identifier_;
public bool HasIdentifier {
get { return hasIdentifier; }
}
public global::CloudFoundry.Dropsonde.Control.UUID Identifier {
get { return identifier_ ?? global::CloudFoundry.Dropsonde.Control.UUID.DefaultInstance; }
}
public const int TimestampFieldNumber = 3;
private bool hasTimestamp;
private long timestamp_;
public bool HasTimestamp {
get { return hasTimestamp; }
}
public long Timestamp {
get { return timestamp_; }
}
public const int ControlTypeFieldNumber = 4;
private bool hasControlType;
private global::CloudFoundry.Dropsonde.Control.ControlMessage.Types.ControlType controlType_ = global::CloudFoundry.Dropsonde.Control.ControlMessage.Types.ControlType.HeartbeatRequest;
public bool HasControlType {
get { return hasControlType; }
}
public global::CloudFoundry.Dropsonde.Control.ControlMessage.Types.ControlType ControlType {
get { return controlType_; }
}
public const int HeartbeatRequestFieldNumber = 5;
private bool hasHeartbeatRequest;
private global::CloudFoundry.Dropsonde.Control.HeartbeatRequest heartbeatRequest_;
public bool HasHeartbeatRequest {
get { return hasHeartbeatRequest; }
}
public global::CloudFoundry.Dropsonde.Control.HeartbeatRequest HeartbeatRequest {
get { return heartbeatRequest_ ?? global::CloudFoundry.Dropsonde.Control.HeartbeatRequest.DefaultInstance; }
}
public override bool IsInitialized {
get {
if (!hasOrigin) return false;
if (!hasIdentifier) return false;
if (!hasTimestamp) return false;
if (!hasControlType) return false;
if (!Identifier.IsInitialized) return false;
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _controlMessageFieldNames;
if (hasOrigin) {
output.WriteString(1, field_names[3], Origin);
}
if (hasIdentifier) {
output.WriteMessage(2, field_names[2], Identifier);
}
if (hasTimestamp) {
output.WriteInt64(3, field_names[4], Timestamp);
}
if (hasControlType) {
output.WriteEnum(4, field_names[0], (int) ControlType, ControlType);
}
if (hasHeartbeatRequest) {
output.WriteMessage(5, field_names[1], HeartbeatRequest);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasOrigin) {
size += pb::CodedOutputStream.ComputeStringSize(1, Origin);
}
if (hasIdentifier) {
size += pb::CodedOutputStream.ComputeMessageSize(2, Identifier);
}
if (hasTimestamp) {
size += pb::CodedOutputStream.ComputeInt64Size(3, Timestamp);
}
if (hasControlType) {
size += pb::CodedOutputStream.ComputeEnumSize(4, (int) ControlType);
}
if (hasHeartbeatRequest) {
size += pb::CodedOutputStream.ComputeMessageSize(5, HeartbeatRequest);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static ControlMessage ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ControlMessage ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ControlMessage ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ControlMessage ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ControlMessage ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ControlMessage ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static ControlMessage ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static ControlMessage ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static ControlMessage ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ControlMessage ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private ControlMessage MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(ControlMessage prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<ControlMessage, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(ControlMessage cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private ControlMessage result;
private ControlMessage PrepareBuilder() {
if (resultIsReadOnly) {
ControlMessage original = result;
result = new ControlMessage();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override ControlMessage MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::CloudFoundry.Dropsonde.Control.ControlMessage.Descriptor; }
}
public override ControlMessage DefaultInstanceForType {
get { return global::CloudFoundry.Dropsonde.Control.ControlMessage.DefaultInstance; }
}
public override ControlMessage BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is ControlMessage) {
return MergeFrom((ControlMessage) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(ControlMessage other) {
if (other == global::CloudFoundry.Dropsonde.Control.ControlMessage.DefaultInstance) return this;
PrepareBuilder();
if (other.HasOrigin) {
Origin = other.Origin;
}
if (other.HasIdentifier) {
MergeIdentifier(other.Identifier);
}
if (other.HasTimestamp) {
Timestamp = other.Timestamp;
}
if (other.HasControlType) {
ControlType = other.ControlType;
}
if (other.HasHeartbeatRequest) {
MergeHeartbeatRequest(other.HeartbeatRequest);
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_controlMessageFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _controlMessageFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 10: {
result.hasOrigin = input.ReadString(ref result.origin_);
break;
}
case 18: {
global::CloudFoundry.Dropsonde.Control.UUID.Builder subBuilder = global::CloudFoundry.Dropsonde.Control.UUID.CreateBuilder();
if (result.hasIdentifier) {
subBuilder.MergeFrom(Identifier);
}
input.ReadMessage(subBuilder, extensionRegistry);
Identifier = subBuilder.BuildPartial();
break;
}
case 24: {
result.hasTimestamp = input.ReadInt64(ref result.timestamp_);
break;
}
case 32: {
object unknown;
if(input.ReadEnum(ref result.controlType_, out unknown)) {
result.hasControlType = true;
} else if(unknown is int) {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
unknownFields.MergeVarintField(4, (ulong)(int)unknown);
}
break;
}
case 42: {
global::CloudFoundry.Dropsonde.Control.HeartbeatRequest.Builder subBuilder = global::CloudFoundry.Dropsonde.Control.HeartbeatRequest.CreateBuilder();
if (result.hasHeartbeatRequest) {
subBuilder.MergeFrom(HeartbeatRequest);
}
input.ReadMessage(subBuilder, extensionRegistry);
HeartbeatRequest = subBuilder.BuildPartial();
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasOrigin {
get { return result.hasOrigin; }
}
public string Origin {
get { return result.Origin; }
set { SetOrigin(value); }
}
public Builder SetOrigin(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasOrigin = true;
result.origin_ = value;
return this;
}
public Builder ClearOrigin() {
PrepareBuilder();
result.hasOrigin = false;
result.origin_ = "";
return this;
}
public bool HasIdentifier {
get { return result.hasIdentifier; }
}
public global::CloudFoundry.Dropsonde.Control.UUID Identifier {
get { return result.Identifier; }
set { SetIdentifier(value); }
}
public Builder SetIdentifier(global::CloudFoundry.Dropsonde.Control.UUID value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasIdentifier = true;
result.identifier_ = value;
return this;
}
public Builder SetIdentifier(global::CloudFoundry.Dropsonde.Control.UUID.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
PrepareBuilder();
result.hasIdentifier = true;
result.identifier_ = builderForValue.Build();
return this;
}
public Builder MergeIdentifier(global::CloudFoundry.Dropsonde.Control.UUID value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
if (result.hasIdentifier &&
result.identifier_ != global::CloudFoundry.Dropsonde.Control.UUID.DefaultInstance) {
result.identifier_ = global::CloudFoundry.Dropsonde.Control.UUID.CreateBuilder(result.identifier_).MergeFrom(value).BuildPartial();
} else {
result.identifier_ = value;
}
result.hasIdentifier = true;
return this;
}
public Builder ClearIdentifier() {
PrepareBuilder();
result.hasIdentifier = false;
result.identifier_ = null;
return this;
}
public bool HasTimestamp {
get { return result.hasTimestamp; }
}
public long Timestamp {
get { return result.Timestamp; }
set { SetTimestamp(value); }
}
public Builder SetTimestamp(long value) {
PrepareBuilder();
result.hasTimestamp = true;
result.timestamp_ = value;
return this;
}
public Builder ClearTimestamp() {
PrepareBuilder();
result.hasTimestamp = false;
result.timestamp_ = 0L;
return this;
}
public bool HasControlType {
get { return result.hasControlType; }
}
public global::CloudFoundry.Dropsonde.Control.ControlMessage.Types.ControlType ControlType {
get { return result.ControlType; }
set { SetControlType(value); }
}
public Builder SetControlType(global::CloudFoundry.Dropsonde.Control.ControlMessage.Types.ControlType value) {
PrepareBuilder();
result.hasControlType = true;
result.controlType_ = value;
return this;
}
public Builder ClearControlType() {
PrepareBuilder();
result.hasControlType = false;
result.controlType_ = global::CloudFoundry.Dropsonde.Control.ControlMessage.Types.ControlType.HeartbeatRequest;
return this;
}
public bool HasHeartbeatRequest {
get { return result.hasHeartbeatRequest; }
}
public global::CloudFoundry.Dropsonde.Control.HeartbeatRequest HeartbeatRequest {
get { return result.HeartbeatRequest; }
set { SetHeartbeatRequest(value); }
}
public Builder SetHeartbeatRequest(global::CloudFoundry.Dropsonde.Control.HeartbeatRequest value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasHeartbeatRequest = true;
result.heartbeatRequest_ = value;
return this;
}
public Builder SetHeartbeatRequest(global::CloudFoundry.Dropsonde.Control.HeartbeatRequest.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
PrepareBuilder();
result.hasHeartbeatRequest = true;
result.heartbeatRequest_ = builderForValue.Build();
return this;
}
public Builder MergeHeartbeatRequest(global::CloudFoundry.Dropsonde.Control.HeartbeatRequest value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
if (result.hasHeartbeatRequest &&
result.heartbeatRequest_ != global::CloudFoundry.Dropsonde.Control.HeartbeatRequest.DefaultInstance) {
result.heartbeatRequest_ = global::CloudFoundry.Dropsonde.Control.HeartbeatRequest.CreateBuilder(result.heartbeatRequest_).MergeFrom(value).BuildPartial();
} else {
result.heartbeatRequest_ = value;
}
result.hasHeartbeatRequest = true;
return this;
}
public Builder ClearHeartbeatRequest() {
PrepareBuilder();
result.hasHeartbeatRequest = false;
result.heartbeatRequest_ = null;
return this;
}
}
static ControlMessage() {
object.ReferenceEquals(global::CloudFoundry.Dropsonde.Control.Controlmessage.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using Lucene.Net.Linq;
using Moq;
using NuGet.Lucene.IO;
using NUnit.Framework;
using Remotion.Linq.Clauses.ResultOperators;
namespace NuGet.Lucene.Tests
{
[TestFixture]
public class LucenePackageRepositoryTests : TestBase
{
private Mock<IPackageIndexer> indexer;
private TestableLucenePackageRepository repository;
[SetUp]
public void SetUp()
{
indexer = new Mock<IPackageIndexer>();
repository = new TestableLucenePackageRepository(packagePathResolver.Object, fileSystem.Object)
{
Indexer = indexer.Object,
LucenePackages = datasource,
LuceneDataProvider = provider,
HashProvider = new CryptoHashProvider()
};
}
public class InitializeTests : LucenePackageRepositoryTests
{
[Test]
public void UpdatesTotalPackages()
{
var p = MakeSamplePackage("a", "1.0");
repository.LucenePackages = new EnumerableQuery<LucenePackage>(Enumerable.Repeat(p, 1234));
repository.Initialize();
Assert.That(repository.PackageCount, Is.EqualTo(repository.LucenePackages.Count()));
}
}
public class IncrementDownloadCountTests : LucenePackageRepositoryTests
{
[Test]
public async Task IncrementDownloadCount()
{
var pkg = MakeSamplePackage("sample", "2.1");
indexer.Setup(i => i.IncrementDownloadCountAsync(pkg, CancellationToken.None)).Returns(Task.FromResult(true)).Verifiable();
await repository.IncrementDownloadCountAsync(pkg, CancellationToken.None);
indexer.Verify();
}
}
public class FindPackageTests : LucenePackageRepositoryTests
{
[Test]
public void FindPackage()
{
InsertPackage("a", "1.0");
InsertPackage("a", "2.0");
InsertPackage("b", "2.0");
var result = repository.FindPackage("a", new SemanticVersion("2.0"));
Assert.That(result.Id, Is.EqualTo("a"));
Assert.That(result.Version.ToString(), Is.EqualTo("2.0"));
}
[Test]
public void FindPackage_ExactMatch()
{
InsertPackage("a", "1.0");
InsertPackage("a", "1.0.0.0");
var result = repository.FindPackage("a", new SemanticVersion("1.0.0.0"));
Assert.That(result.Id, Is.EqualTo("a"));
Assert.That(result.Version.ToString(), Is.EqualTo("1.0.0.0"));
}
}
public class ConvertPackageTests : LucenePackageRepositoryTests
{
[Test]
public void TrimsAuthors()
{
var package = SetUpConvertPackage();
package.SetupGet(p => p.Authors).Returns(new[] {"a", " b"});
package.SetupGet(p => p.Owners).Returns(new[] { "c", " d" });
var result = repository.Convert(package.Object);
Assert.That(result.Authors.ToArray(), Is.EqualTo(new[] {"a", "b"}));
Assert.That(result.Owners.ToArray(), Is.EqualTo(new[] {"c", "d"}));
}
[Test]
public void SupportedFrameworks()
{
var package = SetUpConvertPackage();
package.Setup(p => p.GetSupportedFrameworks()).Returns(new[] { VersionUtility.ParseFrameworkName("net40") });
var result = repository.Convert(package.Object);
Assert.That(result.SupportedFrameworks, Is.Not.Null, "SupportedFrameworks");
Assert.That(result.SupportedFrameworks.ToArray(), Is.EquivalentTo(new[] {"net40"}));
}
[Test]
[TestCase("magicsauce", "magicsauce", "0.0", "")]
[TestCase("magicsauce-lite", "magicsauce", "0.0", "lite")]
[TestCase("magicsauce12", "magicsauce", "1.2", "")]
[TestCase("magicsauce123-lite", "magicsauce", "1.2.3", "lite")]
public void SupportedFrameworks_Custom(string expected, string identifier, string version, string profile)
{
var package = SetUpConvertPackage();
package.Setup(p => p.GetSupportedFrameworks()).Returns(new[] { new FrameworkName(identifier, new Version(version), profile) });
var result = repository.Convert(package.Object);
Assert.That(result.SupportedFrameworks, Is.Not.Null, "SupportedFrameworks");
Assert.That(result.SupportedFrameworks.ToArray(), Is.EquivalentTo(new[] { expected }));
}
[Test]
public void DetectsInvalidModifiedTime()
{
var package = SetUpConvertPackage();
Assert.That(package.Object.Version, Is.Not.Null);
fileSystem.Setup(fs => fs.GetLastModified(It.IsAny<string>()))
.Returns(new DateTime(1601, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
Assert.That(package.Object.Version, Is.Not.Null);
var result = repository.Convert(package.Object);
Assert.That(result.Published, Is.EqualTo(result.Created));
}
[Test]
public void Files()
{
var file1 = new Mock<IPackageFile>();
file1.SetupGet(f => f.Path).Returns("path1");
var package = new PackageWithFiles
{
Id = "Sample",
Version = new SemanticVersion("1.0"),
Files = new[] {file1.Object}
};
fileSystem.Setup(fs => fs.OpenFile(It.IsAny<string>())).Returns(new MemoryStream());
var result = repository.Convert(package);
Assert.That(result.Files, Is.Not.Null, "Files");
Assert.That(result.Files.ToArray(), Is.EquivalentTo(new[] {"path1"}));
}
[Test]
public void FilesSkippedWhenDisabled()
{
var file1 = new Mock<IPackageFile>();
file1.SetupGet(f => f.Path).Returns("path1");
var package = new PackageWithFiles
{
Id = "Sample",
Version = new SemanticVersion("1.0"),
Files = new[] { file1.Object }
};
fileSystem.Setup(fs => fs.OpenFile(It.IsAny<string>())).Returns(new MemoryStream());
repository.IgnorePackageFiles = true;
var result = repository.Convert(package);
Assert.That(result.Files, Is.Not.Null, "Files");
Assert.That(result.Files.ToArray(), Is.Empty);
}
[Test]
public void RemovesPlaceholderUrls()
{
var package = SetUpConvertPackage();
package.SetupGet(p => p.IconUrl).Returns(new Uri("http://ICON_URL_HERE_OR_DELETE_THIS_LINE"));
package.SetupGet(p => p.LicenseUrl).Returns(new Uri("http://LICENSE_URL_HERE_OR_DELETE_THIS_LINE"));
package.SetupGet(p => p.ProjectUrl).Returns(new Uri("http://PROJECT_URL_HERE_OR_DELETE_THIS_LINE"));
var result = repository.Convert(package.Object);
Assert.That(result.IconUrl, Is.Null, "IconUrl");
Assert.That(result.LicenseUrl, Is.Null, "LicenseUrl");
Assert.That(result.ProjectUrl, Is.Null, "ProjectUrl");
}
[Test]
public void SetsPath()
{
var package = SetUpConvertPackage();
var result = repository.Convert(package.Object);
Assert.That(result.Path, Is.EqualTo(Path.Combine("package-dir", "Sample.1.0")));
}
[Test]
public void SetsNormalizedVersion()
{
var package = SetUpConvertPackage();
package.SetupGet(p => p.Version).Returns(new SemanticVersion("1.0.0.0"));
var result = repository.Convert(package.Object);
Assert.That(result.NormalizedVersion, Is.EqualTo("1.0.0"));
}
}
public class GetUpdatesTests : LucenePackageRepositoryTests
{
[Test]
public void GetUpdates()
{
var a1 = MakeSamplePackage("a", "1.0");
var a2 = MakeSamplePackage("a", "2.0");
var a3 = MakeSamplePackage("a", "3.0");
a3.IsLatestVersion = true;
InsertPackage(a1);
InsertPackage(a2);
InsertPackage(a3);
var result = repository.GetUpdates(new[] {a1}, false, false, new FrameworkName[0]);
Assert.That(result.Single().Version.ToString(), Is.EqualTo(a3.Version.ToString()));
}
[Test]
public void FilterByVersionConstraint()
{
var a1 = MakeSamplePackage("a", "1.0");
var a2 = MakeSamplePackage("a", "2.0");
var a3 = MakeSamplePackage("a", "3.0");
a3.IsLatestVersion = true;
InsertPackage(a1);
InsertPackage(a2);
InsertPackage(a3);
var constraints = new[] { VersionUtility.ParseVersionSpec("[1.0,2.0]") };
var result = repository.GetUpdates(new[] { a1 }, false, false, new FrameworkName[0], constraints);
Assert.That(result.Single().Version.ToString(), Is.EqualTo(a2.Version.ToString()));
}
[Test]
public void FilterByVersionConstraint_ExcludesCurrentVersion()
{
var a1 = MakeSamplePackage("a", "1.0");
var a2 = MakeSamplePackage("a", "2.0");
var a3 = MakeSamplePackage("a", "3.0");
a3.IsLatestVersion = true;
InsertPackage(a1);
InsertPackage(a2);
InsertPackage(a3);
var constraints = new[] { VersionUtility.ParseVersionSpec("[1.0,2.0]") };
var result = repository.GetUpdates(new[] { a2 }, false, false, new FrameworkName[0], constraints);
Assert.That(result.ToList(), Is.Empty);
}
[Test]
public void FilterByTargetFrameworkVersion()
{
var b1 = MakeSamplePackage("b", "1.0");
var a1 = MakeSamplePackage("a", "1.0");
var a2 = MakeSamplePackage("a", "2.0");
var a3 = MakeSamplePackage("a", "3.0");
a2.SupportedFrameworks = new[] {"net20"};
a3.SupportedFrameworks = new[] {"net451"};
a3.IsLatestVersion = true;
InsertPackage(b1);
InsertPackage(a1);
InsertPackage(a2);
InsertPackage(a3);
var result = repository.GetUpdates(new[] {b1, a1}, false, false, a2.GetSupportedFrameworks());
Assert.That(result.Single().Version.ToString(), Is.EqualTo(a2.Version.ToString()));
}
[Test]
public void IncludeAll()
{
var a1 = MakeSamplePackage("a", "1.0");
var a2 = MakeSamplePackage("a", "2.0-pre");
var a3 = MakeSamplePackage("a", "3.0");
a3.IsLatestVersion = true;
InsertPackage(a1);
InsertPackage(a2);
InsertPackage(a3);
var result = repository.GetUpdates(new[] {a1}, true, true, new FrameworkName[0]);
Assert.That(result.Select(p => p.Version.ToString()).ToArray(),
Is.EqualTo(new[] {a2.Version.ToString(), a3.Version.ToString()}));
}
}
public class SearchTests : LucenePackageRepositoryTests
{
[Test]
public void Id()
{
InsertPackage("Foo.Bar", "1.0");
var result = repository.Search(new SearchCriteria("Foo.Bar"));
Assert.That(result.Select(r => r.Id).ToArray(), Is.EqualTo(new[] {"Foo.Bar"}));
}
[Test]
public void AllVersions_OrderById_ImplicitlyThenByVersion()
{
InsertPackage("Foo.Bar", "1.0");
InsertPackage("Foo.Bar", "1.1");
InsertPackage("Foo.Bar", "1.2");
var result = repository.Search(new SearchCriteria("Foo.Bar") { SortField = SearchSortField.Id });
Assert.That(result.Select(r => r.Id + ' ' + r.Version).ToArray(), Is.EqualTo(new[] { "Foo.Bar 1.2", "Foo.Bar 1.1", "Foo.Bar 1.0" }));
}
[Test]
public void TokenizeId()
{
InsertPackage("Foo.Bar", "1.0");
InsertPackage("Foo.Baz", "1.0");
var result = repository.Search(new SearchCriteria("Bar"));
Assert.That(result.Select(r => r.Id).ToArray(), Is.EqualTo(new[] { "Foo.Bar" }));
}
[Test]
public void TokenizeIdPrefix()
{
InsertPackage("Foo.BarBell.ThingUpdater", "1.0");
InsertPackage("Foo.BarBell.OtherThing", "1.0");
var result = repository.Search(new SearchCriteria("Foo.BarBell"));
Assert.That(result.Select(r => r.Id).ToArray(), Is.EquivalentTo(new[] { "Foo.BarBell.ThingUpdater", "Foo.BarBell.OtherThing" }));
}
[Test]
public void TokenizeIdPrefix_LowerCase()
{
InsertPackage("Foo.BarBell.ThingUpdater", "1.0");
InsertPackage("Foo.BarBell.OtherThing", "1.0");
var result = repository.Search(new SearchCriteria("foo.barbell"));
Assert.That(result.Select(r => r.Id).ToArray(), Is.EquivalentTo(new[] { "Foo.BarBell.ThingUpdater", "Foo.BarBell.OtherThing" }));
}
[Test]
public void TokenizeIdPrefix_LowerCase_Full()
{
InsertPackage("Microsoft.AspNet.Razor", "1.0");
var result = repository.Search(new SearchCriteria("id:microsoft.aspnet.razor"));
Assert.That(result.Select(r => r.Id).ToArray(), Is.EquivalentTo(new[] { "Microsoft.AspNet.Razor" }));
}
[Test]
public void FilterOnTargetFramework_ExactMatch()
{
var pkg1 = MakeSamplePackage("Foo.Bar", "1.0");
pkg1.SupportedFrameworks = new[] {"net40"};
var pkg2 = MakeSamplePackage("Foo.Bar", "2.0");
pkg2.SupportedFrameworks = new[] { "net45" };
InsertPackage(pkg1);
InsertPackage(pkg2);
repository.Initialize();
var result = repository.Search(new SearchCriteria("id:Foo.Bar") { TargetFrameworks = new[] {"net40"} });
Assert.That(result.Select(r => r.Version).ToArray(), Is.EquivalentTo(new[] { pkg1.Version.SemanticVersion }));
}
[Test]
public void FilterOnTargetFramework_CaseInsensitive()
{
var pkg1 = MakeSamplePackage("Foo.Bar", "1.0");
pkg1.SupportedFrameworks = new[] { "net40-Client" };
InsertPackage(pkg1);
repository.Initialize();
var result = repository.Search(new SearchCriteria("id:Foo.Bar") { TargetFrameworks = new[] { "net40" } });
Assert.That(result.Select(r => r.Version).ToArray(), Is.EquivalentTo(new[] { pkg1.Version.SemanticVersion }));
}
[Test]
public void FilterOnTargetFramework_ExactMatch_NonStandardFramework()
{
var pkg1 = MakeSamplePackage("Foo.Bar", "1.0");
pkg1.SupportedFrameworks = new[] { "mono38" };
var pkg2 = MakeSamplePackage("Foo.Bar", "2.0");
pkg2.SupportedFrameworks = new[] { "net45" };
InsertPackage(pkg1);
InsertPackage(pkg2);
repository.Initialize();
var result = repository.Search(new SearchCriteria("id:Foo.Bar") { TargetFrameworks = new[] { "mono38" } });
Assert.That(result.Select(r => r.Version).ToArray(), Is.EquivalentTo(new[] { pkg1.Version.SemanticVersion }));
}
[Test]
public void FilterOnTargetFramework_CompatibleMatch()
{
var pkg1 = MakeSamplePackage("Foo.Bar", "1.0");
pkg1.SupportedFrameworks = new[] { "net20" };
var pkg2 = MakeSamplePackage("Foo.Bar", "2.0");
pkg2.SupportedFrameworks = new[] { "net45" };
InsertPackage(pkg1);
InsertPackage(pkg2);
repository.Initialize();
var result = repository.Search(new SearchCriteria("id:Foo.Bar") { TargetFrameworks = new[] { "net35" } });
Assert.That(result.Select(r => r.Version).ToArray(), Is.EquivalentTo(new[] { pkg1.Version.SemanticVersion }));
}
[Test]
public void FilterOnTargetFramework_CompatibleMatch_WithProfile()
{
var pkg1 = MakeSamplePackage("Foo.Bar", "1.0");
pkg1.SupportedFrameworks = new[] { "net40-cf" };
var pkg2 = MakeSamplePackage("Foo.Bar", "2.0");
pkg2.SupportedFrameworks = new[] { "net45" };
InsertPackage(pkg1);
InsertPackage(pkg2);
repository.Initialize();
var result = repository.Search(new SearchCriteria("id:Foo.Bar") { TargetFrameworks = new[] { "net40-cf" } });
Assert.That(result.Select(r => r.Version).ToArray(), Is.EquivalentTo(new[] { pkg1.Version.SemanticVersion }));
}
[Test]
public void FilterOnTargetFramework_Portable_ExactMatch()
{
var pkg1 = MakeSamplePackage("Foo.Bar", "1.0");
pkg1.SupportedFrameworks = new[] { "portable-net40+sl50+wp80+win80" };
var pkg2 = MakeSamplePackage("Foo.Bar", "2.0");
pkg2.SupportedFrameworks = new[] { "net45" };
InsertPackage(pkg1);
InsertPackage(pkg2);
repository.Initialize();
var result = repository.Search(new SearchCriteria("id:Foo.Bar") { TargetFrameworks = new[] { "portable-net40+sl50+wp80+win80" } });
Assert.That(result.Select(r => r.Version).ToArray(), Is.EquivalentTo(new[] { pkg1.Version.SemanticVersion }));
}
[Test]
public void FilterOnTargetFramework_CompatibleProfile()
{
var pkg1 = MakeSamplePackage("Foo.Bar", "1.0");
pkg1.SupportedFrameworks = new[] { "net40-client" };
var pkg2 = MakeSamplePackage("Foo.Bar", "2.0");
pkg2.SupportedFrameworks = new[] { "net45" };
InsertPackage(pkg1);
InsertPackage(pkg2);
repository.Initialize();
var result = repository.Search(new SearchCriteria("") { TargetFrameworks = new[] { "net40" } });
Assert.That(result.Select(r => r.Version).ToArray(), Is.EquivalentTo(new[] { pkg1.Version.SemanticVersion }));
}
[Test]
public void FilterOnTargetFramework_AllowsPackagesWithNoSupportedFrameworks()
{
var pkg1 = MakeSamplePackage("Foo.Bar", "1.0");
pkg1.SupportedFrameworks = new string[0];
var pkg2 = MakeSamplePackage("Yaz.Jazz", "2.0");
pkg2.SupportedFrameworks = new[] { "net45" };
InsertPackage(pkg1);
InsertPackage(pkg2);
repository.Initialize();
var result = repository.Search(new SearchCriteria("") { TargetFrameworks = new[] { "net40" } });
Assert.That(result.Select(r => r.Version).ToArray(), Is.EquivalentTo(new[] { pkg1.Version.SemanticVersion }));
}
[Test]
public void FileName()
{
var pkg = MakeSamplePackage("Foo.Bar", "1.0");
pkg.Files = new[] {"/lib/net45/baz.dll"};
InsertPackage(pkg);
var result = repository.Search(new SearchCriteria("baz.dll"));
Assert.That(result.Select(r => r.Id).ToArray(), Is.EqualTo(new[] { "Foo.Bar" }));
}
[Test]
public void FileNameCaseInsensitive()
{
var pkg = MakeSamplePackage("Foo.Bar", "1.0");
pkg.Files = new[] { "/lib/net45/Baz.DLL" };
InsertPackage(pkg);
var result = repository.Search(new SearchCriteria("baz.dll"));
Assert.That(result.Select(r => r.Id).ToArray(), Is.EqualTo(new[] { "Foo.Bar" }));
}
[Test]
public void FileNameFullPath()
{
var pkg = MakeSamplePackage("Foo.Bar", "1.0");
pkg.Files = new[] { "/lib/net45/baz.dll" };
InsertPackage(pkg);
var result = repository.Search(new SearchCriteria("/lib/net45/baz.dll"));
Assert.That(result.Select(r => r.Id).ToArray(), Is.EqualTo(new[] { "Foo.Bar" }));
}
[Test]
public void FileNameNoExtension()
{
var pkg = MakeSamplePackage("Foo.Bar", "1.0");
pkg.Files = new[] { "/lib/net45/Biz.Baz.DLL" };
InsertPackage(pkg);
var result = repository.Search(new SearchCriteria("Biz.Baz"));
Assert.That(result.Select(r => r.Id).ToArray(), Is.EqualTo(new[] { "Foo.Bar" }));
}
[Test]
public void FileNamePartialMatch()
{
var pkg = MakeSamplePackage("Foo.Bar", "1.0");
pkg.Files = new[] { "/lib/net45/Biz.Baz.DLL" };
InsertPackage(pkg);
var result = repository.Search(new SearchCriteria("Baz"));
Assert.That(result.Select(r => r.Id).ToArray(), Is.EqualTo(new[] { "Foo.Bar" }));
}
[Test]
public void UsesAdvancedWhenColonPresent()
{
var query = repository.Search("Tags:remoting", Enumerable.Empty<string>(), allowPrereleaseVersions: true);
AssertComputedQueryEquals(query, "Tags:remot");
}
[Test]
public void AdvancedQueryCaseInsensitiveField()
{
var query = repository.Search("tags:remoting", Enumerable.Empty<string>(), allowPrereleaseVersions: true);
AssertComputedQueryEquals(query, "Tags:remot");
}
[Test]
public void AdvancedSearchUsesFallbackField()
{
var query = repository.Search("NoSuchField:foo", Enumerable.Empty<string>(), allowPrereleaseVersions: true);
AssertComputedQueryEquals(query, "SearchId:foo");
}
[Test]
public void AdvancedSearchMalformedQueryThrows()
{
TestDelegate call = () => repository.Search("(Tags:foo", Enumerable.Empty<string>(), allowPrereleaseVersions: true);
Assert.That(call, Throws.InstanceOf<InvalidSearchCriteriaException>());
}
[Test]
[Description("See http://docs.nuget.org/docs/reference/search-syntax")]
public void AdvancedSearch_PackageId_ExactMatch()
{
var query = repository.Search("PackageId:Foo.Bar", Enumerable.Empty<string>(), allowPrereleaseVersions: true);
AssertComputedQueryEquals(query, "Id:foo.bar");
}
[Test]
[Description("See http://docs.nuget.org/docs/reference/search-syntax")]
public void AdvancedSearch_Id_FuzzyMatch()
{
var query = repository.Search("Id:Foo", Enumerable.Empty<string>(), allowPrereleaseVersions: true);
AssertComputedQueryEquals(query, "SearchId:foo");
}
private static void AssertComputedQueryEquals(IQueryable<IPackage> query, string expectedQuery)
{
LuceneQueryStatistics stats = null;
var result = query.CaptureStatistics(s => { stats = s; }).ToArray();
Assert.That(stats.Query.ToString(), Is.EqualTo(expectedQuery));
}
}
public class LoadFromFileSystemTests : LucenePackageRepositoryTests
{
readonly DateTime lastModified = new DateTime(2001, 5, 27, 0, 0, 0, DateTimeKind.Utc);
readonly string expectedPath = Path.Combine("a", "non", "standard", "package", "location.nupkg");
[Test]
public void LoadFromFileSystem()
{
SetupFileSystem();
repository.LoadFromFileSystem(expectedPath);
fileSystem.Verify();
}
[Test]
public void SetsPublishedDateToLastModified()
{
SetupFileSystem();
fileSystem.Setup(fs => fs.GetLastModified(It.IsAny<string>())).Returns(lastModified);
var result = repository.LoadFromFileSystem(expectedPath);
Assert.That(result.Published.GetValueOrDefault().DateTime, Is.EqualTo(lastModified));
}
[Test]
public void SetsPath()
{
SetupFileSystem();
var result = repository.LoadFromFileSystem(expectedPath);
Assert.That(result.Path, Is.EqualTo(expectedPath));
}
[Test]
public void MakesPathRelative()
{
SetupFileSystem();
var result = repository.LoadFromFileSystem(Path.Combine(Environment.CurrentDirectory, expectedPath));
Assert.That(result.Path, Is.EqualTo(expectedPath));
}
private void SetupFileSystem()
{
var root = Environment.CurrentDirectory;
fileSystem.Setup(fs => fs.Root).Returns(Environment.CurrentDirectory);
fileSystem.Setup(fs => fs.GetFullPath(It.IsAny<string>()))
.Returns<string>(p => Path.Combine(root, p));
fileSystem.Setup(fs => fs.OpenFile(It.IsAny<string>())).Returns(new MemoryStream());
}
}
public class AddDataServicePackageTests : LucenePackageRepositoryTests
{
[SetUp]
public void SetHashAlgorithm()
{
repository.HashAlgorithmName = "SHA256";
}
[Test]
public async Task DownloadAndIndex()
{
var package = new FakeDataServicePackage(new Uri("http://example.com/packages/Foo/1.0"));
fileSystem.Setup(fs => fs.GetFullPath(It.IsAny<string>())).Returns<string>(n => Path.Combine(Environment.CurrentDirectory, n));
await repository.AddPackageAsync(package, CancellationToken.None);
indexer.Verify(i => i.AddPackageAsync(It.IsAny<LucenePackage>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Test]
public async Task DownloadAndIndex_DeletesTempFile()
{
var package = new FakeDataServicePackage(new Uri("http://example.com/packages/Foo/1.0"));
fileSystem.Setup(fs => fs.GetFullPath(It.IsAny<string>())).Returns<string>(n => Path.Combine(Environment.CurrentDirectory, n));
await repository.AddPackageAsync(package, CancellationToken.None);
fileSystem.Verify(fs => fs.DeleteFile(It.IsRegex(@"\.tmp[\\/].+\.nupkg.tmp")));
}
[Test]
public async Task DenyPackageOverwrite()
{
var p = MakeSamplePackage("Foo", "1.0");
repository.LucenePackages = (new[] {p}).AsQueryable();
repository.PackageOverwriteMode = PackageOverwriteMode.Deny;
try
{
await repository.AddPackageAsync(p, CancellationToken.None);
Assert.Fail("Expected PackageOverwriteDeniedException");
}
catch (PackageOverwriteDeniedException)
{
}
indexer.Verify(i => i.AddPackageAsync(It.IsAny<LucenePackage>(), It.IsAny<CancellationToken>()), Times.Never);
}
[Test]
public async Task CancelDuringGetDownloadStream()
{
var package = new FakeDataServicePackage(new Uri("http://example.com/packages/Foo/1.0"));
packagePathResolver.Setup(r => r.GetInstallPath(package)).Returns("Foo");
packagePathResolver.Setup(r => r.GetPackageFileName(package)).Returns("Foo.1.0.nupkg");
var insideHandlerSignal = new ManualResetEventSlim(initialState: false);
var proceedFromHandlerSignal = new ManualResetEventSlim(initialState: false);
var exception = new TaskCanceledException("Fake");
repository.MessageHandler = new FakeHttpMessageHandler((req, token) =>
{
insideHandlerSignal.Set();
Assert.True(proceedFromHandlerSignal.Wait(TimeSpan.FromMilliseconds(500)), "Timeout waiting for proceedFromHandlerSignal");
if (token.IsCancellationRequested)
{
throw exception;
}
});
var cts = new CancellationTokenSource();
var cancelTask = Task.Run(() =>
{
Assert.True(insideHandlerSignal.Wait(TimeSpan.FromMilliseconds(500)), "Timeout waiting for MessageHandler.SendAsync");
cts.Cancel();
proceedFromHandlerSignal.Set();
});
try
{
await repository.AddPackageAsync(package, cts.Token);
await cancelTask;
Assert.Fail("Expected TaskCanceledException");
}
catch (TaskCanceledException ex)
{
Assert.That(ex, Is.SameAs(exception), "Expected spcific instance of TaskCanceledException");
}
}
}
private Mock<IPackage> SetUpConvertPackage()
{
var package = new Mock<IPackage>().SetupAllProperties();
package.SetupGet(p => p.Id).Returns("Sample");
package.SetupGet(p => p.Version).Returns(new SemanticVersion("1.0"));
package.SetupGet(p => p.DependencySets).Returns(new List<PackageDependencySet>());
fileSystem.Setup(fs => fs.OpenFile(It.IsAny<string>())).Returns(new MemoryStream());
package.Setup(p => p.GetStream()).Returns(new MemoryStream());
Assert.That(package.Object.Version, Is.Not.Null);
return package;
}
public class PackageWithFiles : LocalPackage
{
public IEnumerable<IPackageFile> Files { get; set; }
public PackageWithFiles()
{
DependencySets = Enumerable.Empty<PackageDependencySet>();
}
public override void ExtractContents(IFileSystem fileSystem, string extractPath)
{
}
protected sealed override IEnumerable<IPackageFile> GetFilesBase()
{
return Files ?? new IPackageFile[0];
}
public override Stream GetStream()
{
return new MemoryStream();
}
protected override IEnumerable<IPackageAssemblyReference> GetAssemblyReferencesCore()
{
return Enumerable.Empty<IPackageAssemblyReference>();
}
public override IEnumerable<FrameworkName> GetSupportedFrameworks()
{
return Enumerable.Empty<FrameworkName>();
}
}
class FakeDataServicePackage : DataServicePackage
{
public FakeDataServicePackage(Uri packageStreamUri)
{
Id = "Sample";
Version = "1.0";
var context = new Mock<IDataServiceContext>();
context.Setup(c => c.GetReadStreamUri(It.IsAny<object>())).Returns(packageStreamUri);
var prop = typeof(DataServicePackage).GetProperty("Context", BindingFlags.NonPublic | BindingFlags.Instance);
prop.SetValue(this, context.Object);
}
}
public class TestableLucenePackageRepository : LucenePackageRepository
{
public HttpMessageHandler MessageHandler { get; set; }
public TestableLucenePackageRepository(IPackagePathResolver packageResolver, IFileSystem fileSystem)
: base(packageResolver, fileSystem)
{
MessageHandler = new FakeHttpMessageHandler((req, cancel) => {});
}
protected override IPackage OpenPackage(string path)
{
return new TestPackage(Path.GetFileNameWithoutExtension(path));
}
public override IFastZipPackage LoadStagedPackage(HashingWriteStream packageStream)
{
packageStream.Close();
return new FastZipPackage
{
Id = "Sample",
Version = new SemanticVersion("1.0"),
FileLocation = packageStream.FileLocation,
Hash = packageStream.Hash
};
}
protected override Stream OpenFileWriteStream(string path)
{
return new MemoryStream();
}
protected override void MoveFileWithOverwrite(string src, string dest)
{
}
protected override System.Net.Http.HttpClient CreateHttpClient()
{
return new System.Net.Http.HttpClient(MessageHandler);
}
}
public class FakeHttpMessageHandler : HttpMessageHandler
{
private readonly Action<HttpRequestMessage, CancellationToken> onSendAsync;
public FakeHttpMessageHandler(Action<HttpRequestMessage, CancellationToken> onSendAsync)
{
this.onSendAsync = onSendAsync;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
onSendAsync(request, cancellationToken);
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("the package contents")});
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.